compiler, reflect: fix struct field names for embedded aliases
[official-gcc.git] / gcc / go / gofrontend / types.cc
blobe91922c1cac8d21a8c1d2bdc4631f0fe9c814d54
1 // types.cc -- Go frontend types.
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.
7 #include "go-system.h"
9 #include <ostream>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "operator.h"
16 #include "expressions.h"
17 #include "statements.h"
18 #include "export.h"
19 #include "import.h"
20 #include "backend.h"
21 #include "types.h"
23 // Forward declarations so that we don't have to make types.h #include
24 // backend.h.
26 static void
27 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
28 bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 std::vector<Backend::Btyped_identifier>* bfields);
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 bool use_placeholder,
38 std::vector<Backend::Btyped_identifier>* bfields);
40 // Class Type.
42 Type::Type(Type_classification classification)
43 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44 gc_symbol_var_(NULL)
48 Type::~Type()
52 // Get the base type for a type--skip names and forward declarations.
54 Type*
55 Type::base()
57 switch (this->classification_)
59 case TYPE_NAMED:
60 return this->named_type()->named_base();
61 case TYPE_FORWARD:
62 return this->forward_declaration_type()->real_type()->base();
63 default:
64 return this;
68 const Type*
69 Type::base() const
71 switch (this->classification_)
73 case TYPE_NAMED:
74 return this->named_type()->named_base();
75 case TYPE_FORWARD:
76 return this->forward_declaration_type()->real_type()->base();
77 default:
78 return this;
82 // Skip defined forward declarations.
84 Type*
85 Type::forwarded()
87 Type* t = this;
88 Forward_declaration_type* ftype = t->forward_declaration_type();
89 while (ftype != NULL && ftype->is_defined())
91 t = ftype->real_type();
92 ftype = t->forward_declaration_type();
94 return t;
97 const Type*
98 Type::forwarded() const
100 const Type* t = this;
101 const Forward_declaration_type* ftype = t->forward_declaration_type();
102 while (ftype != NULL && ftype->is_defined())
104 t = ftype->real_type();
105 ftype = t->forward_declaration_type();
107 return t;
110 // If this is a named type, return it. Otherwise, return NULL.
112 Named_type*
113 Type::named_type()
115 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
118 const Named_type*
119 Type::named_type() const
121 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
124 // Return true if this type is not defined.
126 bool
127 Type::is_undefined() const
129 return this->forwarded()->forward_declaration_type() != NULL;
132 // Return true if this is a basic type: a type which is not composed
133 // of other types, and is not void.
135 bool
136 Type::is_basic_type() const
138 switch (this->classification_)
140 case TYPE_INTEGER:
141 case TYPE_FLOAT:
142 case TYPE_COMPLEX:
143 case TYPE_BOOLEAN:
144 case TYPE_STRING:
145 case TYPE_NIL:
146 return true;
148 case TYPE_ERROR:
149 case TYPE_VOID:
150 case TYPE_FUNCTION:
151 case TYPE_POINTER:
152 case TYPE_STRUCT:
153 case TYPE_ARRAY:
154 case TYPE_MAP:
155 case TYPE_CHANNEL:
156 case TYPE_INTERFACE:
157 return false;
159 case TYPE_NAMED:
160 case TYPE_FORWARD:
161 return this->base()->is_basic_type();
163 default:
164 go_unreachable();
168 // Return true if this is an abstract type.
170 bool
171 Type::is_abstract() const
173 switch (this->classification())
175 case TYPE_INTEGER:
176 return this->integer_type()->is_abstract();
177 case TYPE_FLOAT:
178 return this->float_type()->is_abstract();
179 case TYPE_COMPLEX:
180 return this->complex_type()->is_abstract();
181 case TYPE_STRING:
182 return this->is_abstract_string_type();
183 case TYPE_BOOLEAN:
184 return this->is_abstract_boolean_type();
185 default:
186 return false;
190 // Return a non-abstract version of an abstract type.
192 Type*
193 Type::make_non_abstract_type()
195 go_assert(this->is_abstract());
196 switch (this->classification())
198 case TYPE_INTEGER:
199 if (this->integer_type()->is_rune())
200 return Type::lookup_integer_type("int32");
201 else
202 return Type::lookup_integer_type("int");
203 case TYPE_FLOAT:
204 return Type::lookup_float_type("float64");
205 case TYPE_COMPLEX:
206 return Type::lookup_complex_type("complex128");
207 case TYPE_STRING:
208 return Type::lookup_string_type();
209 case TYPE_BOOLEAN:
210 return Type::lookup_bool_type();
211 default:
212 go_unreachable();
216 // Return true if this is an error type. Don't give an error if we
217 // try to dereference an undefined forwarding type, as this is called
218 // in the parser when the type may legitimately be undefined.
220 bool
221 Type::is_error_type() const
223 const Type* t = this->forwarded();
224 // Note that we return false for an undefined forward type.
225 switch (t->classification_)
227 case TYPE_ERROR:
228 return true;
229 case TYPE_NAMED:
230 return t->named_type()->is_named_error_type();
231 default:
232 return false;
236 // If this is a pointer type, return the type to which it points.
237 // Otherwise, return NULL.
239 Type*
240 Type::points_to() const
242 const Pointer_type* ptype = this->convert<const Pointer_type,
243 TYPE_POINTER>();
244 return ptype == NULL ? NULL : ptype->points_to();
247 // Return whether this is a slice type.
249 bool
250 Type::is_slice_type() const
252 return this->array_type() != NULL && this->array_type()->length() == NULL;
255 // Return whether this is the predeclared constant nil being used as a
256 // type.
258 bool
259 Type::is_nil_constant_as_type() const
261 const Type* t = this->forwarded();
262 if (t->forward_declaration_type() != NULL)
264 const Named_object* no = t->forward_declaration_type()->named_object();
265 if (no->is_unknown())
266 no = no->unknown_value()->real_named_object();
267 if (no != NULL
268 && no->is_const()
269 && no->const_value()->expr()->is_nil_expression())
270 return true;
272 return false;
275 // Traverse a type.
278 Type::traverse(Type* type, Traverse* traverse)
280 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
281 || (traverse->traverse_mask()
282 & Traverse::traverse_expressions) != 0);
283 if (traverse->remember_type(type))
285 // We have already traversed this type.
286 return TRAVERSE_CONTINUE;
288 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
290 int t = traverse->type(type);
291 if (t == TRAVERSE_EXIT)
292 return TRAVERSE_EXIT;
293 else if (t == TRAVERSE_SKIP_COMPONENTS)
294 return TRAVERSE_CONTINUE;
296 // An array type has an expression which we need to traverse if
297 // traverse_expressions is set.
298 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
299 return TRAVERSE_EXIT;
300 return TRAVERSE_CONTINUE;
303 // Default implementation for do_traverse for child class.
306 Type::do_traverse(Traverse*)
308 return TRAVERSE_CONTINUE;
311 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
312 // then return true for all erroneous types; this is used to avoid
313 // cascading errors. If REASON is not NULL, optionally set *REASON to
314 // the reason the types are not identical.
316 bool
317 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
318 std::string* reason)
320 return Type::are_identical_cmp_tags(t1, t2, COMPARE_TAGS,
321 errors_are_identical, reason);
324 // Like are_identical, but with a CMP_TAGS parameter.
326 bool
327 Type::are_identical_cmp_tags(const Type* t1, const Type* t2, Cmp_tags cmp_tags,
328 bool errors_are_identical, std::string* reason)
330 if (t1 == NULL || t2 == NULL)
332 // Something is wrong.
333 return errors_are_identical ? true : t1 == t2;
336 // Skip defined forward declarations.
337 t1 = t1->forwarded();
338 t2 = t2->forwarded();
340 // Ignore aliases for purposes of type identity.
341 while (t1->named_type() != NULL && t1->named_type()->is_alias())
342 t1 = t1->named_type()->real_type()->forwarded();
343 while (t2->named_type() != NULL && t2->named_type()->is_alias())
344 t2 = t2->named_type()->real_type()->forwarded();
346 if (t1 == t2)
347 return true;
349 // An undefined forward declaration is an error.
350 if (t1->forward_declaration_type() != NULL
351 || t2->forward_declaration_type() != NULL)
352 return errors_are_identical;
354 // Avoid cascading errors with error types.
355 if (t1->is_error_type() || t2->is_error_type())
357 if (errors_are_identical)
358 return true;
359 return t1->is_error_type() && t2->is_error_type();
362 // Get a good reason for the sink type. Note that the sink type on
363 // the left hand side of an assignment is handled in are_assignable.
364 if (t1->is_sink_type() || t2->is_sink_type())
366 if (reason != NULL)
367 *reason = "invalid use of _";
368 return false;
371 // A named type is only identical to itself.
372 if (t1->named_type() != NULL || t2->named_type() != NULL)
373 return false;
375 // Check type shapes.
376 if (t1->classification() != t2->classification())
377 return false;
379 switch (t1->classification())
381 case TYPE_VOID:
382 case TYPE_BOOLEAN:
383 case TYPE_STRING:
384 case TYPE_NIL:
385 // These types are always identical.
386 return true;
388 case TYPE_INTEGER:
389 return t1->integer_type()->is_identical(t2->integer_type());
391 case TYPE_FLOAT:
392 return t1->float_type()->is_identical(t2->float_type());
394 case TYPE_COMPLEX:
395 return t1->complex_type()->is_identical(t2->complex_type());
397 case TYPE_FUNCTION:
398 return t1->function_type()->is_identical(t2->function_type(),
399 false,
400 cmp_tags,
401 errors_are_identical,
402 reason);
404 case TYPE_POINTER:
405 return Type::are_identical_cmp_tags(t1->points_to(), t2->points_to(),
406 cmp_tags, errors_are_identical,
407 reason);
409 case TYPE_STRUCT:
410 return t1->struct_type()->is_identical(t2->struct_type(), cmp_tags,
411 errors_are_identical);
413 case TYPE_ARRAY:
414 return t1->array_type()->is_identical(t2->array_type(), cmp_tags,
415 errors_are_identical);
417 case TYPE_MAP:
418 return t1->map_type()->is_identical(t2->map_type(), cmp_tags,
419 errors_are_identical);
421 case TYPE_CHANNEL:
422 return t1->channel_type()->is_identical(t2->channel_type(), cmp_tags,
423 errors_are_identical);
425 case TYPE_INTERFACE:
426 return t1->interface_type()->is_identical(t2->interface_type(), cmp_tags,
427 errors_are_identical);
429 case TYPE_CALL_MULTIPLE_RESULT:
430 if (reason != NULL)
431 *reason = "invalid use of multiple-value function call";
432 return false;
434 default:
435 go_unreachable();
439 // Return true if it's OK to have a binary operation with types LHS
440 // and RHS. This is not used for shifts or comparisons.
442 bool
443 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
445 if (Type::are_identical(lhs, rhs, true, NULL))
446 return true;
448 // A constant of abstract bool type may be mixed with any bool type.
449 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
450 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
451 return true;
453 // A constant of abstract string type may be mixed with any string
454 // type.
455 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
456 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
457 return true;
459 lhs = lhs->base();
460 rhs = rhs->base();
462 // A constant of abstract integer, float, or complex type may be
463 // mixed with an integer, float, or complex type.
464 if ((rhs->is_abstract()
465 && (rhs->integer_type() != NULL
466 || rhs->float_type() != NULL
467 || rhs->complex_type() != NULL)
468 && (lhs->integer_type() != NULL
469 || lhs->float_type() != NULL
470 || lhs->complex_type() != NULL))
471 || (lhs->is_abstract()
472 && (lhs->integer_type() != NULL
473 || lhs->float_type() != NULL
474 || lhs->complex_type() != NULL)
475 && (rhs->integer_type() != NULL
476 || rhs->float_type() != NULL
477 || rhs->complex_type() != NULL)))
478 return true;
480 // The nil type may be compared to a pointer, an interface type, a
481 // slice type, a channel type, a map type, or a function type.
482 if (lhs->is_nil_type()
483 && (rhs->points_to() != NULL
484 || rhs->interface_type() != NULL
485 || rhs->is_slice_type()
486 || rhs->map_type() != NULL
487 || rhs->channel_type() != NULL
488 || rhs->function_type() != NULL))
489 return true;
490 if (rhs->is_nil_type()
491 && (lhs->points_to() != NULL
492 || lhs->interface_type() != NULL
493 || lhs->is_slice_type()
494 || lhs->map_type() != NULL
495 || lhs->channel_type() != NULL
496 || lhs->function_type() != NULL))
497 return true;
499 return false;
502 // Return true if a value with type T1 may be compared with a value of
503 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
505 bool
506 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
507 const Type *t2, std::string *reason)
509 if (t1 != t2
510 && !Type::are_assignable(t1, t2, NULL)
511 && !Type::are_assignable(t2, t1, NULL))
513 if (reason != NULL)
514 *reason = "incompatible types in binary expression";
515 return false;
518 if (!is_equality_op)
520 if (t1->integer_type() == NULL
521 && t1->float_type() == NULL
522 && !t1->is_string_type())
524 if (reason != NULL)
525 *reason = _("invalid comparison of non-ordered type");
526 return false;
529 else if (t1->is_slice_type()
530 || t1->map_type() != NULL
531 || t1->function_type() != NULL
532 || t2->is_slice_type()
533 || t2->map_type() != NULL
534 || t2->function_type() != NULL)
536 if (!t1->is_nil_type() && !t2->is_nil_type())
538 if (reason != NULL)
540 if (t1->is_slice_type() || t2->is_slice_type())
541 *reason = _("slice can only be compared to nil");
542 else if (t1->map_type() != NULL || t2->map_type() != NULL)
543 *reason = _("map can only be compared to nil");
544 else
545 *reason = _("func can only be compared to nil");
547 // Match 6g error messages.
548 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
550 char buf[200];
551 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
552 reason->c_str());
553 *reason = buf;
556 return false;
559 else
561 if (!t1->is_boolean_type()
562 && t1->integer_type() == NULL
563 && t1->float_type() == NULL
564 && t1->complex_type() == NULL
565 && !t1->is_string_type()
566 && t1->points_to() == NULL
567 && t1->channel_type() == NULL
568 && t1->interface_type() == NULL
569 && t1->struct_type() == NULL
570 && t1->array_type() == NULL
571 && !t1->is_nil_type())
573 if (reason != NULL)
574 *reason = _("invalid comparison of non-comparable type");
575 return false;
578 if (t1->named_type() != NULL)
579 return t1->named_type()->named_type_is_comparable(reason);
580 else if (t2->named_type() != NULL)
581 return t2->named_type()->named_type_is_comparable(reason);
582 else if (t1->struct_type() != NULL)
584 if (t1->struct_type()->is_struct_incomparable())
586 if (reason != NULL)
587 *reason = _("invalid comparison of generated struct");
588 return false;
590 const Struct_field_list* fields = t1->struct_type()->fields();
591 for (Struct_field_list::const_iterator p = fields->begin();
592 p != fields->end();
593 ++p)
595 if (!p->type()->is_comparable())
597 if (reason != NULL)
598 *reason = _("invalid comparison of non-comparable struct");
599 return false;
603 else if (t1->array_type() != NULL)
605 if (t1->array_type()->is_array_incomparable())
607 if (reason != NULL)
608 *reason = _("invalid comparison of generated array");
609 return false;
611 if (t1->array_type()->length()->is_nil_expression()
612 || !t1->array_type()->element_type()->is_comparable())
614 if (reason != NULL)
615 *reason = _("invalid comparison of non-comparable array");
616 return false;
621 return true;
624 // Return true if a value with type RHS may be assigned to a variable
625 // with type LHS. If REASON is not NULL, set *REASON to the reason
626 // the types are not assignable.
628 bool
629 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
631 // Do some checks first. Make sure the types are defined.
632 if (rhs != NULL && !rhs->is_undefined())
634 if (rhs->is_void_type())
636 if (reason != NULL)
637 *reason = "non-value used as value";
638 return false;
640 if (rhs->is_call_multiple_result_type())
642 if (reason != NULL)
643 reason->assign(_("multiple-value function call in "
644 "single-value context"));
645 return false;
649 // Any value may be assigned to the blank identifier.
650 if (lhs != NULL
651 && !lhs->is_undefined()
652 && lhs->is_sink_type())
653 return true;
655 // Identical types are assignable.
656 if (Type::are_identical(lhs, rhs, true, reason))
657 return true;
659 // The types are assignable if they have identical underlying types
660 // and either LHS or RHS is not a named type.
661 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
662 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
663 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
664 return true;
666 // The types are assignable if LHS is an interface type and RHS
667 // implements the required methods.
668 const Interface_type* lhs_interface_type = lhs->interface_type();
669 if (lhs_interface_type != NULL)
671 if (lhs_interface_type->implements_interface(rhs, reason))
672 return true;
673 const Interface_type* rhs_interface_type = rhs->interface_type();
674 if (rhs_interface_type != NULL
675 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
676 reason))
677 return true;
680 // The type are assignable if RHS is a bidirectional channel type,
681 // LHS is a channel type, they have identical element types, and
682 // either LHS or RHS is not a named type.
683 if (lhs->channel_type() != NULL
684 && rhs->channel_type() != NULL
685 && rhs->channel_type()->may_send()
686 && rhs->channel_type()->may_receive()
687 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
688 && Type::are_identical(lhs->channel_type()->element_type(),
689 rhs->channel_type()->element_type(),
690 true,
691 reason))
692 return true;
694 // The nil type may be assigned to a pointer, function, slice, map,
695 // channel, or interface type.
696 if (rhs->is_nil_type()
697 && (lhs->points_to() != NULL
698 || lhs->function_type() != NULL
699 || lhs->is_slice_type()
700 || lhs->map_type() != NULL
701 || lhs->channel_type() != NULL
702 || lhs->interface_type() != NULL))
703 return true;
705 // An untyped numeric constant may be assigned to a numeric type if
706 // it is representable in that type.
707 if ((rhs->is_abstract()
708 && (rhs->integer_type() != NULL
709 || rhs->float_type() != NULL
710 || rhs->complex_type() != NULL))
711 && (lhs->integer_type() != NULL
712 || lhs->float_type() != NULL
713 || lhs->complex_type() != NULL))
714 return true;
716 // Give some better error messages.
717 if (reason != NULL && reason->empty())
719 if (rhs->interface_type() != NULL)
720 reason->assign(_("need explicit conversion"));
721 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
723 size_t len = (lhs->named_type()->name().length()
724 + rhs->named_type()->name().length()
725 + 100);
726 char* buf = new char[len];
727 snprintf(buf, len, _("cannot use type %s as type %s"),
728 rhs->named_type()->message_name().c_str(),
729 lhs->named_type()->message_name().c_str());
730 reason->assign(buf);
731 delete[] buf;
735 return false;
738 // Return true if a value with type RHS may be converted to type LHS.
739 // If REASON is not NULL, set *REASON to the reason the types are not
740 // convertible.
742 bool
743 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
745 // The types are convertible if they are assignable.
746 if (Type::are_assignable(lhs, rhs, reason))
747 return true;
749 // A pointer to a regular type may not be converted to a pointer to
750 // a type that may not live in the heap, except when converting from
751 // unsafe.Pointer.
752 if (lhs->points_to() != NULL
753 && rhs->points_to() != NULL
754 && !lhs->points_to()->in_heap()
755 && rhs->points_to()->in_heap()
756 && !rhs->is_unsafe_pointer_type())
758 if (reason != NULL)
759 reason->assign(_("conversion from normal type to notinheap type"));
760 return false;
763 // The types are convertible if they have identical underlying
764 // types, ignoring struct field tags.
765 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
766 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
767 true, reason))
768 return true;
770 // The types are convertible if they are both unnamed pointer types
771 // and their pointer base types have identical underlying types,
772 // ignoring struct field tags.
773 if (lhs->named_type() == NULL
774 && rhs->named_type() == NULL
775 && lhs->points_to() != NULL
776 && rhs->points_to() != NULL
777 && (lhs->points_to()->named_type() != NULL
778 || rhs->points_to()->named_type() != NULL)
779 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
780 rhs->points_to()->base(),
781 IGNORE_TAGS,
782 true,
783 reason))
784 return true;
786 // Integer and floating point types are convertible to each other.
787 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
788 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
789 return true;
791 // Complex types are convertible to each other.
792 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
793 return true;
795 // An integer, or []byte, or []rune, may be converted to a string.
796 if (lhs->is_string_type())
798 if (rhs->integer_type() != NULL)
799 return true;
800 if (rhs->is_slice_type())
802 const Type* e = rhs->array_type()->element_type()->forwarded();
803 if (e->integer_type() != NULL
804 && (e->integer_type()->is_byte()
805 || e->integer_type()->is_rune()))
806 return true;
810 // A string may be converted to []byte or []rune.
811 if (rhs->is_string_type() && lhs->is_slice_type())
813 const Type* e = lhs->array_type()->element_type()->forwarded();
814 if (e->integer_type() != NULL
815 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
816 return true;
819 // An unsafe.Pointer type may be converted to any pointer type or to
820 // a type whose underlying type is uintptr, and vice-versa.
821 if (lhs->is_unsafe_pointer_type()
822 && (rhs->points_to() != NULL
823 || (rhs->integer_type() != NULL
824 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
825 return true;
826 if (rhs->is_unsafe_pointer_type()
827 && (lhs->points_to() != NULL
828 || (lhs->integer_type() != NULL
829 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
830 return true;
832 // Give a better error message.
833 if (reason != NULL)
835 if (reason->empty())
836 *reason = "invalid type conversion";
837 else
839 std::string s = "invalid type conversion (";
840 s += *reason;
841 s += ')';
842 *reason = s;
846 return false;
849 // Return a hash code for the type to be used for method lookup.
851 unsigned int
852 Type::hash_for_method(Gogo* gogo) const
854 if (this->named_type() != NULL && this->named_type()->is_alias())
855 return this->named_type()->real_type()->hash_for_method(gogo);
856 unsigned int ret = 0;
857 if (this->classification_ != TYPE_FORWARD)
858 ret += this->classification_;
859 return ret + this->do_hash_for_method(gogo);
862 // Default implementation of do_hash_for_method. This is appropriate
863 // for types with no subfields.
865 unsigned int
866 Type::do_hash_for_method(Gogo*) const
868 return 0;
871 // Return a hash code for a string, given a starting hash.
873 unsigned int
874 Type::hash_string(const std::string& s, unsigned int h)
876 const char* p = s.data();
877 size_t len = s.length();
878 for (; len > 0; --len)
880 h ^= *p++;
881 h*= 16777619;
883 return h;
886 // A hash table mapping unnamed types to the backend representation of
887 // those types.
889 Type::Type_btypes Type::type_btypes;
891 // Return the backend representation for this type.
893 Btype*
894 Type::get_backend(Gogo* gogo)
896 if (this->btype_ != NULL)
897 return this->btype_;
899 if (this->forward_declaration_type() != NULL
900 || this->named_type() != NULL)
901 return this->get_btype_without_hash(gogo);
903 if (this->is_error_type())
904 return gogo->backend()->error_type();
906 // To avoid confusing the backend, translate all identical Go types
907 // to the same backend representation. We use a hash table to do
908 // that. There is no need to use the hash table for named types, as
909 // named types are only identical to themselves.
911 std::pair<Type*, Type_btype_entry> val;
912 val.first = this;
913 val.second.btype = NULL;
914 val.second.is_placeholder = false;
915 std::pair<Type_btypes::iterator, bool> ins =
916 Type::type_btypes.insert(val);
917 if (!ins.second && ins.first->second.btype != NULL)
919 // Note that GOGO can be NULL here, but only when the GCC
920 // middle-end is asking for a frontend type. That will only
921 // happen for simple types, which should never require
922 // placeholders.
923 if (!ins.first->second.is_placeholder)
924 this->btype_ = ins.first->second.btype;
925 else if (gogo->named_types_are_converted())
927 this->finish_backend(gogo, ins.first->second.btype);
928 ins.first->second.is_placeholder = false;
931 return ins.first->second.btype;
934 Btype* bt = this->get_btype_without_hash(gogo);
936 if (ins.first->second.btype == NULL)
938 ins.first->second.btype = bt;
939 ins.first->second.is_placeholder = false;
941 else
943 // We have already created a backend representation for this
944 // type. This can happen when an unnamed type is defined using
945 // a named type which in turns uses an identical unnamed type.
946 // Use the representation we created earlier and ignore the one we just
947 // built.
948 if (this->btype_ == bt)
949 this->btype_ = ins.first->second.btype;
950 bt = ins.first->second.btype;
953 return bt;
956 // Return the backend representation for a type without looking in the
957 // hash table for identical types. This is used for named types,
958 // since a named type is never identical to any other type.
960 Btype*
961 Type::get_btype_without_hash(Gogo* gogo)
963 if (this->btype_ == NULL)
965 Btype* bt = this->do_get_backend(gogo);
967 // For a recursive function or pointer type, we will temporarily
968 // return a circular pointer type during the recursion. We
969 // don't want to record that for a forwarding type, as it may
970 // confuse us later.
971 if (this->forward_declaration_type() != NULL
972 && gogo->backend()->is_circular_pointer_type(bt))
973 return bt;
975 if (gogo == NULL || !gogo->named_types_are_converted())
976 return bt;
978 this->btype_ = bt;
980 return this->btype_;
983 // Get the backend representation of a type without forcing the
984 // creation of the backend representation of all supporting types.
985 // This will return a backend type that has the correct size but may
986 // be incomplete. E.g., a pointer will just be a placeholder pointer,
987 // and will not contain the final representation of the type to which
988 // it points. This is used while converting all named types to the
989 // backend representation, to avoid problems with indirect references
990 // to types which are not yet complete. When this is called, the
991 // sizes of all direct references (e.g., a struct field) should be
992 // known, but the sizes of indirect references (e.g., the type to
993 // which a pointer points) may not.
995 Btype*
996 Type::get_backend_placeholder(Gogo* gogo)
998 if (gogo->named_types_are_converted())
999 return this->get_backend(gogo);
1000 if (this->btype_ != NULL)
1001 return this->btype_;
1003 Btype* bt;
1004 switch (this->classification_)
1006 case TYPE_ERROR:
1007 case TYPE_VOID:
1008 case TYPE_BOOLEAN:
1009 case TYPE_INTEGER:
1010 case TYPE_FLOAT:
1011 case TYPE_COMPLEX:
1012 case TYPE_STRING:
1013 case TYPE_NIL:
1014 // These are simple types that can just be created directly.
1015 return this->get_backend(gogo);
1017 case TYPE_MAP:
1018 case TYPE_CHANNEL:
1019 // All maps and channels have the same backend representation.
1020 return this->get_backend(gogo);
1022 case TYPE_NAMED:
1023 case TYPE_FORWARD:
1024 // Named types keep track of their own dependencies and manage
1025 // their own placeholders.
1026 return this->get_backend(gogo);
1028 case TYPE_INTERFACE:
1029 if (this->interface_type()->is_empty())
1030 return Interface_type::get_backend_empty_interface_type(gogo);
1031 break;
1033 default:
1034 break;
1037 std::pair<Type*, Type_btype_entry> val;
1038 val.first = this;
1039 val.second.btype = NULL;
1040 val.second.is_placeholder = false;
1041 std::pair<Type_btypes::iterator, bool> ins =
1042 Type::type_btypes.insert(val);
1043 if (!ins.second && ins.first->second.btype != NULL)
1044 return ins.first->second.btype;
1046 switch (this->classification_)
1048 case TYPE_FUNCTION:
1050 // A Go function type is a pointer to a struct type.
1051 Location loc = this->function_type()->location();
1052 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1054 break;
1056 case TYPE_POINTER:
1058 Location loc = Linemap::unknown_location();
1059 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1060 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1061 Type::placeholder_pointers.push_back(pt);
1063 break;
1065 case TYPE_STRUCT:
1066 // We don't have to make the struct itself be a placeholder. We
1067 // are promised that we know the sizes of the struct fields.
1068 // But we may have to use a placeholder for any particular
1069 // struct field.
1071 std::vector<Backend::Btyped_identifier> bfields;
1072 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1073 true, &bfields);
1074 bt = gogo->backend()->struct_type(bfields);
1076 break;
1078 case TYPE_ARRAY:
1079 if (this->is_slice_type())
1081 std::vector<Backend::Btyped_identifier> bfields;
1082 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1083 bt = gogo->backend()->struct_type(bfields);
1085 else
1087 Btype* element = this->array_type()->get_backend_element(gogo, true);
1088 Bexpression* len = this->array_type()->get_backend_length(gogo);
1089 bt = gogo->backend()->array_type(element, len);
1091 break;
1093 case TYPE_INTERFACE:
1095 go_assert(!this->interface_type()->is_empty());
1096 std::vector<Backend::Btyped_identifier> bfields;
1097 get_backend_interface_fields(gogo, this->interface_type(), true,
1098 &bfields);
1099 bt = gogo->backend()->struct_type(bfields);
1101 break;
1103 case TYPE_SINK:
1104 case TYPE_CALL_MULTIPLE_RESULT:
1105 /* Note that various classifications were handled in the earlier
1106 switch. */
1107 default:
1108 go_unreachable();
1111 if (ins.first->second.btype == NULL)
1113 ins.first->second.btype = bt;
1114 ins.first->second.is_placeholder = true;
1116 else
1118 // A placeholder for this type got created along the way. Use
1119 // that one and ignore the one we just built.
1120 bt = ins.first->second.btype;
1123 return bt;
1126 // Complete the backend representation. This is called for a type
1127 // using a placeholder type.
1129 void
1130 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1132 switch (this->classification_)
1134 case TYPE_ERROR:
1135 case TYPE_VOID:
1136 case TYPE_BOOLEAN:
1137 case TYPE_INTEGER:
1138 case TYPE_FLOAT:
1139 case TYPE_COMPLEX:
1140 case TYPE_STRING:
1141 case TYPE_NIL:
1142 go_unreachable();
1144 case TYPE_FUNCTION:
1146 Btype* bt = this->do_get_backend(gogo);
1147 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1148 go_assert(saw_errors());
1150 break;
1152 case TYPE_POINTER:
1154 Btype* bt = this->do_get_backend(gogo);
1155 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1156 go_assert(saw_errors());
1158 break;
1160 case TYPE_STRUCT:
1161 // The struct type itself is done, but we have to make sure that
1162 // all the field types are converted.
1163 this->struct_type()->finish_backend_fields(gogo);
1164 break;
1166 case TYPE_ARRAY:
1167 // The array type itself is done, but make sure the element type
1168 // is converted.
1169 this->array_type()->finish_backend_element(gogo);
1170 break;
1172 case TYPE_MAP:
1173 case TYPE_CHANNEL:
1174 go_unreachable();
1176 case TYPE_INTERFACE:
1177 // The interface type itself is done, but make sure the method
1178 // types are converted.
1179 this->interface_type()->finish_backend_methods(gogo);
1180 break;
1182 case TYPE_NAMED:
1183 case TYPE_FORWARD:
1184 go_unreachable();
1186 case TYPE_SINK:
1187 case TYPE_CALL_MULTIPLE_RESULT:
1188 default:
1189 go_unreachable();
1192 this->btype_ = placeholder;
1195 // Return a pointer to the type descriptor for this type.
1197 Bexpression*
1198 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1200 Type* t = this->forwarded();
1201 while (t->named_type() != NULL && t->named_type()->is_alias())
1202 t = t->named_type()->real_type()->forwarded();
1203 if (t->type_descriptor_var_ == NULL)
1205 t->make_type_descriptor_var(gogo);
1206 go_assert(t->type_descriptor_var_ != NULL);
1208 Bexpression* var_expr =
1209 gogo->backend()->var_expression(t->type_descriptor_var_,
1210 VE_rvalue, location);
1211 Bexpression* var_addr =
1212 gogo->backend()->address_expression(var_expr, location);
1213 Type* td_type = Type::make_type_descriptor_type();
1214 Btype* td_btype = td_type->get_backend(gogo);
1215 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1216 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1219 // A mapping from unnamed types to type descriptor variables.
1221 Type::Type_descriptor_vars Type::type_descriptor_vars;
1223 // Build the type descriptor for this type.
1225 void
1226 Type::make_type_descriptor_var(Gogo* gogo)
1228 go_assert(this->type_descriptor_var_ == NULL);
1230 Named_type* nt = this->named_type();
1232 // We can have multiple instances of unnamed types, but we only want
1233 // to emit the type descriptor once. We use a hash table. This is
1234 // not necessary for named types, as they are unique, and we store
1235 // the type descriptor in the type itself.
1236 Bvariable** phash = NULL;
1237 if (nt == NULL)
1239 Bvariable* bvnull = NULL;
1240 std::pair<Type_descriptor_vars::iterator, bool> ins =
1241 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1242 if (!ins.second)
1244 // We've already built a type descriptor for this type.
1245 this->type_descriptor_var_ = ins.first->second;
1246 return;
1248 phash = &ins.first->second;
1251 // The type descriptor symbol for the unsafe.Pointer type is defined in
1252 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1253 // symbol if necessary.
1254 if (this->is_unsafe_pointer_type())
1256 Location bloc = Linemap::predeclared_location();
1258 Type* td_type = Type::make_type_descriptor_type();
1259 Btype* td_btype = td_type->get_backend(gogo);
1260 const char *name = "__go_tdn_unsafe.Pointer";
1261 std::string asm_name(go_selectively_encode_id(name));
1262 this->type_descriptor_var_ =
1263 gogo->backend()->immutable_struct_reference(name, asm_name,
1264 td_btype,
1265 bloc);
1267 if (phash != NULL)
1268 *phash = this->type_descriptor_var_;
1269 return;
1272 std::string var_name = this->type_descriptor_var_name(gogo, nt);
1274 // Build the contents of the type descriptor.
1275 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1277 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1279 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1281 const Package* dummy;
1282 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1284 std::string asm_name(go_selectively_encode_id(var_name));
1285 this->type_descriptor_var_ =
1286 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1287 initializer_btype,
1288 loc);
1289 if (phash != NULL)
1290 *phash = this->type_descriptor_var_;
1291 return;
1294 // See if this type descriptor can appear in multiple packages.
1295 bool is_common = false;
1296 if (nt != NULL)
1298 // We create the descriptor for a builtin type whenever we need
1299 // it.
1300 is_common = nt->is_builtin();
1302 else
1304 // This is an unnamed type. The descriptor could be defined in
1305 // any package where it is needed, and the linker will pick one
1306 // descriptor to keep.
1307 is_common = true;
1310 // We are going to build the type descriptor in this package. We
1311 // must create the variable before we convert the initializer to the
1312 // backend representation, because the initializer may refer to the
1313 // type descriptor of this type. By setting type_descriptor_var_ we
1314 // ensure that type_descriptor_pointer will work if called while
1315 // converting INITIALIZER.
1317 std::string asm_name(go_selectively_encode_id(var_name));
1318 this->type_descriptor_var_ =
1319 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1320 initializer_btype, loc);
1321 if (phash != NULL)
1322 *phash = this->type_descriptor_var_;
1324 Translate_context context(gogo, NULL, NULL, NULL);
1325 context.set_is_const();
1326 Bexpression* binitializer = initializer->get_backend(&context);
1328 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1329 var_name, false, is_common,
1330 initializer_btype, loc,
1331 binitializer);
1334 // Return the name of the type descriptor variable. If NT is not
1335 // NULL, use it to get the name. Otherwise this is an unnamed type.
1337 std::string
1338 Type::type_descriptor_var_name(Gogo* gogo, Named_type* nt)
1340 if (nt == NULL)
1341 return "__go_td_" + this->mangled_name(gogo);
1343 Named_object* no = nt->named_object();
1344 unsigned int index;
1345 const Named_object* in_function = nt->in_function(&index);
1346 std::string ret = "__go_tdn_";
1347 if (nt->is_builtin())
1348 go_assert(in_function == NULL);
1349 else
1351 const std::string& pkgpath(no->package() == NULL
1352 ? gogo->pkgpath_symbol()
1353 : no->package()->pkgpath_symbol());
1354 ret.append(pkgpath);
1355 ret.append(1, '.');
1356 if (in_function != NULL)
1358 const Typed_identifier* rcvr =
1359 in_function->func_value()->type()->receiver();
1360 if (rcvr != NULL)
1362 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1363 ret.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1364 ret.append(1, '.');
1366 ret.append(Gogo::unpack_hidden_name(in_function->name()));
1367 ret.append(1, '.');
1368 if (index > 0)
1370 char buf[30];
1371 snprintf(buf, sizeof buf, "%u", index);
1372 ret.append(buf);
1373 ret.append(1, '.');
1378 std::string mname(Gogo::mangle_possibly_hidden_name(no->name()));
1379 ret.append(mname);
1381 return ret;
1384 // Return true if this type descriptor is defined in a different
1385 // package. If this returns true it sets *PACKAGE to the package.
1387 bool
1388 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1389 const Package** package)
1391 if (nt != NULL)
1393 if (nt->named_object()->package() != NULL)
1395 // This is a named type defined in a different package. The
1396 // type descriptor should be defined in that package.
1397 *package = nt->named_object()->package();
1398 return true;
1401 else
1403 if (this->points_to() != NULL
1404 && this->points_to()->named_type() != NULL
1405 && this->points_to()->named_type()->named_object()->package() != NULL)
1407 // This is an unnamed pointer to a named type defined in a
1408 // different package. The descriptor should be defined in
1409 // that package.
1410 *package = this->points_to()->named_type()->named_object()->package();
1411 return true;
1414 return false;
1417 // Return a composite literal for a type descriptor.
1419 Expression*
1420 Type::type_descriptor(Gogo* gogo, Type* type)
1422 return type->do_type_descriptor(gogo, NULL);
1425 // Return a composite literal for a type descriptor with a name.
1427 Expression*
1428 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1430 go_assert(name != NULL && type->named_type() != name);
1431 return type->do_type_descriptor(gogo, name);
1434 // Make a builtin struct type from a list of fields. The fields are
1435 // pairs of a name and a type.
1437 Struct_type*
1438 Type::make_builtin_struct_type(int nfields, ...)
1440 va_list ap;
1441 va_start(ap, nfields);
1443 Location bloc = Linemap::predeclared_location();
1444 Struct_field_list* sfl = new Struct_field_list();
1445 for (int i = 0; i < nfields; i++)
1447 const char* field_name = va_arg(ap, const char *);
1448 Type* type = va_arg(ap, Type*);
1449 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1452 va_end(ap);
1454 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1455 ret->set_is_struct_incomparable();
1456 return ret;
1459 // A list of builtin named types.
1461 std::vector<Named_type*> Type::named_builtin_types;
1463 // Make a builtin named type.
1465 Named_type*
1466 Type::make_builtin_named_type(const char* name, Type* type)
1468 Location bloc = Linemap::predeclared_location();
1469 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1470 Named_type* ret = no->type_value();
1471 Type::named_builtin_types.push_back(ret);
1472 return ret;
1475 // Convert the named builtin types.
1477 void
1478 Type::convert_builtin_named_types(Gogo* gogo)
1480 for (std::vector<Named_type*>::const_iterator p =
1481 Type::named_builtin_types.begin();
1482 p != Type::named_builtin_types.end();
1483 ++p)
1485 bool r = (*p)->verify();
1486 go_assert(r);
1487 (*p)->convert(gogo);
1491 // Return the type of a type descriptor. We should really tie this to
1492 // runtime.Type rather than copying it. This must match the struct "_type"
1493 // declared in libgo/go/runtime/type.go.
1495 Type*
1496 Type::make_type_descriptor_type()
1498 static Type* ret;
1499 if (ret == NULL)
1501 Location bloc = Linemap::predeclared_location();
1503 Type* uint8_type = Type::lookup_integer_type("uint8");
1504 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1505 Type* uint32_type = Type::lookup_integer_type("uint32");
1506 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1507 Type* string_type = Type::lookup_string_type();
1508 Type* pointer_string_type = Type::make_pointer_type(string_type);
1510 // This is an unnamed version of unsafe.Pointer. Perhaps we
1511 // should use the named version instead, although that would
1512 // require us to create the unsafe package if it has not been
1513 // imported. It probably doesn't matter.
1514 Type* void_type = Type::make_void_type();
1515 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1517 Typed_identifier_list *params = new Typed_identifier_list();
1518 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1519 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1521 Typed_identifier_list* results = new Typed_identifier_list();
1522 results->push_back(Typed_identifier("", uintptr_type, bloc));
1524 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1525 bloc);
1527 params = new Typed_identifier_list();
1528 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1529 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1531 results = new Typed_identifier_list();
1532 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1534 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1535 bloc);
1537 // Forward declaration for the type descriptor type.
1538 Named_object* named_type_descriptor_type =
1539 Named_object::make_type_declaration("_type", NULL, bloc);
1540 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1541 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1543 // The type of a method on a concrete type.
1544 Struct_type* method_type =
1545 Type::make_builtin_struct_type(5,
1546 "name", pointer_string_type,
1547 "pkgPath", pointer_string_type,
1548 "mtyp", pointer_type_descriptor_type,
1549 "typ", pointer_type_descriptor_type,
1550 "tfn", unsafe_pointer_type);
1551 Named_type* named_method_type =
1552 Type::make_builtin_named_type("method", method_type);
1554 // Information for types with a name or methods.
1555 Type* slice_named_method_type =
1556 Type::make_array_type(named_method_type, NULL);
1557 Struct_type* uncommon_type =
1558 Type::make_builtin_struct_type(3,
1559 "name", pointer_string_type,
1560 "pkgPath", pointer_string_type,
1561 "methods", slice_named_method_type);
1562 Named_type* named_uncommon_type =
1563 Type::make_builtin_named_type("uncommonType", uncommon_type);
1565 Type* pointer_uncommon_type =
1566 Type::make_pointer_type(named_uncommon_type);
1568 // The type descriptor type.
1570 Struct_type* type_descriptor_type =
1571 Type::make_builtin_struct_type(12,
1572 "size", uintptr_type,
1573 "ptrdata", uintptr_type,
1574 "hash", uint32_type,
1575 "kind", uint8_type,
1576 "align", uint8_type,
1577 "fieldAlign", uint8_type,
1578 "hashfn", hash_fntype,
1579 "equalfn", equal_fntype,
1580 "gcdata", pointer_uint8_type,
1581 "string", pointer_string_type,
1582 "", pointer_uncommon_type,
1583 "ptrToThis",
1584 pointer_type_descriptor_type);
1586 Named_type* named = Type::make_builtin_named_type("_type",
1587 type_descriptor_type);
1589 named_type_descriptor_type->set_type_value(named);
1591 ret = named;
1594 return ret;
1597 // Make the type of a pointer to a type descriptor as represented in
1598 // Go.
1600 Type*
1601 Type::make_type_descriptor_ptr_type()
1603 static Type* ret;
1604 if (ret == NULL)
1605 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1606 return ret;
1609 // Return the alignment required by the memequalN function. N is a
1610 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1611 // in libgo/go/runtime/alg.go.
1613 int64_t
1614 Type::memequal_align(Gogo* gogo, int size)
1616 const char* tn;
1617 switch (size)
1619 case 16:
1620 tn = "int16";
1621 break;
1622 case 32:
1623 tn = "int32";
1624 break;
1625 case 64:
1626 tn = "int64";
1627 break;
1628 case 128:
1629 // The code uses [2]int64, which must have the same alignment as
1630 // int64.
1631 tn = "int64";
1632 break;
1633 default:
1634 go_unreachable();
1637 Type* t = Type::lookup_integer_type(tn);
1639 int64_t ret;
1640 if (!t->backend_type_align(gogo, &ret))
1641 go_unreachable();
1642 return ret;
1645 // Return whether this type needs specially built type functions.
1646 // This returns true for types that are comparable and either can not
1647 // use an identity comparison, or are a non-standard size.
1649 bool
1650 Type::needs_specific_type_functions(Gogo* gogo)
1652 Named_type* nt = this->named_type();
1653 if (nt != NULL && nt->is_alias())
1654 return false;
1655 if (!this->is_comparable())
1656 return false;
1657 if (!this->compare_is_identity(gogo))
1658 return true;
1660 // We create a few predeclared types for type descriptors; they are
1661 // really just for the backend and don't need hash or equality
1662 // functions.
1663 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1664 return false;
1666 int64_t size, align;
1667 if (!this->backend_type_size(gogo, &size)
1668 || !this->backend_type_align(gogo, &align))
1670 go_assert(saw_errors());
1671 return false;
1673 // This switch matches the one in Type::type_functions.
1674 switch (size)
1676 case 0:
1677 case 1:
1678 case 2:
1679 return align < Type::memequal_align(gogo, 16);
1680 case 4:
1681 return align < Type::memequal_align(gogo, 32);
1682 case 8:
1683 return align < Type::memequal_align(gogo, 64);
1684 case 16:
1685 return align < Type::memequal_align(gogo, 128);
1686 default:
1687 return true;
1691 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1692 // hash code for this type and which compare whether two values of
1693 // this type are equal. If NAME is not NULL it is the name of this
1694 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1695 // functions, for convenience; they may be NULL.
1697 void
1698 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1699 Function_type* equal_fntype, Named_object** hash_fn,
1700 Named_object** equal_fn)
1702 // If this loop leaves NAME as NULL, then the type does not have a
1703 // name after all.
1704 while (name != NULL && name->is_alias())
1705 name = name->real_type()->named_type();
1707 if (!this->is_comparable())
1709 *hash_fn = NULL;
1710 *equal_fn = NULL;
1711 return;
1714 if (hash_fntype == NULL || equal_fntype == NULL)
1716 Location bloc = Linemap::predeclared_location();
1718 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1719 Type* void_type = Type::make_void_type();
1720 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1722 if (hash_fntype == NULL)
1724 Typed_identifier_list* params = new Typed_identifier_list();
1725 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1726 bloc));
1727 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1729 Typed_identifier_list* results = new Typed_identifier_list();
1730 results->push_back(Typed_identifier("", uintptr_type, bloc));
1732 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1734 if (equal_fntype == NULL)
1736 Typed_identifier_list* params = new Typed_identifier_list();
1737 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1738 bloc));
1739 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1740 bloc));
1742 Typed_identifier_list* results = new Typed_identifier_list();
1743 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1744 bloc));
1746 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1750 const char* hash_fnname;
1751 const char* equal_fnname;
1752 if (this->compare_is_identity(gogo))
1754 int64_t size, align;
1755 if (!this->backend_type_size(gogo, &size)
1756 || !this->backend_type_align(gogo, &align))
1758 go_assert(saw_errors());
1759 return;
1761 bool build_functions = false;
1762 // This switch matches the one in Type::needs_specific_type_functions.
1763 // The alignment tests are because of the memequal functions,
1764 // which assume that the values are aligned as required for an
1765 // integer of that size.
1766 switch (size)
1768 case 0:
1769 hash_fnname = "runtime.memhash0";
1770 equal_fnname = "runtime.memequal0";
1771 break;
1772 case 1:
1773 hash_fnname = "runtime.memhash8";
1774 equal_fnname = "runtime.memequal8";
1775 break;
1776 case 2:
1777 if (align < Type::memequal_align(gogo, 16))
1778 build_functions = true;
1779 else
1781 hash_fnname = "runtime.memhash16";
1782 equal_fnname = "runtime.memequal16";
1784 break;
1785 case 4:
1786 if (align < Type::memequal_align(gogo, 32))
1787 build_functions = true;
1788 else
1790 hash_fnname = "runtime.memhash32";
1791 equal_fnname = "runtime.memequal32";
1793 break;
1794 case 8:
1795 if (align < Type::memequal_align(gogo, 64))
1796 build_functions = true;
1797 else
1799 hash_fnname = "runtime.memhash64";
1800 equal_fnname = "runtime.memequal64";
1802 break;
1803 case 16:
1804 if (align < Type::memequal_align(gogo, 128))
1805 build_functions = true;
1806 else
1808 hash_fnname = "runtime.memhash128";
1809 equal_fnname = "runtime.memequal128";
1811 break;
1812 default:
1813 build_functions = true;
1814 break;
1816 if (build_functions)
1818 // We don't have a built-in function for a type of this size
1819 // and alignment. Build a function to use that calls the
1820 // generic hash/equality functions for identity, passing the size.
1821 this->specific_type_functions(gogo, name, size, hash_fntype,
1822 equal_fntype, hash_fn, equal_fn);
1823 return;
1826 else
1828 switch (this->base()->classification())
1830 case Type::TYPE_ERROR:
1831 case Type::TYPE_VOID:
1832 case Type::TYPE_NIL:
1833 case Type::TYPE_FUNCTION:
1834 case Type::TYPE_MAP:
1835 // For these types is_comparable should have returned false.
1836 go_unreachable();
1838 case Type::TYPE_BOOLEAN:
1839 case Type::TYPE_INTEGER:
1840 case Type::TYPE_POINTER:
1841 case Type::TYPE_CHANNEL:
1842 // For these types compare_is_identity should have returned true.
1843 go_unreachable();
1845 case Type::TYPE_FLOAT:
1846 switch (this->float_type()->bits())
1848 case 32:
1849 hash_fnname = "runtime.f32hash";
1850 equal_fnname = "runtime.f32equal";
1851 break;
1852 case 64:
1853 hash_fnname = "runtime.f64hash";
1854 equal_fnname = "runtime.f64equal";
1855 break;
1856 default:
1857 go_unreachable();
1859 break;
1861 case Type::TYPE_COMPLEX:
1862 switch (this->complex_type()->bits())
1864 case 64:
1865 hash_fnname = "runtime.c64hash";
1866 equal_fnname = "runtime.c64equal";
1867 break;
1868 case 128:
1869 hash_fnname = "runtime.c128hash";
1870 equal_fnname = "runtime.c128equal";
1871 break;
1872 default:
1873 go_unreachable();
1875 break;
1877 case Type::TYPE_STRING:
1878 hash_fnname = "runtime.strhash";
1879 equal_fnname = "runtime.strequal";
1880 break;
1882 case Type::TYPE_STRUCT:
1884 // This is a struct which can not be compared using a
1885 // simple identity function. We need to build a function
1886 // for comparison.
1887 this->specific_type_functions(gogo, name, -1, hash_fntype,
1888 equal_fntype, hash_fn, equal_fn);
1889 return;
1892 case Type::TYPE_ARRAY:
1893 if (this->is_slice_type())
1895 // Type::is_compatible_for_comparison should have
1896 // returned false.
1897 go_unreachable();
1899 else
1901 // This is an array which can not be compared using a
1902 // simple identity function. We need to build a
1903 // function for comparison.
1904 this->specific_type_functions(gogo, name, -1, hash_fntype,
1905 equal_fntype, hash_fn, equal_fn);
1906 return;
1908 break;
1910 case Type::TYPE_INTERFACE:
1911 if (this->interface_type()->is_empty())
1913 hash_fnname = "runtime.nilinterhash";
1914 equal_fnname = "runtime.nilinterequal";
1916 else
1918 hash_fnname = "runtime.interhash";
1919 equal_fnname = "runtime.interequal";
1921 break;
1923 case Type::TYPE_NAMED:
1924 case Type::TYPE_FORWARD:
1925 go_unreachable();
1927 default:
1928 go_unreachable();
1933 Location bloc = Linemap::predeclared_location();
1934 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1935 hash_fntype, bloc);
1936 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1937 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1938 equal_fntype, bloc);
1939 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1942 // A hash table mapping types to the specific hash functions.
1944 Type::Type_functions Type::type_functions_table;
1946 // Handle a type function which is specific to a type: if SIZE == -1,
1947 // this is a struct or array that can not use an identity comparison.
1948 // Otherwise, it is a type that uses an identity comparison but is not
1949 // one of the standard supported sizes.
1951 void
1952 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1953 Function_type* hash_fntype,
1954 Function_type* equal_fntype,
1955 Named_object** hash_fn,
1956 Named_object** equal_fn)
1958 Hash_equal_fn fnull(NULL, NULL);
1959 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1960 std::pair<Type_functions::iterator, bool> ins =
1961 Type::type_functions_table.insert(val);
1962 if (!ins.second)
1964 // We already have functions for this type
1965 *hash_fn = ins.first->second.first;
1966 *equal_fn = ins.first->second.second;
1967 return;
1970 std::string base_name;
1971 if (name == NULL)
1973 // Mangled names can have '.' if they happen to refer to named
1974 // types in some way. That's fine if this is simply a named
1975 // type, but otherwise it will confuse the code that builds
1976 // function identifiers. Remove '.' when necessary.
1977 base_name = this->mangled_name(gogo);
1978 size_t i;
1979 while ((i = base_name.find('.')) != std::string::npos)
1980 base_name[i] = '$';
1981 base_name = gogo->pack_hidden_name(base_name, false);
1983 else
1985 // This name is already hidden or not as appropriate.
1986 base_name = name->name();
1987 unsigned int index;
1988 const Named_object* in_function = name->in_function(&index);
1989 if (in_function != NULL)
1991 base_name.append(1, '$');
1992 const Typed_identifier* rcvr =
1993 in_function->func_value()->type()->receiver();
1994 if (rcvr != NULL)
1996 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
1997 base_name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
1998 base_name.append(1, '$');
2000 base_name.append(Gogo::unpack_hidden_name(in_function->name()));
2001 if (index > 0)
2003 char buf[30];
2004 snprintf(buf, sizeof buf, "%u", index);
2005 base_name += '$';
2006 base_name += buf;
2010 std::string hash_name = base_name + "$hash";
2011 std::string equal_name = base_name + "$equal";
2013 Location bloc = Linemap::predeclared_location();
2015 const Package* package = NULL;
2016 bool is_defined_elsewhere =
2017 this->type_descriptor_defined_elsewhere(name, &package);
2018 if (is_defined_elsewhere)
2020 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2021 hash_fntype, bloc);
2022 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2023 equal_fntype, bloc);
2025 else
2027 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2028 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2029 bloc);
2032 ins.first->second.first = *hash_fn;
2033 ins.first->second.second = *equal_fn;
2035 if (!is_defined_elsewhere)
2037 if (gogo->in_global_scope())
2038 this->write_specific_type_functions(gogo, name, size, hash_name,
2039 hash_fntype, equal_name,
2040 equal_fntype);
2041 else
2042 gogo->queue_specific_type_function(this, name, size, hash_name,
2043 hash_fntype, equal_name,
2044 equal_fntype);
2048 // Write the hash and equality functions for a type which needs to be
2049 // written specially.
2051 void
2052 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2053 const std::string& hash_name,
2054 Function_type* hash_fntype,
2055 const std::string& equal_name,
2056 Function_type* equal_fntype)
2058 Location bloc = Linemap::predeclared_location();
2060 if (gogo->specific_type_functions_are_written())
2062 go_assert(saw_errors());
2063 return;
2066 go_assert(this->is_comparable());
2068 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2069 bloc);
2070 hash_fn->func_value()->set_is_type_specific_function();
2071 gogo->start_block(bloc);
2073 if (size != -1)
2074 this->write_identity_hash(gogo, size);
2075 else if (name != NULL && name->real_type()->named_type() != NULL)
2076 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2077 else if (this->struct_type() != NULL)
2078 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2079 equal_fntype);
2080 else if (this->array_type() != NULL)
2081 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2082 equal_fntype);
2083 else
2084 go_unreachable();
2086 Block* b = gogo->finish_block(bloc);
2087 gogo->add_block(b, bloc);
2088 gogo->lower_block(hash_fn, b);
2089 gogo->finish_function(bloc);
2091 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2092 false, bloc);
2093 equal_fn->func_value()->set_is_type_specific_function();
2094 gogo->start_block(bloc);
2096 if (size != -1)
2097 this->write_identity_equal(gogo, size);
2098 else if (name != NULL && name->real_type()->named_type() != NULL)
2099 this->write_named_equal(gogo, name);
2100 else if (this->struct_type() != NULL)
2101 this->struct_type()->write_equal_function(gogo, name);
2102 else if (this->array_type() != NULL)
2103 this->array_type()->write_equal_function(gogo, name);
2104 else
2105 go_unreachable();
2107 b = gogo->finish_block(bloc);
2108 gogo->add_block(b, bloc);
2109 gogo->lower_block(equal_fn, b);
2110 gogo->finish_function(bloc);
2112 // Build the function descriptors for the type descriptor to refer to.
2113 hash_fn->func_value()->descriptor(gogo, hash_fn);
2114 equal_fn->func_value()->descriptor(gogo, equal_fn);
2117 // Write a hash function for a type that can use an identity hash but
2118 // is not one of the standard supported sizes. For example, this
2119 // would be used for the type [3]byte. This builds a return statement
2120 // that returns a call to the memhash function, passing the key and
2121 // seed from the function arguments (already constructed before this
2122 // is called), and the constant size.
2124 void
2125 Type::write_identity_hash(Gogo* gogo, int64_t size)
2127 Location bloc = Linemap::predeclared_location();
2129 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2130 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2132 Typed_identifier_list* params = new Typed_identifier_list();
2133 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2134 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2135 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2137 Typed_identifier_list* results = new Typed_identifier_list();
2138 results->push_back(Typed_identifier("", uintptr_type, bloc));
2140 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2141 results, bloc);
2143 Named_object* memhash =
2144 Named_object::make_function_declaration("runtime.memhash", NULL,
2145 memhash_fntype, bloc);
2146 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2148 Named_object* key_arg = gogo->lookup("key", NULL);
2149 go_assert(key_arg != NULL);
2150 Named_object* seed_arg = gogo->lookup("seed", NULL);
2151 go_assert(seed_arg != NULL);
2153 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2154 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2155 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2156 bloc);
2157 Expression_list* args = new Expression_list();
2158 args->push_back(key_ref);
2159 args->push_back(seed_ref);
2160 args->push_back(size_arg);
2161 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2162 Expression* call = Expression::make_call(func, args, false, bloc);
2164 Expression_list* vals = new Expression_list();
2165 vals->push_back(call);
2166 Statement* s = Statement::make_return_statement(vals, bloc);
2167 gogo->add_statement(s);
2170 // Write an equality function for a type that can use an identity
2171 // equality comparison but is not one of the standard supported sizes.
2172 // For example, this would be used for the type [3]byte. This builds
2173 // a return statement that returns a call to the memequal function,
2174 // passing the two keys from the function arguments (already
2175 // constructed before this is called), and the constant size.
2177 void
2178 Type::write_identity_equal(Gogo* gogo, int64_t size)
2180 Location bloc = Linemap::predeclared_location();
2182 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2183 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2185 Typed_identifier_list* params = new Typed_identifier_list();
2186 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2187 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2188 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2190 Typed_identifier_list* results = new Typed_identifier_list();
2191 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2193 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2194 results, bloc);
2196 Named_object* memequal =
2197 Named_object::make_function_declaration("runtime.memequal", NULL,
2198 memequal_fntype, bloc);
2199 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2201 Named_object* key1_arg = gogo->lookup("key1", NULL);
2202 go_assert(key1_arg != NULL);
2203 Named_object* key2_arg = gogo->lookup("key2", NULL);
2204 go_assert(key2_arg != NULL);
2206 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2207 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2208 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2209 bloc);
2210 Expression_list* args = new Expression_list();
2211 args->push_back(key1_ref);
2212 args->push_back(key2_ref);
2213 args->push_back(size_arg);
2214 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2215 Expression* call = Expression::make_call(func, args, false, bloc);
2217 Expression_list* vals = new Expression_list();
2218 vals->push_back(call);
2219 Statement* s = Statement::make_return_statement(vals, bloc);
2220 gogo->add_statement(s);
2223 // Write a hash function that simply calls the hash function for a
2224 // named type. This is used when one named type is defined as
2225 // another. This ensures that this case works when the other named
2226 // type is defined in another package and relies on calling hash
2227 // functions defined only in that package.
2229 void
2230 Type::write_named_hash(Gogo* gogo, Named_type* name,
2231 Function_type* hash_fntype, Function_type* equal_fntype)
2233 Location bloc = Linemap::predeclared_location();
2235 Named_type* base_type = name->real_type()->named_type();
2236 while (base_type->is_alias())
2238 base_type = base_type->real_type()->named_type();
2239 go_assert(base_type != NULL);
2241 go_assert(base_type != NULL);
2243 // The pointer to the type we are going to hash. This is an
2244 // unsafe.Pointer.
2245 Named_object* key_arg = gogo->lookup("key", NULL);
2246 go_assert(key_arg != NULL);
2248 // The seed argument to the hash function.
2249 Named_object* seed_arg = gogo->lookup("seed", NULL);
2250 go_assert(seed_arg != NULL);
2252 Named_object* hash_fn;
2253 Named_object* equal_fn;
2254 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2255 &hash_fn, &equal_fn);
2257 // Call the hash function for the base type.
2258 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2259 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2260 Expression_list* args = new Expression_list();
2261 args->push_back(key_ref);
2262 args->push_back(seed_ref);
2263 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2264 Expression* call = Expression::make_call(func, args, false, bloc);
2266 // Return the hash of the base type.
2267 Expression_list* vals = new Expression_list();
2268 vals->push_back(call);
2269 Statement* s = Statement::make_return_statement(vals, bloc);
2270 gogo->add_statement(s);
2273 // Write an equality function that simply calls the equality function
2274 // for a named type. This is used when one named type is defined as
2275 // another. This ensures that this case works when the other named
2276 // type is defined in another package and relies on calling equality
2277 // functions defined only in that package.
2279 void
2280 Type::write_named_equal(Gogo* gogo, Named_type* name)
2282 Location bloc = Linemap::predeclared_location();
2284 // The pointers to the types we are going to compare. These have
2285 // type unsafe.Pointer.
2286 Named_object* key1_arg = gogo->lookup("key1", NULL);
2287 Named_object* key2_arg = gogo->lookup("key2", NULL);
2288 go_assert(key1_arg != NULL && key2_arg != NULL);
2290 Named_type* base_type = name->real_type()->named_type();
2291 go_assert(base_type != NULL);
2293 // Build temporaries with the base type.
2294 Type* pt = Type::make_pointer_type(base_type);
2296 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2297 ref = Expression::make_cast(pt, ref, bloc);
2298 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2299 gogo->add_statement(p1);
2301 ref = Expression::make_var_reference(key2_arg, bloc);
2302 ref = Expression::make_cast(pt, ref, bloc);
2303 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2304 gogo->add_statement(p2);
2306 // Compare the values for equality.
2307 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2308 t1 = Expression::make_unary(OPERATOR_MULT, t1, bloc);
2310 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2311 t2 = Expression::make_unary(OPERATOR_MULT, t2, bloc);
2313 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2315 // Return the equality comparison.
2316 Expression_list* vals = new Expression_list();
2317 vals->push_back(cond);
2318 Statement* s = Statement::make_return_statement(vals, bloc);
2319 gogo->add_statement(s);
2322 // Return a composite literal for the type descriptor for a plain type
2323 // of kind RUNTIME_TYPE_KIND named NAME.
2325 Expression*
2326 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2327 Named_type* name, const Methods* methods,
2328 bool only_value_methods)
2330 Location bloc = Linemap::predeclared_location();
2332 Type* td_type = Type::make_type_descriptor_type();
2333 const Struct_field_list* fields = td_type->struct_type()->fields();
2335 Expression_list* vals = new Expression_list();
2336 vals->reserve(12);
2338 if (!this->has_pointer())
2339 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2340 if (this->points_to() != NULL)
2341 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2342 int64_t ptrsize;
2343 int64_t ptrdata;
2344 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2345 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2347 Struct_field_list::const_iterator p = fields->begin();
2348 go_assert(p->is_field_name("size"));
2349 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2350 vals->push_back(Expression::make_type_info(this, type_info));
2352 ++p;
2353 go_assert(p->is_field_name("ptrdata"));
2354 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2355 vals->push_back(Expression::make_type_info(this, type_info));
2357 ++p;
2358 go_assert(p->is_field_name("hash"));
2359 unsigned int h;
2360 if (name != NULL)
2361 h = name->hash_for_method(gogo);
2362 else
2363 h = this->hash_for_method(gogo);
2364 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2366 ++p;
2367 go_assert(p->is_field_name("kind"));
2368 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2369 bloc));
2371 ++p;
2372 go_assert(p->is_field_name("align"));
2373 type_info = Expression::TYPE_INFO_ALIGNMENT;
2374 vals->push_back(Expression::make_type_info(this, type_info));
2376 ++p;
2377 go_assert(p->is_field_name("fieldAlign"));
2378 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2379 vals->push_back(Expression::make_type_info(this, type_info));
2381 ++p;
2382 go_assert(p->is_field_name("hashfn"));
2383 Function_type* hash_fntype = p->type()->function_type();
2385 ++p;
2386 go_assert(p->is_field_name("equalfn"));
2387 Function_type* equal_fntype = p->type()->function_type();
2389 Named_object* hash_fn;
2390 Named_object* equal_fn;
2391 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2392 &equal_fn);
2393 if (hash_fn == NULL)
2394 vals->push_back(Expression::make_cast(hash_fntype,
2395 Expression::make_nil(bloc),
2396 bloc));
2397 else
2398 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2399 if (equal_fn == NULL)
2400 vals->push_back(Expression::make_cast(equal_fntype,
2401 Expression::make_nil(bloc),
2402 bloc));
2403 else
2404 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2406 ++p;
2407 go_assert(p->is_field_name("gcdata"));
2408 vals->push_back(Expression::make_gc_symbol(this));
2410 ++p;
2411 go_assert(p->is_field_name("string"));
2412 Expression* s = Expression::make_string((name != NULL
2413 ? name->reflection(gogo)
2414 : this->reflection(gogo)),
2415 bloc);
2416 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2418 ++p;
2419 go_assert(p->is_field_name("uncommonType"));
2420 if (name == NULL && methods == NULL)
2421 vals->push_back(Expression::make_nil(bloc));
2422 else
2424 if (methods == NULL)
2425 methods = name->methods();
2426 vals->push_back(this->uncommon_type_constructor(gogo,
2427 p->type()->deref(),
2428 name, methods,
2429 only_value_methods));
2432 ++p;
2433 go_assert(p->is_field_name("ptrToThis"));
2434 if (name == NULL && methods == NULL)
2435 vals->push_back(Expression::make_nil(bloc));
2436 else
2438 Type* pt;
2439 if (name != NULL)
2440 pt = Type::make_pointer_type(name);
2441 else
2442 pt = Type::make_pointer_type(this);
2443 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2446 ++p;
2447 go_assert(p == fields->end());
2449 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2452 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2453 // length used by the gc toolchain, and also appears in
2454 // libgo/go/reflect/type.go.
2456 static const int64_t max_ptrmask_bytes = 2048;
2458 // Return a pointer to the Garbage Collection information for this type.
2460 Bexpression*
2461 Type::gc_symbol_pointer(Gogo* gogo)
2463 Type* t = this->forwarded();
2464 while (t->named_type() != NULL && t->named_type()->is_alias())
2465 t = t->named_type()->real_type()->forwarded();
2467 if (!t->has_pointer())
2468 return gogo->backend()->nil_pointer_expression();
2470 if (t->gc_symbol_var_ == NULL)
2472 t->make_gc_symbol_var(gogo);
2473 go_assert(t->gc_symbol_var_ != NULL);
2475 Location bloc = Linemap::predeclared_location();
2476 Bexpression* var_expr =
2477 gogo->backend()->var_expression(t->gc_symbol_var_, VE_rvalue, bloc);
2478 Bexpression* addr_expr =
2479 gogo->backend()->address_expression(var_expr, bloc);
2481 Type* uint8_type = Type::lookup_integer_type("uint8");
2482 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2483 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2484 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2487 // A mapping from unnamed types to GC symbol variables.
2489 Type::GC_symbol_vars Type::gc_symbol_vars;
2491 // Build the GC symbol for this type.
2493 void
2494 Type::make_gc_symbol_var(Gogo* gogo)
2496 go_assert(this->gc_symbol_var_ == NULL);
2498 Named_type* nt = this->named_type();
2500 // We can have multiple instances of unnamed types and similar to type
2501 // descriptors, we only want to the emit the GC data once, so we use a
2502 // hash table.
2503 Bvariable** phash = NULL;
2504 if (nt == NULL)
2506 Bvariable* bvnull = NULL;
2507 std::pair<GC_symbol_vars::iterator, bool> ins =
2508 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2509 if (!ins.second)
2511 // We've already built a gc symbol for this type.
2512 this->gc_symbol_var_ = ins.first->second;
2513 return;
2515 phash = &ins.first->second;
2518 int64_t ptrsize;
2519 int64_t ptrdata;
2520 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2522 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2523 if (phash != NULL)
2524 *phash = this->gc_symbol_var_;
2525 return;
2528 std::string sym_name = this->type_descriptor_var_name(gogo, nt) + "$gc";
2530 // Build the contents of the gc symbol.
2531 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2532 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2534 // If the type descriptor for this type is defined somewhere else, so is the
2535 // GC symbol.
2536 const Package* dummy;
2537 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2539 std::string asm_name(go_selectively_encode_id(sym_name));
2540 this->gc_symbol_var_ =
2541 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2542 sym_btype);
2543 if (phash != NULL)
2544 *phash = this->gc_symbol_var_;
2545 return;
2548 // See if this gc symbol can appear in multiple packages.
2549 bool is_common = false;
2550 if (nt != NULL)
2552 // We create the symbol for a builtin type whenever we need
2553 // it.
2554 is_common = nt->is_builtin();
2556 else
2558 // This is an unnamed type. The descriptor could be defined in
2559 // any package where it is needed, and the linker will pick one
2560 // descriptor to keep.
2561 is_common = true;
2564 // Since we are building the GC symbol in this package, we must create the
2565 // variable before converting the initializer to its backend representation
2566 // because the initializer may refer to the GC symbol for this type.
2567 std::string asm_name(go_selectively_encode_id(sym_name));
2568 this->gc_symbol_var_ =
2569 gogo->backend()->implicit_variable(sym_name, asm_name,
2570 sym_btype, false, true, is_common, 0);
2571 if (phash != NULL)
2572 *phash = this->gc_symbol_var_;
2574 Translate_context context(gogo, NULL, NULL, NULL);
2575 context.set_is_const();
2576 Bexpression* sym_binit = sym_init->get_backend(&context);
2577 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2578 sym_btype, false, true, is_common,
2579 sym_binit);
2582 // Return whether this type needs a GC program, and set *PTRDATA to
2583 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2584 // pointer.
2586 bool
2587 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2589 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2590 if (!voidptr->backend_type_size(gogo, ptrsize))
2591 go_unreachable();
2593 if (!this->backend_type_ptrdata(gogo, ptrdata))
2595 go_assert(saw_errors());
2596 return false;
2599 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2602 // A simple class used to build a GC ptrmask for a type.
2604 class Ptrmask
2606 public:
2607 Ptrmask(size_t count)
2608 : bits_((count + 7) / 8, 0)
2611 void
2612 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2614 std::string
2615 symname() const;
2617 Expression*
2618 constructor(Gogo* gogo) const;
2620 private:
2621 void
2622 set(size_t index)
2623 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2625 // The actual bits.
2626 std::vector<unsigned char> bits_;
2629 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2630 // counts in bytes. PTRSIZE is the size of a pointer on the target
2631 // system.
2633 void
2634 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2636 switch (type->base()->classification())
2638 default:
2639 case Type::TYPE_NIL:
2640 case Type::TYPE_CALL_MULTIPLE_RESULT:
2641 case Type::TYPE_NAMED:
2642 case Type::TYPE_FORWARD:
2643 go_unreachable();
2645 case Type::TYPE_ERROR:
2646 case Type::TYPE_VOID:
2647 case Type::TYPE_BOOLEAN:
2648 case Type::TYPE_INTEGER:
2649 case Type::TYPE_FLOAT:
2650 case Type::TYPE_COMPLEX:
2651 case Type::TYPE_SINK:
2652 break;
2654 case Type::TYPE_FUNCTION:
2655 case Type::TYPE_POINTER:
2656 case Type::TYPE_MAP:
2657 case Type::TYPE_CHANNEL:
2658 // These types are all a single pointer.
2659 go_assert((offset % ptrsize) == 0);
2660 this->set(offset / ptrsize);
2661 break;
2663 case Type::TYPE_STRING:
2664 // A string starts with a single pointer.
2665 go_assert((offset % ptrsize) == 0);
2666 this->set(offset / ptrsize);
2667 break;
2669 case Type::TYPE_INTERFACE:
2670 // An interface is two pointers.
2671 go_assert((offset % ptrsize) == 0);
2672 this->set(offset / ptrsize);
2673 this->set((offset / ptrsize) + 1);
2674 break;
2676 case Type::TYPE_STRUCT:
2678 if (!type->has_pointer())
2679 return;
2681 const Struct_field_list* fields = type->struct_type()->fields();
2682 int64_t soffset = 0;
2683 for (Struct_field_list::const_iterator pf = fields->begin();
2684 pf != fields->end();
2685 ++pf)
2687 int64_t field_align;
2688 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2690 go_assert(saw_errors());
2691 return;
2693 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2695 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2697 int64_t field_size;
2698 if (!pf->type()->backend_type_size(gogo, &field_size))
2700 go_assert(saw_errors());
2701 return;
2703 soffset += field_size;
2706 break;
2708 case Type::TYPE_ARRAY:
2709 if (type->is_slice_type())
2711 // A slice starts with a single pointer.
2712 go_assert((offset % ptrsize) == 0);
2713 this->set(offset / ptrsize);
2714 break;
2716 else
2718 if (!type->has_pointer())
2719 return;
2721 int64_t len;
2722 if (!type->array_type()->int_length(&len))
2724 go_assert(saw_errors());
2725 return;
2728 Type* element_type = type->array_type()->element_type();
2729 int64_t ele_size;
2730 if (!element_type->backend_type_size(gogo, &ele_size))
2732 go_assert(saw_errors());
2733 return;
2736 int64_t eoffset = 0;
2737 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2738 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2739 break;
2744 // Return a symbol name for this ptrmask. This is used to coalesce
2745 // identical ptrmasks, which are common. The symbol name must use
2746 // only characters that are valid in symbols. It's nice if it's
2747 // short. We convert it to a base64 string.
2749 std::string
2750 Ptrmask::symname() const
2752 const char chars[65] =
2753 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
2754 go_assert(chars[64] == '\0');
2755 std::string ret;
2756 unsigned int b = 0;
2757 int remaining = 0;
2758 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2759 p != this->bits_.end();
2760 ++p)
2762 b |= *p << remaining;
2763 remaining += 8;
2764 while (remaining >= 6)
2766 ret += chars[b & 0x3f];
2767 b >>= 6;
2768 remaining -= 6;
2771 while (remaining > 0)
2773 ret += chars[b & 0x3f];
2774 b >>= 6;
2775 remaining -= 6;
2777 return ret;
2780 // Return a constructor for this ptrmask. This will be used to
2781 // initialize the runtime ptrmask value.
2783 Expression*
2784 Ptrmask::constructor(Gogo* gogo) const
2786 Location bloc = Linemap::predeclared_location();
2787 Type* byte_type = gogo->lookup_global("byte")->type_value();
2788 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2789 bloc);
2790 Array_type* at = Type::make_array_type(byte_type, len);
2791 Expression_list* vals = new Expression_list();
2792 vals->reserve(this->bits_.size());
2793 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2794 p != this->bits_.end();
2795 ++p)
2796 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2797 return Expression::make_array_composite_literal(at, vals, bloc);
2800 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2801 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2803 // Return a ptrmask variable for a type. For a type descriptor this
2804 // is only used for variables that are small enough to not need a
2805 // gcprog, but for a global variable this is used for a variable of
2806 // any size. PTRDATA is the number of bytes of the type that contain
2807 // pointer data. PTRSIZE is the size of a pointer on the target
2808 // system.
2810 Bvariable*
2811 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2813 Ptrmask ptrmask(ptrdata / ptrsize);
2814 if (ptrdata >= ptrsize)
2815 ptrmask.set_from(gogo, this, ptrsize, 0);
2816 else
2818 // This can happen in error cases. Just build an empty gcbits.
2819 go_assert(saw_errors());
2821 std::string sym_name = "runtime.gcbits." + ptrmask.symname();
2822 Bvariable* bvnull = NULL;
2823 std::pair<GC_gcbits_vars::iterator, bool> ins =
2824 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2825 if (!ins.second)
2827 // We've already built a GC symbol for this set of gcbits.
2828 return ins.first->second;
2831 Expression* val = ptrmask.constructor(gogo);
2832 Translate_context context(gogo, NULL, NULL, NULL);
2833 context.set_is_const();
2834 Bexpression* bval = val->get_backend(&context);
2836 std::string asm_name(go_selectively_encode_id(sym_name));
2837 Btype *btype = val->type()->get_backend(gogo);
2838 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2839 btype, false, true,
2840 true, 0);
2841 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2842 true, true, bval);
2843 ins.first->second = ret;
2844 return ret;
2847 // A GCProg is used to build a program for the garbage collector.
2848 // This is used for types with a lot of pointer data, to reduce the
2849 // size of the data in the compiled program. The program is expanded
2850 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2852 class GCProg
2854 public:
2855 GCProg()
2856 : bytes_(), index_(0), nb_(0)
2859 // The number of bits described so far.
2860 int64_t
2861 bit_index() const
2862 { return this->index_; }
2864 void
2865 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2867 void
2868 end();
2870 Expression*
2871 constructor(Gogo* gogo) const;
2873 private:
2874 void
2875 ptr(int64_t);
2877 bool
2878 should_repeat(int64_t, int64_t);
2880 void
2881 repeat(int64_t, int64_t);
2883 void
2884 zero_until(int64_t);
2886 void
2887 lit(unsigned char);
2889 void
2890 varint(int64_t);
2892 void
2893 flushlit();
2895 // Add a byte to the program.
2896 void
2897 byte(unsigned char x)
2898 { this->bytes_.push_back(x); }
2900 // The maximum number of bytes of literal bits.
2901 static const int max_literal = 127;
2903 // The program.
2904 std::vector<unsigned char> bytes_;
2905 // The index of the last bit described.
2906 int64_t index_;
2907 // The current set of literal bits.
2908 unsigned char b_[max_literal];
2909 // The current number of literal bits.
2910 int nb_;
2913 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2914 // counts in bytes. PTRSIZE is the size of a pointer on the target
2915 // system.
2917 void
2918 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2920 switch (type->base()->classification())
2922 default:
2923 case Type::TYPE_NIL:
2924 case Type::TYPE_CALL_MULTIPLE_RESULT:
2925 case Type::TYPE_NAMED:
2926 case Type::TYPE_FORWARD:
2927 go_unreachable();
2929 case Type::TYPE_ERROR:
2930 case Type::TYPE_VOID:
2931 case Type::TYPE_BOOLEAN:
2932 case Type::TYPE_INTEGER:
2933 case Type::TYPE_FLOAT:
2934 case Type::TYPE_COMPLEX:
2935 case Type::TYPE_SINK:
2936 break;
2938 case Type::TYPE_FUNCTION:
2939 case Type::TYPE_POINTER:
2940 case Type::TYPE_MAP:
2941 case Type::TYPE_CHANNEL:
2942 // These types are all a single pointer.
2943 go_assert((offset % ptrsize) == 0);
2944 this->ptr(offset / ptrsize);
2945 break;
2947 case Type::TYPE_STRING:
2948 // A string starts with a single pointer.
2949 go_assert((offset % ptrsize) == 0);
2950 this->ptr(offset / ptrsize);
2951 break;
2953 case Type::TYPE_INTERFACE:
2954 // An interface is two pointers.
2955 go_assert((offset % ptrsize) == 0);
2956 this->ptr(offset / ptrsize);
2957 this->ptr((offset / ptrsize) + 1);
2958 break;
2960 case Type::TYPE_STRUCT:
2962 if (!type->has_pointer())
2963 return;
2965 const Struct_field_list* fields = type->struct_type()->fields();
2966 int64_t soffset = 0;
2967 for (Struct_field_list::const_iterator pf = fields->begin();
2968 pf != fields->end();
2969 ++pf)
2971 int64_t field_align;
2972 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2974 go_assert(saw_errors());
2975 return;
2977 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2979 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2981 int64_t field_size;
2982 if (!pf->type()->backend_type_size(gogo, &field_size))
2984 go_assert(saw_errors());
2985 return;
2987 soffset += field_size;
2990 break;
2992 case Type::TYPE_ARRAY:
2993 if (type->is_slice_type())
2995 // A slice starts with a single pointer.
2996 go_assert((offset % ptrsize) == 0);
2997 this->ptr(offset / ptrsize);
2998 break;
3000 else
3002 if (!type->has_pointer())
3003 return;
3005 int64_t len;
3006 if (!type->array_type()->int_length(&len))
3008 go_assert(saw_errors());
3009 return;
3012 Type* element_type = type->array_type()->element_type();
3014 // Flatten array of array to a big array by multiplying counts.
3015 while (element_type->array_type() != NULL
3016 && !element_type->is_slice_type())
3018 int64_t ele_len;
3019 if (!element_type->array_type()->int_length(&ele_len))
3021 go_assert(saw_errors());
3022 return;
3025 len *= ele_len;
3026 element_type = element_type->array_type()->element_type();
3029 int64_t ele_size;
3030 if (!element_type->backend_type_size(gogo, &ele_size))
3032 go_assert(saw_errors());
3033 return;
3036 go_assert(len > 0 && ele_size > 0);
3038 if (!this->should_repeat(ele_size / ptrsize, len))
3040 // Cheaper to just emit the bits.
3041 int64_t eoffset = 0;
3042 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3043 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3045 else
3047 go_assert((offset % ptrsize) == 0);
3048 go_assert((ele_size % ptrsize) == 0);
3049 this->set_from(gogo, element_type, ptrsize, offset);
3050 this->zero_until((offset + ele_size) / ptrsize);
3051 this->repeat(ele_size / ptrsize, len - 1);
3054 break;
3059 // Emit a 1 into the bit stream of a GC program at the given bit index.
3061 void
3062 GCProg::ptr(int64_t index)
3064 go_assert(index >= this->index_);
3065 this->zero_until(index);
3066 this->lit(1);
3069 // Return whether it is worthwhile to use a repeat to describe c
3070 // elements of n bits each, compared to just emitting c copies of the
3071 // n-bit description.
3073 bool
3074 GCProg::should_repeat(int64_t n, int64_t c)
3076 // Repeat if there is more than 1 item and if the total data doesn't
3077 // fit into four bytes.
3078 return c > 1 && c * n > 4 * 8;
3081 // Emit an instruction to repeat the description of the last n words c
3082 // times (including the initial description, so c + 1 times in total).
3084 void
3085 GCProg::repeat(int64_t n, int64_t c)
3087 if (n == 0 || c == 0)
3088 return;
3089 this->flushlit();
3090 if (n < 128)
3091 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3092 else
3094 this->byte(0x80);
3095 this->varint(n);
3097 this->varint(c);
3098 this->index_ += n * c;
3101 // Add zeros to the bit stream up to the given index.
3103 void
3104 GCProg::zero_until(int64_t index)
3106 go_assert(index >= this->index_);
3107 int64_t skip = index - this->index_;
3108 if (skip == 0)
3109 return;
3110 if (skip < 4 * 8)
3112 for (int64_t i = 0; i < skip; ++i)
3113 this->lit(0);
3114 return;
3116 this->lit(0);
3117 this->flushlit();
3118 this->repeat(1, skip - 1);
3121 // Add a single literal bit to the program.
3123 void
3124 GCProg::lit(unsigned char x)
3126 if (this->nb_ == GCProg::max_literal)
3127 this->flushlit();
3128 this->b_[this->nb_] = x;
3129 ++this->nb_;
3130 ++this->index_;
3133 // Emit the varint encoding of x.
3135 void
3136 GCProg::varint(int64_t x)
3138 go_assert(x >= 0);
3139 while (x >= 0x80)
3141 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3142 x >>= 7;
3144 this->byte(static_cast<unsigned char>(x & 0x7f));
3147 // Flush any pending literal bits.
3149 void
3150 GCProg::flushlit()
3152 if (this->nb_ == 0)
3153 return;
3154 this->byte(static_cast<unsigned char>(this->nb_));
3155 unsigned char bits = 0;
3156 for (int i = 0; i < this->nb_; ++i)
3158 bits |= this->b_[i] << (i % 8);
3159 if ((i + 1) % 8 == 0)
3161 this->byte(bits);
3162 bits = 0;
3165 if (this->nb_ % 8 != 0)
3166 this->byte(bits);
3167 this->nb_ = 0;
3170 // Mark the end of a GC program.
3172 void
3173 GCProg::end()
3175 this->flushlit();
3176 this->byte(0);
3179 // Return an Expression for the bytes in a GC program.
3181 Expression*
3182 GCProg::constructor(Gogo* gogo) const
3184 Location bloc = Linemap::predeclared_location();
3186 // The first four bytes are the length of the program in target byte
3187 // order. Build a struct whose first type is uint32 to make this
3188 // work.
3190 Type* uint32_type = Type::lookup_integer_type("uint32");
3192 Type* byte_type = gogo->lookup_global("byte")->type_value();
3193 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3194 bloc);
3195 Array_type* at = Type::make_array_type(byte_type, len);
3197 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3198 "bytes", at);
3200 Expression_list* vals = new Expression_list();
3201 vals->reserve(this->bytes_.size());
3202 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3203 p != this->bytes_.end();
3204 ++p)
3205 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3206 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3208 vals = new Expression_list();
3209 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3210 bloc));
3211 vals->push_back(bytes);
3213 return Expression::make_struct_composite_literal(st, vals, bloc);
3216 // Return a composite literal for the garbage collection program for
3217 // this type. This is only used for types that are too large to use a
3218 // ptrmask.
3220 Expression*
3221 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3223 Location bloc = Linemap::predeclared_location();
3225 GCProg prog;
3226 prog.set_from(gogo, this, ptrsize, 0);
3227 int64_t offset = prog.bit_index() * ptrsize;
3228 prog.end();
3230 int64_t type_size;
3231 if (!this->backend_type_size(gogo, &type_size))
3233 go_assert(saw_errors());
3234 return Expression::make_error(bloc);
3237 go_assert(offset >= ptrdata && offset <= type_size);
3239 return prog.constructor(gogo);
3242 // Return a composite literal for the uncommon type information for
3243 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3244 // struct. If name is not NULL, it is the name of the type. If
3245 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3246 // is true if only value methods should be included. At least one of
3247 // NAME and METHODS must not be NULL.
3249 Expression*
3250 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3251 Named_type* name, const Methods* methods,
3252 bool only_value_methods) const
3254 Location bloc = Linemap::predeclared_location();
3256 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3258 Expression_list* vals = new Expression_list();
3259 vals->reserve(3);
3261 Struct_field_list::const_iterator p = fields->begin();
3262 go_assert(p->is_field_name("name"));
3264 ++p;
3265 go_assert(p->is_field_name("pkgPath"));
3267 if (name == NULL)
3269 vals->push_back(Expression::make_nil(bloc));
3270 vals->push_back(Expression::make_nil(bloc));
3272 else
3274 Named_object* no = name->named_object();
3275 std::string n = Gogo::unpack_hidden_name(no->name());
3276 Expression* s = Expression::make_string(n, bloc);
3277 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3279 if (name->is_builtin())
3280 vals->push_back(Expression::make_nil(bloc));
3281 else
3283 const Package* package = no->package();
3284 const std::string& pkgpath(package == NULL
3285 ? gogo->pkgpath()
3286 : package->pkgpath());
3287 s = Expression::make_string(pkgpath, bloc);
3288 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3292 ++p;
3293 go_assert(p->is_field_name("methods"));
3294 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3295 only_value_methods));
3297 ++p;
3298 go_assert(p == fields->end());
3300 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3301 vals, bloc);
3302 return Expression::make_unary(OPERATOR_AND, r, bloc);
3305 // Sort methods by name.
3307 class Sort_methods
3309 public:
3310 bool
3311 operator()(const std::pair<std::string, const Method*>& m1,
3312 const std::pair<std::string, const Method*>& m2) const
3314 return (Gogo::unpack_hidden_name(m1.first)
3315 < Gogo::unpack_hidden_name(m2.first));
3319 // Return a composite literal for the type method table for this type.
3320 // METHODS_TYPE is the type of the table, and is a slice type.
3321 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3322 // then only value methods are used.
3324 Expression*
3325 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3326 const Methods* methods,
3327 bool only_value_methods) const
3329 Location bloc = Linemap::predeclared_location();
3331 std::vector<std::pair<std::string, const Method*> > smethods;
3332 if (methods != NULL)
3334 smethods.reserve(methods->count());
3335 for (Methods::const_iterator p = methods->begin();
3336 p != methods->end();
3337 ++p)
3339 if (p->second->is_ambiguous())
3340 continue;
3341 if (only_value_methods && !p->second->is_value_method())
3342 continue;
3344 // This is where we implement the magic //go:nointerface
3345 // comment. If we saw that comment, we don't add this
3346 // method to the type descriptor.
3347 if (p->second->nointerface())
3348 continue;
3350 smethods.push_back(std::make_pair(p->first, p->second));
3354 if (smethods.empty())
3355 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3357 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3359 Type* method_type = methods_type->array_type()->element_type();
3361 Expression_list* vals = new Expression_list();
3362 vals->reserve(smethods.size());
3363 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3364 = smethods.begin();
3365 p != smethods.end();
3366 ++p)
3367 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3368 p->second, only_value_methods));
3370 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3373 // Return a composite literal for a single method. METHOD_TYPE is the
3374 // type of the entry. METHOD_NAME is the name of the method and M is
3375 // the method information.
3377 Expression*
3378 Type::method_constructor(Gogo*, Type* method_type,
3379 const std::string& method_name,
3380 const Method* m,
3381 bool only_value_methods) const
3383 Location bloc = Linemap::predeclared_location();
3385 const Struct_field_list* fields = method_type->struct_type()->fields();
3387 Expression_list* vals = new Expression_list();
3388 vals->reserve(5);
3390 Struct_field_list::const_iterator p = fields->begin();
3391 go_assert(p->is_field_name("name"));
3392 const std::string n = Gogo::unpack_hidden_name(method_name);
3393 Expression* s = Expression::make_string(n, bloc);
3394 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3396 ++p;
3397 go_assert(p->is_field_name("pkgPath"));
3398 if (!Gogo::is_hidden_name(method_name))
3399 vals->push_back(Expression::make_nil(bloc));
3400 else
3402 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3403 bloc);
3404 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3407 Named_object* no = (m->needs_stub_method()
3408 ? m->stub_object()
3409 : m->named_object());
3411 Function_type* mtype;
3412 if (no->is_function())
3413 mtype = no->func_value()->type();
3414 else
3415 mtype = no->func_declaration_value()->type();
3416 go_assert(mtype->is_method());
3417 Type* nonmethod_type = mtype->copy_without_receiver();
3419 ++p;
3420 go_assert(p->is_field_name("mtyp"));
3421 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3423 ++p;
3424 go_assert(p->is_field_name("typ"));
3425 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3426 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3427 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3429 ++p;
3430 go_assert(p->is_field_name("tfn"));
3431 vals->push_back(Expression::make_func_code_reference(no, bloc));
3433 ++p;
3434 go_assert(p == fields->end());
3436 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3439 // Return a composite literal for the type descriptor of a plain type.
3440 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3441 // NULL, it is the name to use as well as the list of methods.
3443 Expression*
3444 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3445 Named_type* name)
3447 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3448 name, NULL, true);
3451 // Return the type reflection string for this type.
3453 std::string
3454 Type::reflection(Gogo* gogo) const
3456 std::string ret;
3458 // The do_reflection virtual function should set RET to the
3459 // reflection string.
3460 this->do_reflection(gogo, &ret);
3462 return ret;
3465 // Return a mangled name for the type.
3467 std::string
3468 Type::mangled_name(Gogo* gogo) const
3470 std::string ret;
3472 // The do_mangled_name virtual function should set RET to the
3473 // mangled name. For a composite type it should append a code for
3474 // the composition and then call do_mangled_name on the components.
3475 this->do_mangled_name(gogo, &ret);
3477 return ret;
3480 // Return whether the backend size of the type is known.
3482 bool
3483 Type::is_backend_type_size_known(Gogo* gogo)
3485 switch (this->classification_)
3487 case TYPE_ERROR:
3488 case TYPE_VOID:
3489 case TYPE_BOOLEAN:
3490 case TYPE_INTEGER:
3491 case TYPE_FLOAT:
3492 case TYPE_COMPLEX:
3493 case TYPE_STRING:
3494 case TYPE_FUNCTION:
3495 case TYPE_POINTER:
3496 case TYPE_NIL:
3497 case TYPE_MAP:
3498 case TYPE_CHANNEL:
3499 case TYPE_INTERFACE:
3500 return true;
3502 case TYPE_STRUCT:
3504 const Struct_field_list* fields = this->struct_type()->fields();
3505 for (Struct_field_list::const_iterator pf = fields->begin();
3506 pf != fields->end();
3507 ++pf)
3508 if (!pf->type()->is_backend_type_size_known(gogo))
3509 return false;
3510 return true;
3513 case TYPE_ARRAY:
3515 const Array_type* at = this->array_type();
3516 if (at->length() == NULL)
3517 return true;
3518 else
3520 Numeric_constant nc;
3521 if (!at->length()->numeric_constant_value(&nc))
3522 return false;
3523 mpz_t ival;
3524 if (!nc.to_int(&ival))
3525 return false;
3526 mpz_clear(ival);
3527 return at->element_type()->is_backend_type_size_known(gogo);
3531 case TYPE_NAMED:
3532 this->named_type()->convert(gogo);
3533 return this->named_type()->is_named_backend_type_size_known();
3535 case TYPE_FORWARD:
3537 Forward_declaration_type* fdt = this->forward_declaration_type();
3538 return fdt->real_type()->is_backend_type_size_known(gogo);
3541 case TYPE_SINK:
3542 case TYPE_CALL_MULTIPLE_RESULT:
3543 go_unreachable();
3545 default:
3546 go_unreachable();
3550 // If the size of the type can be determined, set *PSIZE to the size
3551 // in bytes and return true. Otherwise, return false. This queries
3552 // the backend.
3554 bool
3555 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3557 if (!this->is_backend_type_size_known(gogo))
3558 return false;
3559 if (this->is_error_type())
3560 return false;
3561 Btype* bt = this->get_backend_placeholder(gogo);
3562 *psize = gogo->backend()->type_size(bt);
3563 if (*psize == -1)
3565 if (this->named_type() != NULL)
3566 go_error_at(this->named_type()->location(),
3567 "type %s larger than address space",
3568 Gogo::message_name(this->named_type()->name()).c_str());
3569 else
3570 go_error_at(Linemap::unknown_location(),
3571 "type %s larger than address space",
3572 this->reflection(gogo).c_str());
3574 // Make this an error type to avoid knock-on errors.
3575 this->classification_ = TYPE_ERROR;
3576 return false;
3578 return true;
3581 // If the alignment of the type can be determined, set *PALIGN to
3582 // the alignment in bytes and return true. Otherwise, return false.
3584 bool
3585 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3587 if (!this->is_backend_type_size_known(gogo))
3588 return false;
3589 Btype* bt = this->get_backend_placeholder(gogo);
3590 *palign = gogo->backend()->type_alignment(bt);
3591 return true;
3594 // Like backend_type_align, but return the alignment when used as a
3595 // field.
3597 bool
3598 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3600 if (!this->is_backend_type_size_known(gogo))
3601 return false;
3602 Btype* bt = this->get_backend_placeholder(gogo);
3603 *palign = gogo->backend()->type_field_alignment(bt);
3604 return true;
3607 // Get the ptrdata value for a type. This is the size of the prefix
3608 // of the type that contains all pointers. Store the ptrdata in
3609 // *PPTRDATA and return whether we found it.
3611 bool
3612 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3614 *pptrdata = 0;
3616 if (!this->has_pointer())
3617 return true;
3619 if (!this->is_backend_type_size_known(gogo))
3620 return false;
3622 switch (this->classification_)
3624 case TYPE_ERROR:
3625 return true;
3627 case TYPE_FUNCTION:
3628 case TYPE_POINTER:
3629 case TYPE_MAP:
3630 case TYPE_CHANNEL:
3631 // These types are nothing but a pointer.
3632 return this->backend_type_size(gogo, pptrdata);
3634 case TYPE_INTERFACE:
3635 // An interface is a struct of two pointers.
3636 return this->backend_type_size(gogo, pptrdata);
3638 case TYPE_STRING:
3640 // A string is a struct whose first field is a pointer, and
3641 // whose second field is not.
3642 Type* uint8_type = Type::lookup_integer_type("uint8");
3643 Type* ptr = Type::make_pointer_type(uint8_type);
3644 return ptr->backend_type_size(gogo, pptrdata);
3647 case TYPE_NAMED:
3648 case TYPE_FORWARD:
3649 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3651 case TYPE_STRUCT:
3653 const Struct_field_list* fields = this->struct_type()->fields();
3654 int64_t offset = 0;
3655 const Struct_field *ptr = NULL;
3656 int64_t ptr_offset = 0;
3657 for (Struct_field_list::const_iterator pf = fields->begin();
3658 pf != fields->end();
3659 ++pf)
3661 int64_t field_align;
3662 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3663 return false;
3664 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3666 if (pf->type()->has_pointer())
3668 ptr = &*pf;
3669 ptr_offset = offset;
3672 int64_t field_size;
3673 if (!pf->type()->backend_type_size(gogo, &field_size))
3674 return false;
3675 offset += field_size;
3678 if (ptr != NULL)
3680 int64_t ptr_ptrdata;
3681 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3682 return false;
3683 *pptrdata = ptr_offset + ptr_ptrdata;
3685 return true;
3688 case TYPE_ARRAY:
3689 if (this->is_slice_type())
3691 // A slice is a struct whose first field is a pointer, and
3692 // whose remaining fields are not.
3693 Type* element_type = this->array_type()->element_type();
3694 Type* ptr = Type::make_pointer_type(element_type);
3695 return ptr->backend_type_size(gogo, pptrdata);
3697 else
3699 Numeric_constant nc;
3700 if (!this->array_type()->length()->numeric_constant_value(&nc))
3701 return false;
3702 int64_t len;
3703 if (!nc.to_memory_size(&len))
3704 return false;
3706 Type* element_type = this->array_type()->element_type();
3707 int64_t ele_size;
3708 int64_t ele_ptrdata;
3709 if (!element_type->backend_type_size(gogo, &ele_size)
3710 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3711 return false;
3712 go_assert(ele_size > 0 && ele_ptrdata > 0);
3714 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3715 return true;
3718 default:
3719 case TYPE_VOID:
3720 case TYPE_BOOLEAN:
3721 case TYPE_INTEGER:
3722 case TYPE_FLOAT:
3723 case TYPE_COMPLEX:
3724 case TYPE_SINK:
3725 case TYPE_NIL:
3726 case TYPE_CALL_MULTIPLE_RESULT:
3727 go_unreachable();
3731 // Get the ptrdata value to store in a type descriptor. This is
3732 // normally the same as backend_type_ptrdata, but for a type that is
3733 // large enough to use a gcprog we may need to store a different value
3734 // if it ends with an array. If the gcprog uses a repeat descriptor
3735 // for the array, and if the array element ends with non-pointer data,
3736 // then the gcprog will produce a value that describes the complete
3737 // array where the backend ptrdata will omit the non-pointer elements
3738 // of the final array element. This is a subtle difference but the
3739 // run time code checks it to verify that it has expanded a gcprog as
3740 // expected.
3742 bool
3743 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3745 int64_t backend_ptrdata;
3746 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3747 return false;
3749 int64_t ptrsize;
3750 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3752 *pptrdata = backend_ptrdata;
3753 return true;
3756 GCProg prog;
3757 prog.set_from(gogo, this, ptrsize, 0);
3758 int64_t offset = prog.bit_index() * ptrsize;
3760 go_assert(offset >= backend_ptrdata);
3761 *pptrdata = offset;
3762 return true;
3765 // Default function to export a type.
3767 void
3768 Type::do_export(Export*) const
3770 go_unreachable();
3773 // Import a type.
3775 Type*
3776 Type::import_type(Import* imp)
3778 if (imp->match_c_string("("))
3779 return Function_type::do_import(imp);
3780 else if (imp->match_c_string("*"))
3781 return Pointer_type::do_import(imp);
3782 else if (imp->match_c_string("struct "))
3783 return Struct_type::do_import(imp);
3784 else if (imp->match_c_string("["))
3785 return Array_type::do_import(imp);
3786 else if (imp->match_c_string("map "))
3787 return Map_type::do_import(imp);
3788 else if (imp->match_c_string("chan "))
3789 return Channel_type::do_import(imp);
3790 else if (imp->match_c_string("interface"))
3791 return Interface_type::do_import(imp);
3792 else
3794 go_error_at(imp->location(), "import error: expected type");
3795 return Type::make_error_type();
3799 // A type used to indicate a parsing error. This exists to simplify
3800 // later error detection.
3802 class Error_type : public Type
3804 public:
3805 Error_type()
3806 : Type(TYPE_ERROR)
3809 protected:
3810 bool
3811 do_compare_is_identity(Gogo*)
3812 { return false; }
3814 Btype*
3815 do_get_backend(Gogo* gogo)
3816 { return gogo->backend()->error_type(); }
3818 Expression*
3819 do_type_descriptor(Gogo*, Named_type*)
3820 { return Expression::make_error(Linemap::predeclared_location()); }
3822 void
3823 do_reflection(Gogo*, std::string*) const
3824 { go_assert(saw_errors()); }
3826 void
3827 do_mangled_name(Gogo*, std::string* ret) const
3828 { ret->push_back('E'); }
3831 Type*
3832 Type::make_error_type()
3834 static Error_type singleton_error_type;
3835 return &singleton_error_type;
3838 // The void type.
3840 class Void_type : public Type
3842 public:
3843 Void_type()
3844 : Type(TYPE_VOID)
3847 protected:
3848 bool
3849 do_compare_is_identity(Gogo*)
3850 { return false; }
3852 Btype*
3853 do_get_backend(Gogo* gogo)
3854 { return gogo->backend()->void_type(); }
3856 Expression*
3857 do_type_descriptor(Gogo*, Named_type*)
3858 { go_unreachable(); }
3860 void
3861 do_reflection(Gogo*, std::string*) const
3864 void
3865 do_mangled_name(Gogo*, std::string* ret) const
3866 { ret->push_back('v'); }
3869 Type*
3870 Type::make_void_type()
3872 static Void_type singleton_void_type;
3873 return &singleton_void_type;
3876 // The boolean type.
3878 class Boolean_type : public Type
3880 public:
3881 Boolean_type()
3882 : Type(TYPE_BOOLEAN)
3885 protected:
3886 bool
3887 do_compare_is_identity(Gogo*)
3888 { return true; }
3890 Btype*
3891 do_get_backend(Gogo* gogo)
3892 { return gogo->backend()->bool_type(); }
3894 Expression*
3895 do_type_descriptor(Gogo*, Named_type* name);
3897 // We should not be asked for the reflection string of a basic type.
3898 void
3899 do_reflection(Gogo*, std::string* ret) const
3900 { ret->append("bool"); }
3902 void
3903 do_mangled_name(Gogo*, std::string* ret) const
3904 { ret->push_back('b'); }
3907 // Make the type descriptor.
3909 Expression*
3910 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3912 if (name != NULL)
3913 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3914 else
3916 Named_object* no = gogo->lookup_global("bool");
3917 go_assert(no != NULL);
3918 return Type::type_descriptor(gogo, no->type_value());
3922 Type*
3923 Type::make_boolean_type()
3925 static Boolean_type boolean_type;
3926 return &boolean_type;
3929 // The named type "bool".
3931 static Named_type* named_bool_type;
3933 // Get the named type "bool".
3935 Named_type*
3936 Type::lookup_bool_type()
3938 return named_bool_type;
3941 // Make the named type "bool".
3943 Named_type*
3944 Type::make_named_bool_type()
3946 Type* bool_type = Type::make_boolean_type();
3947 Named_object* named_object =
3948 Named_object::make_type("bool", NULL, bool_type,
3949 Linemap::predeclared_location());
3950 Named_type* named_type = named_object->type_value();
3951 named_bool_type = named_type;
3952 return named_type;
3955 // Class Integer_type.
3957 Integer_type::Named_integer_types Integer_type::named_integer_types;
3959 // Create a new integer type. Non-abstract integer types always have
3960 // names.
3962 Named_type*
3963 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3964 int bits, int runtime_type_kind)
3966 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3967 runtime_type_kind);
3968 std::string sname(name);
3969 Named_object* named_object =
3970 Named_object::make_type(sname, NULL, integer_type,
3971 Linemap::predeclared_location());
3972 Named_type* named_type = named_object->type_value();
3973 std::pair<Named_integer_types::iterator, bool> ins =
3974 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3975 go_assert(ins.second);
3976 return named_type;
3979 // Look up an existing integer type.
3981 Named_type*
3982 Integer_type::lookup_integer_type(const char* name)
3984 Named_integer_types::const_iterator p =
3985 Integer_type::named_integer_types.find(name);
3986 go_assert(p != Integer_type::named_integer_types.end());
3987 return p->second;
3990 // Create a new abstract integer type.
3992 Integer_type*
3993 Integer_type::create_abstract_integer_type()
3995 static Integer_type* abstract_type;
3996 if (abstract_type == NULL)
3998 Type* int_type = Type::lookup_integer_type("int");
3999 abstract_type = new Integer_type(true, false,
4000 int_type->integer_type()->bits(),
4001 RUNTIME_TYPE_KIND_INT);
4003 return abstract_type;
4006 // Create a new abstract character type.
4008 Integer_type*
4009 Integer_type::create_abstract_character_type()
4011 static Integer_type* abstract_type;
4012 if (abstract_type == NULL)
4014 abstract_type = new Integer_type(true, false, 32,
4015 RUNTIME_TYPE_KIND_INT32);
4016 abstract_type->set_is_rune();
4018 return abstract_type;
4021 // Integer type compatibility.
4023 bool
4024 Integer_type::is_identical(const Integer_type* t) const
4026 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
4027 return false;
4028 return this->is_abstract_ == t->is_abstract_;
4031 // Hash code.
4033 unsigned int
4034 Integer_type::do_hash_for_method(Gogo*) const
4036 return ((this->bits_ << 4)
4037 + ((this->is_unsigned_ ? 1 : 0) << 8)
4038 + ((this->is_abstract_ ? 1 : 0) << 9));
4041 // Convert an Integer_type to the backend representation.
4043 Btype*
4044 Integer_type::do_get_backend(Gogo* gogo)
4046 if (this->is_abstract_)
4048 go_assert(saw_errors());
4049 return gogo->backend()->error_type();
4051 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4054 // The type descriptor for an integer type. Integer types are always
4055 // named.
4057 Expression*
4058 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4060 go_assert(name != NULL || saw_errors());
4061 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4064 // We should not be asked for the reflection string of a basic type.
4066 void
4067 Integer_type::do_reflection(Gogo*, std::string*) const
4069 go_assert(saw_errors());
4072 // Mangled name.
4074 void
4075 Integer_type::do_mangled_name(Gogo*, std::string* ret) const
4077 char buf[100];
4078 snprintf(buf, sizeof buf, "i%s%s%de",
4079 this->is_abstract_ ? "a" : "",
4080 this->is_unsigned_ ? "u" : "",
4081 this->bits_);
4082 ret->append(buf);
4085 // Make an integer type.
4087 Named_type*
4088 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4089 int runtime_type_kind)
4091 return Integer_type::create_integer_type(name, is_unsigned, bits,
4092 runtime_type_kind);
4095 // Make an abstract integer type.
4097 Integer_type*
4098 Type::make_abstract_integer_type()
4100 return Integer_type::create_abstract_integer_type();
4103 // Make an abstract character type.
4105 Integer_type*
4106 Type::make_abstract_character_type()
4108 return Integer_type::create_abstract_character_type();
4111 // Look up an integer type.
4113 Named_type*
4114 Type::lookup_integer_type(const char* name)
4116 return Integer_type::lookup_integer_type(name);
4119 // Class Float_type.
4121 Float_type::Named_float_types Float_type::named_float_types;
4123 // Create a new float type. Non-abstract float types always have
4124 // names.
4126 Named_type*
4127 Float_type::create_float_type(const char* name, int bits,
4128 int runtime_type_kind)
4130 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4131 std::string sname(name);
4132 Named_object* named_object =
4133 Named_object::make_type(sname, NULL, float_type,
4134 Linemap::predeclared_location());
4135 Named_type* named_type = named_object->type_value();
4136 std::pair<Named_float_types::iterator, bool> ins =
4137 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4138 go_assert(ins.second);
4139 return named_type;
4142 // Look up an existing float type.
4144 Named_type*
4145 Float_type::lookup_float_type(const char* name)
4147 Named_float_types::const_iterator p =
4148 Float_type::named_float_types.find(name);
4149 go_assert(p != Float_type::named_float_types.end());
4150 return p->second;
4153 // Create a new abstract float type.
4155 Float_type*
4156 Float_type::create_abstract_float_type()
4158 static Float_type* abstract_type;
4159 if (abstract_type == NULL)
4160 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4161 return abstract_type;
4164 // Whether this type is identical with T.
4166 bool
4167 Float_type::is_identical(const Float_type* t) const
4169 if (this->bits_ != t->bits_)
4170 return false;
4171 return this->is_abstract_ == t->is_abstract_;
4174 // Hash code.
4176 unsigned int
4177 Float_type::do_hash_for_method(Gogo*) const
4179 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4182 // Convert to the backend representation.
4184 Btype*
4185 Float_type::do_get_backend(Gogo* gogo)
4187 return gogo->backend()->float_type(this->bits_);
4190 // The type descriptor for a float type. Float types are always named.
4192 Expression*
4193 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4195 go_assert(name != NULL || saw_errors());
4196 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4199 // We should not be asked for the reflection string of a basic type.
4201 void
4202 Float_type::do_reflection(Gogo*, std::string*) const
4204 go_assert(saw_errors());
4207 // Mangled name.
4209 void
4210 Float_type::do_mangled_name(Gogo*, std::string* ret) const
4212 char buf[100];
4213 snprintf(buf, sizeof buf, "f%s%de",
4214 this->is_abstract_ ? "a" : "",
4215 this->bits_);
4216 ret->append(buf);
4219 // Make a floating point type.
4221 Named_type*
4222 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4224 return Float_type::create_float_type(name, bits, runtime_type_kind);
4227 // Make an abstract float type.
4229 Float_type*
4230 Type::make_abstract_float_type()
4232 return Float_type::create_abstract_float_type();
4235 // Look up a float type.
4237 Named_type*
4238 Type::lookup_float_type(const char* name)
4240 return Float_type::lookup_float_type(name);
4243 // Class Complex_type.
4245 Complex_type::Named_complex_types Complex_type::named_complex_types;
4247 // Create a new complex type. Non-abstract complex types always have
4248 // names.
4250 Named_type*
4251 Complex_type::create_complex_type(const char* name, int bits,
4252 int runtime_type_kind)
4254 Complex_type* complex_type = new Complex_type(false, bits,
4255 runtime_type_kind);
4256 std::string sname(name);
4257 Named_object* named_object =
4258 Named_object::make_type(sname, NULL, complex_type,
4259 Linemap::predeclared_location());
4260 Named_type* named_type = named_object->type_value();
4261 std::pair<Named_complex_types::iterator, bool> ins =
4262 Complex_type::named_complex_types.insert(std::make_pair(sname,
4263 named_type));
4264 go_assert(ins.second);
4265 return named_type;
4268 // Look up an existing complex type.
4270 Named_type*
4271 Complex_type::lookup_complex_type(const char* name)
4273 Named_complex_types::const_iterator p =
4274 Complex_type::named_complex_types.find(name);
4275 go_assert(p != Complex_type::named_complex_types.end());
4276 return p->second;
4279 // Create a new abstract complex type.
4281 Complex_type*
4282 Complex_type::create_abstract_complex_type()
4284 static Complex_type* abstract_type;
4285 if (abstract_type == NULL)
4286 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4287 return abstract_type;
4290 // Whether this type is identical with T.
4292 bool
4293 Complex_type::is_identical(const Complex_type *t) const
4295 if (this->bits_ != t->bits_)
4296 return false;
4297 return this->is_abstract_ == t->is_abstract_;
4300 // Hash code.
4302 unsigned int
4303 Complex_type::do_hash_for_method(Gogo*) const
4305 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4308 // Convert to the backend representation.
4310 Btype*
4311 Complex_type::do_get_backend(Gogo* gogo)
4313 return gogo->backend()->complex_type(this->bits_);
4316 // The type descriptor for a complex type. Complex types are always
4317 // named.
4319 Expression*
4320 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4322 go_assert(name != NULL || saw_errors());
4323 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4326 // We should not be asked for the reflection string of a basic type.
4328 void
4329 Complex_type::do_reflection(Gogo*, std::string*) const
4331 go_assert(saw_errors());
4334 // Mangled name.
4336 void
4337 Complex_type::do_mangled_name(Gogo*, std::string* ret) const
4339 char buf[100];
4340 snprintf(buf, sizeof buf, "c%s%de",
4341 this->is_abstract_ ? "a" : "",
4342 this->bits_);
4343 ret->append(buf);
4346 // Make a complex type.
4348 Named_type*
4349 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4351 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4354 // Make an abstract complex type.
4356 Complex_type*
4357 Type::make_abstract_complex_type()
4359 return Complex_type::create_abstract_complex_type();
4362 // Look up a complex type.
4364 Named_type*
4365 Type::lookup_complex_type(const char* name)
4367 return Complex_type::lookup_complex_type(name);
4370 // Class String_type.
4372 // Convert String_type to the backend representation. A string is a
4373 // struct with two fields: a pointer to the characters and a length.
4375 Btype*
4376 String_type::do_get_backend(Gogo* gogo)
4378 static Btype* backend_string_type;
4379 if (backend_string_type == NULL)
4381 std::vector<Backend::Btyped_identifier> fields(2);
4383 Type* b = gogo->lookup_global("byte")->type_value();
4384 Type* pb = Type::make_pointer_type(b);
4386 // We aren't going to get back to this field to finish the
4387 // backend representation, so force it to be finished now.
4388 if (!gogo->named_types_are_converted())
4390 Btype* bt = pb->get_backend_placeholder(gogo);
4391 pb->finish_backend(gogo, bt);
4394 fields[0].name = "__data";
4395 fields[0].btype = pb->get_backend(gogo);
4396 fields[0].location = Linemap::predeclared_location();
4398 Type* int_type = Type::lookup_integer_type("int");
4399 fields[1].name = "__length";
4400 fields[1].btype = int_type->get_backend(gogo);
4401 fields[1].location = fields[0].location;
4403 backend_string_type = gogo->backend()->struct_type(fields);
4405 return backend_string_type;
4408 // The type descriptor for the string type.
4410 Expression*
4411 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4413 if (name != NULL)
4414 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4415 else
4417 Named_object* no = gogo->lookup_global("string");
4418 go_assert(no != NULL);
4419 return Type::type_descriptor(gogo, no->type_value());
4423 // We should not be asked for the reflection string of a basic type.
4425 void
4426 String_type::do_reflection(Gogo*, std::string* ret) const
4428 ret->append("string");
4431 // Mangled name of a string type.
4433 void
4434 String_type::do_mangled_name(Gogo*, std::string* ret) const
4436 ret->push_back('z');
4439 // Make a string type.
4441 Type*
4442 Type::make_string_type()
4444 static String_type string_type;
4445 return &string_type;
4448 // The named type "string".
4450 static Named_type* named_string_type;
4452 // Get the named type "string".
4454 Named_type*
4455 Type::lookup_string_type()
4457 return named_string_type;
4460 // Make the named type string.
4462 Named_type*
4463 Type::make_named_string_type()
4465 Type* string_type = Type::make_string_type();
4466 Named_object* named_object =
4467 Named_object::make_type("string", NULL, string_type,
4468 Linemap::predeclared_location());
4469 Named_type* named_type = named_object->type_value();
4470 named_string_type = named_type;
4471 return named_type;
4474 // The sink type. This is the type of the blank identifier _. Any
4475 // type may be assigned to it.
4477 class Sink_type : public Type
4479 public:
4480 Sink_type()
4481 : Type(TYPE_SINK)
4484 protected:
4485 bool
4486 do_compare_is_identity(Gogo*)
4487 { return false; }
4489 Btype*
4490 do_get_backend(Gogo*)
4491 { go_unreachable(); }
4493 Expression*
4494 do_type_descriptor(Gogo*, Named_type*)
4495 { go_unreachable(); }
4497 void
4498 do_reflection(Gogo*, std::string*) const
4499 { go_unreachable(); }
4501 void
4502 do_mangled_name(Gogo*, std::string*) const
4503 { go_unreachable(); }
4506 // Make the sink type.
4508 Type*
4509 Type::make_sink_type()
4511 static Sink_type sink_type;
4512 return &sink_type;
4515 // Class Function_type.
4517 // Traversal.
4520 Function_type::do_traverse(Traverse* traverse)
4522 if (this->receiver_ != NULL
4523 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4524 return TRAVERSE_EXIT;
4525 if (this->parameters_ != NULL
4526 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4527 return TRAVERSE_EXIT;
4528 if (this->results_ != NULL
4529 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4530 return TRAVERSE_EXIT;
4531 return TRAVERSE_CONTINUE;
4534 // Returns whether T is a valid redeclaration of this type. If this
4535 // returns false, and REASON is not NULL, *REASON may be set to a
4536 // brief explanation of why it returned false.
4538 bool
4539 Function_type::is_valid_redeclaration(const Function_type* t,
4540 std::string* reason) const
4542 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4543 return false;
4545 // A redeclaration of a function is required to use the same names
4546 // for the receiver and parameters.
4547 if (this->receiver() != NULL
4548 && this->receiver()->name() != t->receiver()->name())
4550 if (reason != NULL)
4551 *reason = "receiver name changed";
4552 return false;
4555 const Typed_identifier_list* parms1 = this->parameters();
4556 const Typed_identifier_list* parms2 = t->parameters();
4557 if (parms1 != NULL)
4559 Typed_identifier_list::const_iterator p1 = parms1->begin();
4560 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4561 p2 != parms2->end();
4562 ++p2, ++p1)
4564 if (p1->name() != p2->name())
4566 if (reason != NULL)
4567 *reason = "parameter name changed";
4568 return false;
4571 // This is called at parse time, so we may have unknown
4572 // types.
4573 Type* t1 = p1->type()->forwarded();
4574 Type* t2 = p2->type()->forwarded();
4575 if (t1 != t2
4576 && t1->forward_declaration_type() != NULL
4577 && (t2->forward_declaration_type() == NULL
4578 || (t1->forward_declaration_type()->named_object()
4579 != t2->forward_declaration_type()->named_object())))
4580 return false;
4584 const Typed_identifier_list* results1 = this->results();
4585 const Typed_identifier_list* results2 = t->results();
4586 if (results1 != NULL)
4588 Typed_identifier_list::const_iterator res1 = results1->begin();
4589 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4590 res2 != results2->end();
4591 ++res2, ++res1)
4593 if (res1->name() != res2->name())
4595 if (reason != NULL)
4596 *reason = "result name changed";
4597 return false;
4600 // This is called at parse time, so we may have unknown
4601 // types.
4602 Type* t1 = res1->type()->forwarded();
4603 Type* t2 = res2->type()->forwarded();
4604 if (t1 != t2
4605 && t1->forward_declaration_type() != NULL
4606 && (t2->forward_declaration_type() == NULL
4607 || (t1->forward_declaration_type()->named_object()
4608 != t2->forward_declaration_type()->named_object())))
4609 return false;
4613 return true;
4616 // Check whether T is the same as this type.
4618 bool
4619 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4620 Cmp_tags cmp_tags, bool errors_are_identical,
4621 std::string* reason) const
4623 if (!ignore_receiver)
4625 const Typed_identifier* r1 = this->receiver();
4626 const Typed_identifier* r2 = t->receiver();
4627 if ((r1 != NULL) != (r2 != NULL))
4629 if (reason != NULL)
4630 *reason = _("different receiver types");
4631 return false;
4633 if (r1 != NULL)
4635 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4636 errors_are_identical, reason))
4638 if (reason != NULL && !reason->empty())
4639 *reason = "receiver: " + *reason;
4640 return false;
4645 const Typed_identifier_list* parms1 = this->parameters();
4646 const Typed_identifier_list* parms2 = t->parameters();
4647 if ((parms1 != NULL) != (parms2 != NULL))
4649 if (reason != NULL)
4650 *reason = _("different number of parameters");
4651 return false;
4653 if (parms1 != NULL)
4655 Typed_identifier_list::const_iterator p1 = parms1->begin();
4656 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4657 p2 != parms2->end();
4658 ++p2, ++p1)
4660 if (p1 == parms1->end())
4662 if (reason != NULL)
4663 *reason = _("different number of parameters");
4664 return false;
4667 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4668 errors_are_identical, NULL))
4670 if (reason != NULL)
4671 *reason = _("different parameter types");
4672 return false;
4675 if (p1 != parms1->end())
4677 if (reason != NULL)
4678 *reason = _("different number of parameters");
4679 return false;
4683 if (this->is_varargs() != t->is_varargs())
4685 if (reason != NULL)
4686 *reason = _("different varargs");
4687 return false;
4690 const Typed_identifier_list* results1 = this->results();
4691 const Typed_identifier_list* results2 = t->results();
4692 if ((results1 != NULL) != (results2 != NULL))
4694 if (reason != NULL)
4695 *reason = _("different number of results");
4696 return false;
4698 if (results1 != NULL)
4700 Typed_identifier_list::const_iterator res1 = results1->begin();
4701 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4702 res2 != results2->end();
4703 ++res2, ++res1)
4705 if (res1 == results1->end())
4707 if (reason != NULL)
4708 *reason = _("different number of results");
4709 return false;
4712 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4713 cmp_tags, errors_are_identical,
4714 NULL))
4716 if (reason != NULL)
4717 *reason = _("different result types");
4718 return false;
4721 if (res1 != results1->end())
4723 if (reason != NULL)
4724 *reason = _("different number of results");
4725 return false;
4729 return true;
4732 // Hash code.
4734 unsigned int
4735 Function_type::do_hash_for_method(Gogo* gogo) const
4737 unsigned int ret = 0;
4738 // We ignore the receiver type for hash codes, because we need to
4739 // get the same hash code for a method in an interface and a method
4740 // declared for a type. The former will not have a receiver.
4741 if (this->parameters_ != NULL)
4743 int shift = 1;
4744 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4745 p != this->parameters_->end();
4746 ++p, ++shift)
4747 ret += p->type()->hash_for_method(gogo) << shift;
4749 if (this->results_ != NULL)
4751 int shift = 2;
4752 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4753 p != this->results_->end();
4754 ++p, ++shift)
4755 ret += p->type()->hash_for_method(gogo) << shift;
4757 if (this->is_varargs_)
4758 ret += 1;
4759 ret <<= 4;
4760 return ret;
4763 // Hash result parameters.
4765 unsigned int
4766 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4768 unsigned int hash = 0;
4769 for (Typed_identifier_list::const_iterator p = t->begin();
4770 p != t->end();
4771 ++p)
4773 hash <<= 2;
4774 hash = Type::hash_string(p->name(), hash);
4775 hash += p->type()->hash_for_method(NULL);
4777 return hash;
4780 // Compare result parameters so that can map identical result
4781 // parameters to a single struct type.
4783 bool
4784 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4785 const Typed_identifier_list* b) const
4787 if (a->size() != b->size())
4788 return false;
4789 Typed_identifier_list::const_iterator pa = a->begin();
4790 for (Typed_identifier_list::const_iterator pb = b->begin();
4791 pb != b->end();
4792 ++pa, ++pb)
4794 if (pa->name() != pb->name()
4795 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4796 return false;
4798 return true;
4801 // Hash from results to a backend struct type.
4803 Function_type::Results_structs Function_type::results_structs;
4805 // Get the backend representation for a function type.
4807 Btype*
4808 Function_type::get_backend_fntype(Gogo* gogo)
4810 if (this->fnbtype_ == NULL)
4812 Backend::Btyped_identifier breceiver;
4813 if (this->receiver_ != NULL)
4815 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4817 // We always pass the address of the receiver parameter, in
4818 // order to make interface calls work with unknown types.
4819 Type* rtype = this->receiver_->type();
4820 if (rtype->points_to() == NULL)
4821 rtype = Type::make_pointer_type(rtype);
4822 breceiver.btype = rtype->get_backend(gogo);
4823 breceiver.location = this->receiver_->location();
4826 std::vector<Backend::Btyped_identifier> bparameters;
4827 if (this->parameters_ != NULL)
4829 bparameters.resize(this->parameters_->size());
4830 size_t i = 0;
4831 for (Typed_identifier_list::const_iterator p =
4832 this->parameters_->begin(); p != this->parameters_->end();
4833 ++p, ++i)
4835 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4836 bparameters[i].btype = p->type()->get_backend(gogo);
4837 bparameters[i].location = p->location();
4839 go_assert(i == bparameters.size());
4842 std::vector<Backend::Btyped_identifier> bresults;
4843 Btype* bresult_struct = NULL;
4844 if (this->results_ != NULL)
4846 bresults.resize(this->results_->size());
4847 size_t i = 0;
4848 for (Typed_identifier_list::const_iterator p =
4849 this->results_->begin();
4850 p != this->results_->end();
4851 ++p, ++i)
4853 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4854 bresults[i].btype = p->type()->get_backend(gogo);
4855 bresults[i].location = p->location();
4857 go_assert(i == bresults.size());
4859 if (this->results_->size() > 1)
4861 // Use the same results struct for all functions that
4862 // return the same set of results. This is useful to
4863 // unify calls to interface methods with other calls.
4864 std::pair<Typed_identifier_list*, Btype*> val;
4865 val.first = this->results_;
4866 val.second = NULL;
4867 std::pair<Results_structs::iterator, bool> ins =
4868 Function_type::results_structs.insert(val);
4869 if (ins.second)
4871 // Build a new struct type.
4872 Struct_field_list* sfl = new Struct_field_list;
4873 for (Typed_identifier_list::const_iterator p =
4874 this->results_->begin();
4875 p != this->results_->end();
4876 ++p)
4878 Typed_identifier tid = *p;
4879 if (tid.name().empty())
4880 tid = Typed_identifier("UNNAMED", tid.type(),
4881 tid.location());
4882 sfl->push_back(Struct_field(tid));
4884 Struct_type* st = Type::make_struct_type(sfl,
4885 this->location());
4886 st->set_is_struct_incomparable();
4887 ins.first->second = st->get_backend(gogo);
4889 bresult_struct = ins.first->second;
4893 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4894 bresults, bresult_struct,
4895 this->location());
4899 return this->fnbtype_;
4902 // Get the backend representation for a Go function type.
4904 Btype*
4905 Function_type::do_get_backend(Gogo* gogo)
4907 // When we do anything with a function value other than call it, it
4908 // is represented as a pointer to a struct whose first field is the
4909 // actual function. So that is what we return as the type of a Go
4910 // function.
4912 Location loc = this->location();
4913 Btype* struct_type =
4914 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4915 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4917 std::vector<Backend::Btyped_identifier> fields(1);
4918 fields[0].name = "code";
4919 fields[0].btype = this->get_backend_fntype(gogo);
4920 fields[0].location = loc;
4921 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4922 return gogo->backend()->error_type();
4923 return ptr_struct_type;
4926 // The type of a function type descriptor.
4928 Type*
4929 Function_type::make_function_type_descriptor_type()
4931 static Type* ret;
4932 if (ret == NULL)
4934 Type* tdt = Type::make_type_descriptor_type();
4935 Type* ptdt = Type::make_type_descriptor_ptr_type();
4937 Type* bool_type = Type::lookup_bool_type();
4939 Type* slice_type = Type::make_array_type(ptdt, NULL);
4941 Struct_type* s = Type::make_builtin_struct_type(4,
4942 "", tdt,
4943 "dotdotdot", bool_type,
4944 "in", slice_type,
4945 "out", slice_type);
4947 ret = Type::make_builtin_named_type("FuncType", s);
4950 return ret;
4953 // The type descriptor for a function type.
4955 Expression*
4956 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4958 Location bloc = Linemap::predeclared_location();
4960 Type* ftdt = Function_type::make_function_type_descriptor_type();
4962 const Struct_field_list* fields = ftdt->struct_type()->fields();
4964 Expression_list* vals = new Expression_list();
4965 vals->reserve(4);
4967 Struct_field_list::const_iterator p = fields->begin();
4968 go_assert(p->is_field_name("_type"));
4969 vals->push_back(this->type_descriptor_constructor(gogo,
4970 RUNTIME_TYPE_KIND_FUNC,
4971 name, NULL, true));
4973 ++p;
4974 go_assert(p->is_field_name("dotdotdot"));
4975 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4977 ++p;
4978 go_assert(p->is_field_name("in"));
4979 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4980 this->parameters()));
4982 ++p;
4983 go_assert(p->is_field_name("out"));
4984 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4985 this->results()));
4987 ++p;
4988 go_assert(p == fields->end());
4990 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4993 // Return a composite literal for the parameters or results of a type
4994 // descriptor.
4996 Expression*
4997 Function_type::type_descriptor_params(Type* params_type,
4998 const Typed_identifier* receiver,
4999 const Typed_identifier_list* params)
5001 Location bloc = Linemap::predeclared_location();
5003 if (receiver == NULL && params == NULL)
5004 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
5006 Expression_list* vals = new Expression_list();
5007 vals->reserve((params == NULL ? 0 : params->size())
5008 + (receiver != NULL ? 1 : 0));
5010 if (receiver != NULL)
5011 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
5013 if (params != NULL)
5015 for (Typed_identifier_list::const_iterator p = params->begin();
5016 p != params->end();
5017 ++p)
5018 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
5021 return Expression::make_slice_composite_literal(params_type, vals, bloc);
5024 // The reflection string.
5026 void
5027 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
5029 // FIXME: Turn this off until we straighten out the type of the
5030 // struct field used in a go statement which calls a method.
5031 // go_assert(this->receiver_ == NULL);
5033 ret->append("func");
5035 if (this->receiver_ != NULL)
5037 ret->push_back('(');
5038 this->append_reflection(this->receiver_->type(), gogo, ret);
5039 ret->push_back(')');
5042 ret->push_back('(');
5043 const Typed_identifier_list* params = this->parameters();
5044 if (params != NULL)
5046 bool is_varargs = this->is_varargs_;
5047 for (Typed_identifier_list::const_iterator p = params->begin();
5048 p != params->end();
5049 ++p)
5051 if (p != params->begin())
5052 ret->append(", ");
5053 if (!is_varargs || p + 1 != params->end())
5054 this->append_reflection(p->type(), gogo, ret);
5055 else
5057 ret->append("...");
5058 this->append_reflection(p->type()->array_type()->element_type(),
5059 gogo, ret);
5063 ret->push_back(')');
5065 const Typed_identifier_list* results = this->results();
5066 if (results != NULL && !results->empty())
5068 if (results->size() == 1)
5069 ret->push_back(' ');
5070 else
5071 ret->append(" (");
5072 for (Typed_identifier_list::const_iterator p = results->begin();
5073 p != results->end();
5074 ++p)
5076 if (p != results->begin())
5077 ret->append(", ");
5078 this->append_reflection(p->type(), gogo, ret);
5080 if (results->size() > 1)
5081 ret->push_back(')');
5085 // Mangled name.
5087 void
5088 Function_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5090 ret->push_back('F');
5092 if (this->receiver_ != NULL)
5094 ret->push_back('m');
5095 this->append_mangled_name(this->receiver_->type(), gogo, ret);
5098 const Typed_identifier_list* params = this->parameters();
5099 if (params != NULL)
5101 ret->push_back('p');
5102 for (Typed_identifier_list::const_iterator p = params->begin();
5103 p != params->end();
5104 ++p)
5105 this->append_mangled_name(p->type(), gogo, ret);
5106 if (this->is_varargs_)
5107 ret->push_back('V');
5108 ret->push_back('e');
5111 const Typed_identifier_list* results = this->results();
5112 if (results != NULL)
5114 ret->push_back('r');
5115 for (Typed_identifier_list::const_iterator p = results->begin();
5116 p != results->end();
5117 ++p)
5118 this->append_mangled_name(p->type(), gogo, ret);
5119 ret->push_back('e');
5122 ret->push_back('e');
5125 // Export a function type.
5127 void
5128 Function_type::do_export(Export* exp) const
5130 // We don't write out the receiver. The only function types which
5131 // should have a receiver are the ones associated with explicitly
5132 // defined methods. For those the receiver type is written out by
5133 // Function::export_func.
5135 exp->write_c_string("(");
5136 bool first = true;
5137 if (this->parameters_ != NULL)
5139 bool is_varargs = this->is_varargs_;
5140 for (Typed_identifier_list::const_iterator p =
5141 this->parameters_->begin();
5142 p != this->parameters_->end();
5143 ++p)
5145 if (first)
5146 first = false;
5147 else
5148 exp->write_c_string(", ");
5149 exp->write_name(p->name());
5150 exp->write_c_string(" ");
5151 if (!is_varargs || p + 1 != this->parameters_->end())
5152 exp->write_type(p->type());
5153 else
5155 exp->write_c_string("...");
5156 exp->write_type(p->type()->array_type()->element_type());
5160 exp->write_c_string(")");
5162 const Typed_identifier_list* results = this->results_;
5163 if (results != NULL)
5165 exp->write_c_string(" ");
5166 if (results->size() == 1 && results->begin()->name().empty())
5167 exp->write_type(results->begin()->type());
5168 else
5170 first = true;
5171 exp->write_c_string("(");
5172 for (Typed_identifier_list::const_iterator p = results->begin();
5173 p != results->end();
5174 ++p)
5176 if (first)
5177 first = false;
5178 else
5179 exp->write_c_string(", ");
5180 exp->write_name(p->name());
5181 exp->write_c_string(" ");
5182 exp->write_type(p->type());
5184 exp->write_c_string(")");
5189 // Import a function type.
5191 Function_type*
5192 Function_type::do_import(Import* imp)
5194 imp->require_c_string("(");
5195 Typed_identifier_list* parameters;
5196 bool is_varargs = false;
5197 if (imp->peek_char() == ')')
5198 parameters = NULL;
5199 else
5201 parameters = new Typed_identifier_list();
5202 while (true)
5204 std::string name = imp->read_name();
5205 imp->require_c_string(" ");
5207 if (imp->match_c_string("..."))
5209 imp->advance(3);
5210 is_varargs = true;
5213 Type* ptype = imp->read_type();
5214 if (is_varargs)
5215 ptype = Type::make_array_type(ptype, NULL);
5216 parameters->push_back(Typed_identifier(name, ptype,
5217 imp->location()));
5218 if (imp->peek_char() != ',')
5219 break;
5220 go_assert(!is_varargs);
5221 imp->require_c_string(", ");
5224 imp->require_c_string(")");
5226 Typed_identifier_list* results;
5227 if (imp->peek_char() != ' ')
5228 results = NULL;
5229 else
5231 imp->advance(1);
5232 results = new Typed_identifier_list;
5233 if (imp->peek_char() != '(')
5235 Type* rtype = imp->read_type();
5236 results->push_back(Typed_identifier("", rtype, imp->location()));
5238 else
5240 imp->advance(1);
5241 while (true)
5243 std::string name = imp->read_name();
5244 imp->require_c_string(" ");
5245 Type* rtype = imp->read_type();
5246 results->push_back(Typed_identifier(name, rtype,
5247 imp->location()));
5248 if (imp->peek_char() != ',')
5249 break;
5250 imp->require_c_string(", ");
5252 imp->require_c_string(")");
5256 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5257 imp->location());
5258 if (is_varargs)
5259 ret->set_is_varargs();
5260 return ret;
5263 // Make a copy of a function type without a receiver.
5265 Function_type*
5266 Function_type::copy_without_receiver() const
5268 go_assert(this->is_method());
5269 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5270 this->results_,
5271 this->location_);
5272 if (this->is_varargs())
5273 ret->set_is_varargs();
5274 if (this->is_builtin())
5275 ret->set_is_builtin();
5276 return ret;
5279 // Make a copy of a function type with a receiver.
5281 Function_type*
5282 Function_type::copy_with_receiver(Type* receiver_type) const
5284 go_assert(!this->is_method());
5285 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5286 this->location_);
5287 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5288 this->results_,
5289 this->location_);
5290 if (this->is_varargs_)
5291 ret->set_is_varargs();
5292 return ret;
5295 // Make a copy of a function type with the receiver as the first
5296 // parameter.
5298 Function_type*
5299 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5301 go_assert(this->is_method());
5302 Typed_identifier_list* new_params = new Typed_identifier_list();
5303 Type* rtype = this->receiver_->type();
5304 if (want_pointer_receiver)
5305 rtype = Type::make_pointer_type(rtype);
5306 Typed_identifier receiver(this->receiver_->name(), rtype,
5307 this->receiver_->location());
5308 new_params->push_back(receiver);
5309 const Typed_identifier_list* orig_params = this->parameters_;
5310 if (orig_params != NULL && !orig_params->empty())
5312 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5313 p != orig_params->end();
5314 ++p)
5315 new_params->push_back(*p);
5317 return Type::make_function_type(NULL, new_params, this->results_,
5318 this->location_);
5321 // Make a copy of a function type ignoring any receiver and adding a
5322 // closure parameter.
5324 Function_type*
5325 Function_type::copy_with_names() const
5327 Typed_identifier_list* new_params = new Typed_identifier_list();
5328 const Typed_identifier_list* orig_params = this->parameters_;
5329 if (orig_params != NULL && !orig_params->empty())
5331 static int count;
5332 char buf[50];
5333 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5334 p != orig_params->end();
5335 ++p)
5337 snprintf(buf, sizeof buf, "pt.%u", count);
5338 ++count;
5339 new_params->push_back(Typed_identifier(buf, p->type(),
5340 p->location()));
5344 const Typed_identifier_list* orig_results = this->results_;
5345 Typed_identifier_list* new_results;
5346 if (orig_results == NULL || orig_results->empty())
5347 new_results = NULL;
5348 else
5350 new_results = new Typed_identifier_list();
5351 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5352 p != orig_results->end();
5353 ++p)
5354 new_results->push_back(Typed_identifier("", p->type(),
5355 p->location()));
5358 return Type::make_function_type(NULL, new_params, new_results,
5359 this->location());
5362 // Make a function type.
5364 Function_type*
5365 Type::make_function_type(Typed_identifier* receiver,
5366 Typed_identifier_list* parameters,
5367 Typed_identifier_list* results,
5368 Location location)
5370 return new Function_type(receiver, parameters, results, location);
5373 // Make a backend function type.
5375 Backend_function_type*
5376 Type::make_backend_function_type(Typed_identifier* receiver,
5377 Typed_identifier_list* parameters,
5378 Typed_identifier_list* results,
5379 Location location)
5381 return new Backend_function_type(receiver, parameters, results, location);
5384 // Class Pointer_type.
5386 // Traversal.
5389 Pointer_type::do_traverse(Traverse* traverse)
5391 return Type::traverse(this->to_type_, traverse);
5394 // Hash code.
5396 unsigned int
5397 Pointer_type::do_hash_for_method(Gogo* gogo) const
5399 return this->to_type_->hash_for_method(gogo) << 4;
5402 // Get the backend representation for a pointer type.
5404 Btype*
5405 Pointer_type::do_get_backend(Gogo* gogo)
5407 Btype* to_btype = this->to_type_->get_backend(gogo);
5408 return gogo->backend()->pointer_type(to_btype);
5411 // The type of a pointer type descriptor.
5413 Type*
5414 Pointer_type::make_pointer_type_descriptor_type()
5416 static Type* ret;
5417 if (ret == NULL)
5419 Type* tdt = Type::make_type_descriptor_type();
5420 Type* ptdt = Type::make_type_descriptor_ptr_type();
5422 Struct_type* s = Type::make_builtin_struct_type(2,
5423 "", tdt,
5424 "elem", ptdt);
5426 ret = Type::make_builtin_named_type("PtrType", s);
5429 return ret;
5432 // The type descriptor for a pointer type.
5434 Expression*
5435 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5437 if (this->is_unsafe_pointer_type())
5439 go_assert(name != NULL);
5440 return this->plain_type_descriptor(gogo,
5441 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5442 name);
5444 else
5446 Location bloc = Linemap::predeclared_location();
5448 const Methods* methods;
5449 Type* deref = this->points_to();
5450 if (deref->named_type() != NULL)
5451 methods = deref->named_type()->methods();
5452 else if (deref->struct_type() != NULL)
5453 methods = deref->struct_type()->methods();
5454 else
5455 methods = NULL;
5457 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5459 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5461 Expression_list* vals = new Expression_list();
5462 vals->reserve(2);
5464 Struct_field_list::const_iterator p = fields->begin();
5465 go_assert(p->is_field_name("_type"));
5466 vals->push_back(this->type_descriptor_constructor(gogo,
5467 RUNTIME_TYPE_KIND_PTR,
5468 name, methods, false));
5470 ++p;
5471 go_assert(p->is_field_name("elem"));
5472 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5474 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5478 // Reflection string.
5480 void
5481 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5483 ret->push_back('*');
5484 this->append_reflection(this->to_type_, gogo, ret);
5487 void
5488 Pointer_type::do_mangled_name(Gogo* gogo, std::string* ret) const
5490 ret->push_back('p');
5491 this->append_mangled_name(this->to_type_, gogo, ret);
5494 // Export.
5496 void
5497 Pointer_type::do_export(Export* exp) const
5499 exp->write_c_string("*");
5500 if (this->is_unsafe_pointer_type())
5501 exp->write_c_string("any");
5502 else
5503 exp->write_type(this->to_type_);
5506 // Import.
5508 Pointer_type*
5509 Pointer_type::do_import(Import* imp)
5511 imp->require_c_string("*");
5512 if (imp->match_c_string("any"))
5514 imp->advance(3);
5515 return Type::make_pointer_type(Type::make_void_type());
5517 Type* to = imp->read_type();
5518 return Type::make_pointer_type(to);
5521 // Cache of pointer types. Key is "to" type, value is pointer type
5522 // that points to key.
5524 Type::Pointer_type_table Type::pointer_types;
5526 // A list of placeholder pointer types. We keep this so we can ensure
5527 // they are finalized.
5529 std::vector<Pointer_type*> Type::placeholder_pointers;
5531 // Make a pointer type.
5533 Pointer_type*
5534 Type::make_pointer_type(Type* to_type)
5536 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5537 if (p != pointer_types.end())
5538 return p->second;
5539 Pointer_type* ret = new Pointer_type(to_type);
5540 pointer_types[to_type] = ret;
5541 return ret;
5544 // This helper is invoked immediately after named types have been
5545 // converted, to clean up any unresolved pointer types remaining in
5546 // the pointer type cache.
5548 // The motivation for this routine: occasionally the compiler creates
5549 // some specific pointer type as part of a lowering operation (ex:
5550 // pointer-to-void), then Type::backend_type_size() is invoked on the
5551 // type (which creates a Btype placeholder for it), that placeholder
5552 // passed somewhere along the line to the back end, but since there is
5553 // no reference to the type in user code, there is never a call to
5554 // Type::finish_backend for the type (hence the Btype remains as an
5555 // unresolved placeholder). Calling this routine will clean up such
5556 // instances.
5558 void
5559 Type::finish_pointer_types(Gogo* gogo)
5561 // We don't use begin() and end() because it is possible to add new
5562 // placeholder pointer types as we finalized existing ones.
5563 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5565 Pointer_type* pt = Type::placeholder_pointers[i];
5566 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5567 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5569 pt->finish_backend(gogo, tbti->second.btype);
5570 tbti->second.is_placeholder = false;
5575 // The nil type. We use a special type for nil because it is not the
5576 // same as any other type. In C term nil has type void*, but there is
5577 // no such type in Go.
5579 class Nil_type : public Type
5581 public:
5582 Nil_type()
5583 : Type(TYPE_NIL)
5586 protected:
5587 bool
5588 do_compare_is_identity(Gogo*)
5589 { return false; }
5591 Btype*
5592 do_get_backend(Gogo* gogo)
5593 { return gogo->backend()->pointer_type(gogo->backend()->void_type()); }
5595 Expression*
5596 do_type_descriptor(Gogo*, Named_type*)
5597 { go_unreachable(); }
5599 void
5600 do_reflection(Gogo*, std::string*) const
5601 { go_unreachable(); }
5603 void
5604 do_mangled_name(Gogo*, std::string* ret) const
5605 { ret->push_back('n'); }
5608 // Make the nil type.
5610 Type*
5611 Type::make_nil_type()
5613 static Nil_type singleton_nil_type;
5614 return &singleton_nil_type;
5617 // The type of a function call which returns multiple values. This is
5618 // really a struct, but we don't want to confuse a function call which
5619 // returns a struct with a function call which returns multiple
5620 // values.
5622 class Call_multiple_result_type : public Type
5624 public:
5625 Call_multiple_result_type(Call_expression* call)
5626 : Type(TYPE_CALL_MULTIPLE_RESULT),
5627 call_(call)
5630 protected:
5631 bool
5632 do_has_pointer() const
5633 { return false; }
5635 bool
5636 do_compare_is_identity(Gogo*)
5637 { return false; }
5639 Btype*
5640 do_get_backend(Gogo* gogo)
5642 go_assert(saw_errors());
5643 return gogo->backend()->error_type();
5646 Expression*
5647 do_type_descriptor(Gogo*, Named_type*)
5649 go_assert(saw_errors());
5650 return Expression::make_error(Linemap::unknown_location());
5653 void
5654 do_reflection(Gogo*, std::string*) const
5655 { go_assert(saw_errors()); }
5657 void
5658 do_mangled_name(Gogo*, std::string*) const
5659 { go_assert(saw_errors()); }
5661 private:
5662 // The expression being called.
5663 Call_expression* call_;
5666 // Make a call result type.
5668 Type*
5669 Type::make_call_multiple_result_type(Call_expression* call)
5671 return new Call_multiple_result_type(call);
5674 // Class Struct_field.
5676 // Get the name of a field.
5678 const std::string&
5679 Struct_field::field_name() const
5681 const std::string& name(this->typed_identifier_.name());
5682 if (!name.empty())
5683 return name;
5684 else
5686 // This is called during parsing, before anything is lowered, so
5687 // we have to be pretty careful to avoid dereferencing an
5688 // unknown type name.
5689 Type* t = this->typed_identifier_.type();
5690 Type* dt = t;
5691 if (t->classification() == Type::TYPE_POINTER)
5693 // Very ugly.
5694 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5695 dt = ptype->points_to();
5697 if (dt->forward_declaration_type() != NULL)
5698 return dt->forward_declaration_type()->name();
5699 else if (dt->named_type() != NULL)
5701 // Note that this can be an alias name.
5702 return dt->named_type()->name();
5704 else if (t->is_error_type() || dt->is_error_type())
5706 static const std::string error_string = "*error*";
5707 return error_string;
5709 else
5711 // Avoid crashing in the erroneous case where T is named but
5712 // DT is not.
5713 go_assert(t != dt);
5714 if (t->forward_declaration_type() != NULL)
5715 return t->forward_declaration_type()->name();
5716 else if (t->named_type() != NULL)
5717 return t->named_type()->name();
5718 else
5719 go_unreachable();
5724 // Return whether this field is named NAME.
5726 bool
5727 Struct_field::is_field_name(const std::string& name) const
5729 const std::string& me(this->typed_identifier_.name());
5730 if (!me.empty())
5731 return me == name;
5732 else
5734 Type* t = this->typed_identifier_.type();
5735 if (t->points_to() != NULL)
5736 t = t->points_to();
5737 Named_type* nt = t->named_type();
5738 if (nt != NULL && nt->name() == name)
5739 return true;
5741 // This is a horrible hack caused by the fact that we don't pack
5742 // the names of builtin types. FIXME.
5743 if (!this->is_imported_
5744 && nt != NULL
5745 && nt->is_builtin()
5746 && nt->name() == Gogo::unpack_hidden_name(name))
5747 return true;
5749 return false;
5753 // Return whether this field is an unexported field named NAME.
5755 bool
5756 Struct_field::is_unexported_field_name(Gogo* gogo,
5757 const std::string& name) const
5759 const std::string& field_name(this->field_name());
5760 if (Gogo::is_hidden_name(field_name)
5761 && name == Gogo::unpack_hidden_name(field_name)
5762 && gogo->pack_hidden_name(name, false) != field_name)
5763 return true;
5765 // Check for the name of a builtin type. This is like the test in
5766 // is_field_name, only there we return false if this->is_imported_,
5767 // and here we return true.
5768 if (this->is_imported_ && this->is_anonymous())
5770 Type* t = this->typed_identifier_.type();
5771 if (t->points_to() != NULL)
5772 t = t->points_to();
5773 Named_type* nt = t->named_type();
5774 if (nt != NULL
5775 && nt->is_builtin()
5776 && nt->name() == Gogo::unpack_hidden_name(name))
5777 return true;
5780 return false;
5783 // Return whether this field is an embedded built-in type.
5785 bool
5786 Struct_field::is_embedded_builtin(Gogo* gogo) const
5788 const std::string& name(this->field_name());
5789 // We know that a field is an embedded type if it is anonymous.
5790 // We can decide if it is a built-in type by checking to see if it is
5791 // registered globally under the field's name.
5792 // This allows us to distinguish between embedded built-in types and
5793 // embedded types that are aliases to built-in types.
5794 return (this->is_anonymous()
5795 && !Gogo::is_hidden_name(name)
5796 && gogo->lookup_global(name.c_str()) != NULL);
5799 // Class Struct_type.
5801 // A hash table used to find identical unnamed structs so that they
5802 // share method tables.
5804 Struct_type::Identical_structs Struct_type::identical_structs;
5806 // A hash table used to merge method sets for identical unnamed
5807 // structs.
5809 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5811 // Traversal.
5814 Struct_type::do_traverse(Traverse* traverse)
5816 Struct_field_list* fields = this->fields_;
5817 if (fields != NULL)
5819 for (Struct_field_list::iterator p = fields->begin();
5820 p != fields->end();
5821 ++p)
5823 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5824 return TRAVERSE_EXIT;
5827 return TRAVERSE_CONTINUE;
5830 // Verify that the struct type is complete and valid.
5832 bool
5833 Struct_type::do_verify()
5835 Struct_field_list* fields = this->fields_;
5836 if (fields == NULL)
5837 return true;
5838 for (Struct_field_list::iterator p = fields->begin();
5839 p != fields->end();
5840 ++p)
5842 Type* t = p->type();
5843 if (p->is_anonymous())
5845 if (t->named_type() != NULL && t->points_to() != NULL)
5847 go_error_at(p->location(), "embedded type may not be a pointer");
5848 p->set_type(Type::make_error_type());
5850 else if (t->points_to() != NULL
5851 && t->points_to()->interface_type() != NULL)
5853 go_error_at(p->location(),
5854 "embedded type may not be pointer to interface");
5855 p->set_type(Type::make_error_type());
5859 return true;
5862 // Whether this contains a pointer.
5864 bool
5865 Struct_type::do_has_pointer() const
5867 const Struct_field_list* fields = this->fields();
5868 if (fields == NULL)
5869 return false;
5870 for (Struct_field_list::const_iterator p = fields->begin();
5871 p != fields->end();
5872 ++p)
5874 if (p->type()->has_pointer())
5875 return true;
5877 return false;
5880 // Whether this type is identical to T.
5882 bool
5883 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5884 bool errors_are_identical) const
5886 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5887 return false;
5888 const Struct_field_list* fields1 = this->fields();
5889 const Struct_field_list* fields2 = t->fields();
5890 if (fields1 == NULL || fields2 == NULL)
5891 return fields1 == fields2;
5892 Struct_field_list::const_iterator pf2 = fields2->begin();
5893 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5894 pf1 != fields1->end();
5895 ++pf1, ++pf2)
5897 if (pf2 == fields2->end())
5898 return false;
5899 if (pf1->field_name() != pf2->field_name())
5900 return false;
5901 if (pf1->is_anonymous() != pf2->is_anonymous()
5902 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5903 errors_are_identical, NULL))
5904 return false;
5905 if (cmp_tags == COMPARE_TAGS)
5907 if (!pf1->has_tag())
5909 if (pf2->has_tag())
5910 return false;
5912 else
5914 if (!pf2->has_tag())
5915 return false;
5916 if (pf1->tag() != pf2->tag())
5917 return false;
5921 if (pf2 != fields2->end())
5922 return false;
5923 return true;
5926 // Whether comparisons of this struct type are simple identity
5927 // comparisons.
5929 bool
5930 Struct_type::do_compare_is_identity(Gogo* gogo)
5932 const Struct_field_list* fields = this->fields_;
5933 if (fields == NULL)
5934 return true;
5935 int64_t offset = 0;
5936 for (Struct_field_list::const_iterator pf = fields->begin();
5937 pf != fields->end();
5938 ++pf)
5940 if (Gogo::is_sink_name(pf->field_name()))
5941 return false;
5943 if (!pf->type()->compare_is_identity(gogo))
5944 return false;
5946 int64_t field_align;
5947 if (!pf->type()->backend_type_align(gogo, &field_align))
5948 return false;
5949 if ((offset & (field_align - 1)) != 0)
5951 // This struct has padding. We don't guarantee that that
5952 // padding is zero-initialized for a stack variable, so we
5953 // can't use memcmp to compare struct values.
5954 return false;
5957 int64_t field_size;
5958 if (!pf->type()->backend_type_size(gogo, &field_size))
5959 return false;
5960 offset += field_size;
5963 int64_t struct_size;
5964 if (!this->backend_type_size(gogo, &struct_size))
5965 return false;
5966 if (offset != struct_size)
5968 // Trailing padding may not be zero when on the stack.
5969 return false;
5972 return true;
5975 // Return whether this struct type is reflexive--whether a value of
5976 // this type is always equal to itself.
5978 bool
5979 Struct_type::do_is_reflexive()
5981 const Struct_field_list* fields = this->fields_;
5982 if (fields == NULL)
5983 return true;
5984 for (Struct_field_list::const_iterator pf = fields->begin();
5985 pf != fields->end();
5986 ++pf)
5988 if (!pf->type()->is_reflexive())
5989 return false;
5991 return true;
5994 // Return whether this struct type needs a key update when used as a
5995 // map key.
5997 bool
5998 Struct_type::do_needs_key_update()
6000 const Struct_field_list* fields = this->fields_;
6001 if (fields == NULL)
6002 return false;
6003 for (Struct_field_list::const_iterator pf = fields->begin();
6004 pf != fields->end();
6005 ++pf)
6007 if (pf->type()->needs_key_update())
6008 return true;
6010 return false;
6013 // Return whether this struct type is permitted to be in the heap.
6015 bool
6016 Struct_type::do_in_heap()
6018 const Struct_field_list* fields = this->fields_;
6019 if (fields == NULL)
6020 return true;
6021 for (Struct_field_list::const_iterator pf = fields->begin();
6022 pf != fields->end();
6023 ++pf)
6025 if (!pf->type()->in_heap())
6026 return false;
6028 return true;
6031 // Build identity and hash functions for this struct.
6033 // Hash code.
6035 unsigned int
6036 Struct_type::do_hash_for_method(Gogo* gogo) const
6038 unsigned int ret = 0;
6039 if (this->fields() != NULL)
6041 for (Struct_field_list::const_iterator pf = this->fields()->begin();
6042 pf != this->fields()->end();
6043 ++pf)
6044 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
6046 ret <<= 2;
6047 if (this->is_struct_incomparable_)
6048 ret <<= 1;
6049 return ret;
6052 // Find the local field NAME.
6054 const Struct_field*
6055 Struct_type::find_local_field(const std::string& name,
6056 unsigned int *pindex) const
6058 const Struct_field_list* fields = this->fields_;
6059 if (fields == NULL)
6060 return NULL;
6061 unsigned int i = 0;
6062 for (Struct_field_list::const_iterator pf = fields->begin();
6063 pf != fields->end();
6064 ++pf, ++i)
6066 if (pf->is_field_name(name))
6068 if (pindex != NULL)
6069 *pindex = i;
6070 return &*pf;
6073 return NULL;
6076 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
6078 Field_reference_expression*
6079 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
6080 Location location) const
6082 unsigned int depth;
6083 return this->field_reference_depth(struct_expr, name, location, NULL,
6084 &depth);
6087 // Return an expression for a field, along with the depth at which it
6088 // was found.
6090 Field_reference_expression*
6091 Struct_type::field_reference_depth(Expression* struct_expr,
6092 const std::string& name,
6093 Location location,
6094 Saw_named_type* saw,
6095 unsigned int* depth) const
6097 const Struct_field_list* fields = this->fields_;
6098 if (fields == NULL)
6099 return NULL;
6101 // Look for a field with this name.
6102 unsigned int i = 0;
6103 for (Struct_field_list::const_iterator pf = fields->begin();
6104 pf != fields->end();
6105 ++pf, ++i)
6107 if (pf->is_field_name(name))
6109 *depth = 0;
6110 return Expression::make_field_reference(struct_expr, i, location);
6114 // Look for an anonymous field which contains a field with this
6115 // name.
6116 unsigned int found_depth = 0;
6117 Field_reference_expression* ret = NULL;
6118 i = 0;
6119 for (Struct_field_list::const_iterator pf = fields->begin();
6120 pf != fields->end();
6121 ++pf, ++i)
6123 if (!pf->is_anonymous())
6124 continue;
6126 Struct_type* st = pf->type()->deref()->struct_type();
6127 if (st == NULL)
6128 continue;
6130 Saw_named_type* hold_saw = saw;
6131 Saw_named_type saw_here;
6132 Named_type* nt = pf->type()->named_type();
6133 if (nt == NULL)
6134 nt = pf->type()->deref()->named_type();
6135 if (nt != NULL)
6137 Saw_named_type* q;
6138 for (q = saw; q != NULL; q = q->next)
6140 if (q->nt == nt)
6142 // If this is an error, it will be reported
6143 // elsewhere.
6144 break;
6147 if (q != NULL)
6148 continue;
6149 saw_here.next = saw;
6150 saw_here.nt = nt;
6151 saw = &saw_here;
6154 // Look for a reference using a NULL struct expression. If we
6155 // find one, fill in the struct expression with a reference to
6156 // this field.
6157 unsigned int subdepth;
6158 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6159 location,
6160 saw,
6161 &subdepth);
6163 saw = hold_saw;
6165 if (sub == NULL)
6166 continue;
6168 if (ret == NULL || subdepth < found_depth)
6170 if (ret != NULL)
6171 delete ret;
6172 ret = sub;
6173 found_depth = subdepth;
6174 Expression* here = Expression::make_field_reference(struct_expr, i,
6175 location);
6176 if (pf->type()->points_to() != NULL)
6177 here = Expression::make_unary(OPERATOR_MULT, here, location);
6178 while (sub->expr() != NULL)
6180 sub = sub->expr()->deref()->field_reference_expression();
6181 go_assert(sub != NULL);
6183 sub->set_struct_expression(here);
6184 sub->set_implicit(true);
6186 else if (subdepth > found_depth)
6187 delete sub;
6188 else
6190 // We do not handle ambiguity here--it should be handled by
6191 // Type::bind_field_or_method.
6192 delete sub;
6193 found_depth = 0;
6194 ret = NULL;
6198 if (ret != NULL)
6199 *depth = found_depth + 1;
6201 return ret;
6204 // Return the total number of fields, including embedded fields.
6206 unsigned int
6207 Struct_type::total_field_count() const
6209 if (this->fields_ == NULL)
6210 return 0;
6211 unsigned int ret = 0;
6212 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6213 pf != this->fields_->end();
6214 ++pf)
6216 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6217 ++ret;
6218 else
6219 ret += pf->type()->struct_type()->total_field_count();
6221 return ret;
6224 // Return whether NAME is an unexported field, for better error reporting.
6226 bool
6227 Struct_type::is_unexported_local_field(Gogo* gogo,
6228 const std::string& name) const
6230 const Struct_field_list* fields = this->fields_;
6231 if (fields != NULL)
6233 for (Struct_field_list::const_iterator pf = fields->begin();
6234 pf != fields->end();
6235 ++pf)
6236 if (pf->is_unexported_field_name(gogo, name))
6237 return true;
6239 return false;
6242 // Finalize the methods of an unnamed struct.
6244 void
6245 Struct_type::finalize_methods(Gogo* gogo)
6247 if (this->all_methods_ != NULL)
6248 return;
6250 // It is possible to have multiple identical structs that have
6251 // methods. We want them to share method tables. Otherwise we will
6252 // emit identical methods more than once, which is bad since they
6253 // will even have the same names.
6254 std::pair<Identical_structs::iterator, bool> ins =
6255 Struct_type::identical_structs.insert(std::make_pair(this, this));
6256 if (!ins.second)
6258 // An identical struct was already entered into the hash table.
6259 // Note that finalize_methods is, fortunately, not recursive.
6260 this->all_methods_ = ins.first->second->all_methods_;
6261 return;
6264 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6267 // Return the method NAME, or NULL if there isn't one or if it is
6268 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6269 // ambiguous.
6271 Method*
6272 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6274 return Type::method_function(this->all_methods_, name, is_ambiguous);
6277 // Return a pointer to the interface method table for this type for
6278 // the interface INTERFACE. IS_POINTER is true if this is for a
6279 // pointer to THIS.
6281 Expression*
6282 Struct_type::interface_method_table(Interface_type* interface,
6283 bool is_pointer)
6285 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6286 val(this, NULL);
6287 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6288 Struct_type::struct_method_tables.insert(val);
6290 Struct_method_table_pair* smtp;
6291 if (!ins.second)
6292 smtp = ins.first->second;
6293 else
6295 smtp = new Struct_method_table_pair();
6296 smtp->first = NULL;
6297 smtp->second = NULL;
6298 ins.first->second = smtp;
6301 return Type::interface_method_table(this, interface, is_pointer,
6302 &smtp->first, &smtp->second);
6305 // Convert struct fields to the backend representation. This is not
6306 // declared in types.h so that types.h doesn't have to #include
6307 // backend.h.
6309 static void
6310 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6311 bool use_placeholder,
6312 std::vector<Backend::Btyped_identifier>* bfields)
6314 bfields->resize(fields->size());
6315 size_t i = 0;
6316 for (Struct_field_list::const_iterator p = fields->begin();
6317 p != fields->end();
6318 ++p, ++i)
6320 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6321 (*bfields)[i].btype = (use_placeholder
6322 ? p->type()->get_backend_placeholder(gogo)
6323 : p->type()->get_backend(gogo));
6324 (*bfields)[i].location = p->location();
6326 go_assert(i == fields->size());
6329 // Get the backend representation for a struct type.
6331 Btype*
6332 Struct_type::do_get_backend(Gogo* gogo)
6334 std::vector<Backend::Btyped_identifier> bfields;
6335 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6336 return gogo->backend()->struct_type(bfields);
6339 // Finish the backend representation of the fields of a struct.
6341 void
6342 Struct_type::finish_backend_fields(Gogo* gogo)
6344 const Struct_field_list* fields = this->fields_;
6345 if (fields != NULL)
6347 for (Struct_field_list::const_iterator p = fields->begin();
6348 p != fields->end();
6349 ++p)
6350 p->type()->get_backend(gogo);
6354 // The type of a struct type descriptor.
6356 Type*
6357 Struct_type::make_struct_type_descriptor_type()
6359 static Type* ret;
6360 if (ret == NULL)
6362 Type* tdt = Type::make_type_descriptor_type();
6363 Type* ptdt = Type::make_type_descriptor_ptr_type();
6365 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6366 Type* string_type = Type::lookup_string_type();
6367 Type* pointer_string_type = Type::make_pointer_type(string_type);
6369 Struct_type* sf =
6370 Type::make_builtin_struct_type(5,
6371 "name", pointer_string_type,
6372 "pkgPath", pointer_string_type,
6373 "typ", ptdt,
6374 "tag", pointer_string_type,
6375 "offsetAnon", uintptr_type);
6376 Type* nsf = Type::make_builtin_named_type("structField", sf);
6378 Type* slice_type = Type::make_array_type(nsf, NULL);
6380 Struct_type* s = Type::make_builtin_struct_type(2,
6381 "", tdt,
6382 "fields", slice_type);
6384 ret = Type::make_builtin_named_type("StructType", s);
6387 return ret;
6390 // Build a type descriptor for a struct type.
6392 Expression*
6393 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6395 Location bloc = Linemap::predeclared_location();
6397 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6399 const Struct_field_list* fields = stdt->struct_type()->fields();
6401 Expression_list* vals = new Expression_list();
6402 vals->reserve(2);
6404 const Methods* methods = this->methods();
6405 // A named struct should not have methods--the methods should attach
6406 // to the named type.
6407 go_assert(methods == NULL || name == NULL);
6409 Struct_field_list::const_iterator ps = fields->begin();
6410 go_assert(ps->is_field_name("_type"));
6411 vals->push_back(this->type_descriptor_constructor(gogo,
6412 RUNTIME_TYPE_KIND_STRUCT,
6413 name, methods, true));
6415 ++ps;
6416 go_assert(ps->is_field_name("fields"));
6418 Expression_list* elements = new Expression_list();
6419 elements->reserve(this->fields_->size());
6420 Type* element_type = ps->type()->array_type()->element_type();
6421 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6422 pf != this->fields_->end();
6423 ++pf)
6425 const Struct_field_list* f = element_type->struct_type()->fields();
6427 Expression_list* fvals = new Expression_list();
6428 fvals->reserve(5);
6430 Struct_field_list::const_iterator q = f->begin();
6431 go_assert(q->is_field_name("name"));
6432 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6433 Expression* s = Expression::make_string(n, bloc);
6434 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6436 ++q;
6437 go_assert(q->is_field_name("pkgPath"));
6438 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6439 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6440 fvals->push_back(Expression::make_nil(bloc));
6441 else
6443 std::string n;
6444 if (is_embedded_builtin)
6445 n = gogo->package_name();
6446 else
6447 n = Gogo::hidden_name_pkgpath(pf->field_name());
6448 Expression* s = Expression::make_string(n, bloc);
6449 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6452 ++q;
6453 go_assert(q->is_field_name("typ"));
6454 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6456 ++q;
6457 go_assert(q->is_field_name("tag"));
6458 if (!pf->has_tag())
6459 fvals->push_back(Expression::make_nil(bloc));
6460 else
6462 Expression* s = Expression::make_string(pf->tag(), bloc);
6463 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6466 ++q;
6467 go_assert(q->is_field_name("offsetAnon"));
6468 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6469 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6470 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6471 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6472 int av = pf->is_anonymous() ? 1 : 0;
6473 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6474 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6475 fvals->push_back(o);
6477 Expression* v = Expression::make_struct_composite_literal(element_type,
6478 fvals, bloc);
6479 elements->push_back(v);
6482 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6483 elements, bloc));
6485 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6488 // Write the hash function for a struct which can not use the identity
6489 // function.
6491 void
6492 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6493 Function_type* hash_fntype,
6494 Function_type* equal_fntype)
6496 Location bloc = Linemap::predeclared_location();
6498 // The pointer to the struct that we are going to hash. This is an
6499 // argument to the hash function we are implementing here.
6500 Named_object* key_arg = gogo->lookup("key", NULL);
6501 go_assert(key_arg != NULL);
6502 Type* key_arg_type = key_arg->var_value()->type();
6504 // The seed argument to the hash function.
6505 Named_object* seed_arg = gogo->lookup("seed", NULL);
6506 go_assert(seed_arg != NULL);
6508 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6510 // Make a temporary to hold the return value, initialized to the seed.
6511 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6512 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6513 bloc);
6514 gogo->add_statement(retval);
6516 // Make a temporary to hold the key as a uintptr.
6517 ref = Expression::make_var_reference(key_arg, bloc);
6518 ref = Expression::make_cast(uintptr_type, ref, bloc);
6519 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6520 bloc);
6521 gogo->add_statement(key);
6523 // Loop over the struct fields.
6524 const Struct_field_list* fields = this->fields_;
6525 for (Struct_field_list::const_iterator pf = fields->begin();
6526 pf != fields->end();
6527 ++pf)
6529 if (Gogo::is_sink_name(pf->field_name()))
6530 continue;
6532 // Get a pointer to the value of this field.
6533 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6534 ref = Expression::make_temporary_reference(key, bloc);
6535 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6536 bloc);
6537 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6539 // Get the hash function to use for the type of this field.
6540 Named_object* hash_fn;
6541 Named_object* equal_fn;
6542 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6543 equal_fntype, &hash_fn, &equal_fn);
6545 // Call the hash function for the field, passing retval as the seed.
6546 ref = Expression::make_temporary_reference(retval, bloc);
6547 Expression_list* args = new Expression_list();
6548 args->push_back(subkey);
6549 args->push_back(ref);
6550 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6551 Expression* call = Expression::make_call(func, args, false, bloc);
6553 // Set retval to the result.
6554 Temporary_reference_expression* tref =
6555 Expression::make_temporary_reference(retval, bloc);
6556 tref->set_is_lvalue();
6557 Statement* s = Statement::make_assignment(tref, call, bloc);
6558 gogo->add_statement(s);
6561 // Return retval to the caller of the hash function.
6562 Expression_list* vals = new Expression_list();
6563 ref = Expression::make_temporary_reference(retval, bloc);
6564 vals->push_back(ref);
6565 Statement* s = Statement::make_return_statement(vals, bloc);
6566 gogo->add_statement(s);
6569 // Write the equality function for a struct which can not use the
6570 // identity function.
6572 void
6573 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6575 Location bloc = Linemap::predeclared_location();
6577 // The pointers to the structs we are going to compare.
6578 Named_object* key1_arg = gogo->lookup("key1", NULL);
6579 Named_object* key2_arg = gogo->lookup("key2", NULL);
6580 go_assert(key1_arg != NULL && key2_arg != NULL);
6582 // Build temporaries with the right types.
6583 Type* pt = Type::make_pointer_type(name != NULL
6584 ? static_cast<Type*>(name)
6585 : static_cast<Type*>(this));
6587 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6588 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6589 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6590 gogo->add_statement(p1);
6592 ref = Expression::make_var_reference(key2_arg, bloc);
6593 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6594 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6595 gogo->add_statement(p2);
6597 const Struct_field_list* fields = this->fields_;
6598 unsigned int field_index = 0;
6599 for (Struct_field_list::const_iterator pf = fields->begin();
6600 pf != fields->end();
6601 ++pf, ++field_index)
6603 if (Gogo::is_sink_name(pf->field_name()))
6604 continue;
6606 // Compare one field in both P1 and P2.
6607 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6608 f1 = Expression::make_unary(OPERATOR_MULT, f1, bloc);
6609 f1 = Expression::make_field_reference(f1, field_index, bloc);
6611 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6612 f2 = Expression::make_unary(OPERATOR_MULT, f2, bloc);
6613 f2 = Expression::make_field_reference(f2, field_index, bloc);
6615 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6617 // If the values are not equal, return false.
6618 gogo->start_block(bloc);
6619 Expression_list* vals = new Expression_list();
6620 vals->push_back(Expression::make_boolean(false, bloc));
6621 Statement* s = Statement::make_return_statement(vals, bloc);
6622 gogo->add_statement(s);
6623 Block* then_block = gogo->finish_block(bloc);
6625 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6626 gogo->add_statement(s);
6629 // All the fields are equal, so return true.
6630 Expression_list* vals = new Expression_list();
6631 vals->push_back(Expression::make_boolean(true, bloc));
6632 Statement* s = Statement::make_return_statement(vals, bloc);
6633 gogo->add_statement(s);
6636 // Reflection string.
6638 void
6639 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6641 ret->append("struct {");
6643 for (Struct_field_list::const_iterator p = this->fields_->begin();
6644 p != this->fields_->end();
6645 ++p)
6647 if (p != this->fields_->begin())
6648 ret->push_back(';');
6649 ret->push_back(' ');
6650 if (p->is_anonymous())
6651 ret->push_back('?');
6652 else
6653 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6654 ret->push_back(' ');
6655 if (p->is_anonymous()
6656 && p->type()->named_type() != NULL
6657 && p->type()->named_type()->is_alias())
6658 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6659 else
6660 this->append_reflection(p->type(), gogo, ret);
6662 if (p->has_tag())
6664 const std::string& tag(p->tag());
6665 ret->append(" \"");
6666 for (std::string::const_iterator p = tag.begin();
6667 p != tag.end();
6668 ++p)
6670 if (*p == '\0')
6671 ret->append("\\x00");
6672 else if (*p == '\n')
6673 ret->append("\\n");
6674 else if (*p == '\t')
6675 ret->append("\\t");
6676 else if (*p == '"')
6677 ret->append("\\\"");
6678 else if (*p == '\\')
6679 ret->append("\\\\");
6680 else
6681 ret->push_back(*p);
6683 ret->push_back('"');
6687 if (!this->fields_->empty())
6688 ret->push_back(' ');
6690 ret->push_back('}');
6693 // Mangled name.
6695 void
6696 Struct_type::do_mangled_name(Gogo* gogo, std::string* ret) const
6698 ret->push_back('S');
6700 const Struct_field_list* fields = this->fields_;
6701 if (fields != NULL)
6703 for (Struct_field_list::const_iterator p = fields->begin();
6704 p != fields->end();
6705 ++p)
6707 if (p->is_anonymous())
6708 ret->append("0_");
6709 else
6712 std::string n(Gogo::mangle_possibly_hidden_name(p->field_name()));
6713 char buf[20];
6714 snprintf(buf, sizeof buf, "%u_",
6715 static_cast<unsigned int>(n.length()));
6716 ret->append(buf);
6717 ret->append(n);
6720 // For an anonymous field with an alias type, the field name
6721 // is the alias name.
6722 if (p->is_anonymous()
6723 && p->type()->named_type() != NULL
6724 && p->type()->named_type()->is_alias())
6725 p->type()->named_type()->append_mangled_type_name(gogo, true, ret);
6726 else
6727 this->append_mangled_name(p->type(), gogo, ret);
6728 if (p->has_tag())
6730 const std::string& tag(p->tag());
6731 std::string out;
6732 for (std::string::const_iterator p = tag.begin();
6733 p != tag.end();
6734 ++p)
6736 if (ISALNUM(*p) || *p == '_')
6737 out.push_back(*p);
6738 else
6740 char buf[20];
6741 snprintf(buf, sizeof buf, ".%x.",
6742 static_cast<unsigned int>(*p));
6743 out.append(buf);
6746 char buf[20];
6747 snprintf(buf, sizeof buf, "T%u_",
6748 static_cast<unsigned int>(out.length()));
6749 ret->append(buf);
6750 ret->append(out);
6755 if (this->is_struct_incomparable_)
6756 ret->push_back('x');
6758 ret->push_back('e');
6761 // If the offset of field INDEX in the backend implementation can be
6762 // determined, set *POFFSET to the offset in bytes and return true.
6763 // Otherwise, return false.
6765 bool
6766 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6767 int64_t* poffset)
6769 if (!this->is_backend_type_size_known(gogo))
6770 return false;
6771 Btype* bt = this->get_backend_placeholder(gogo);
6772 *poffset = gogo->backend()->type_field_offset(bt, index);
6773 return true;
6776 // Export.
6778 void
6779 Struct_type::do_export(Export* exp) const
6781 exp->write_c_string("struct { ");
6782 const Struct_field_list* fields = this->fields_;
6783 go_assert(fields != NULL);
6784 for (Struct_field_list::const_iterator p = fields->begin();
6785 p != fields->end();
6786 ++p)
6788 if (p->is_anonymous())
6789 exp->write_string("? ");
6790 else
6792 exp->write_string(p->field_name());
6793 exp->write_c_string(" ");
6795 exp->write_type(p->type());
6797 if (p->has_tag())
6799 exp->write_c_string(" ");
6800 Expression* expr =
6801 Expression::make_string(p->tag(), Linemap::predeclared_location());
6802 expr->export_expression(exp);
6803 delete expr;
6806 exp->write_c_string("; ");
6808 exp->write_c_string("}");
6811 // Import.
6813 Struct_type*
6814 Struct_type::do_import(Import* imp)
6816 imp->require_c_string("struct { ");
6817 Struct_field_list* fields = new Struct_field_list;
6818 if (imp->peek_char() != '}')
6820 while (true)
6822 std::string name;
6823 if (imp->match_c_string("? "))
6824 imp->advance(2);
6825 else
6827 name = imp->read_identifier();
6828 imp->require_c_string(" ");
6830 Type* ftype = imp->read_type();
6832 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6833 sf.set_is_imported();
6835 if (imp->peek_char() == ' ')
6837 imp->advance(1);
6838 Expression* expr = Expression::import_expression(imp);
6839 String_expression* sexpr = expr->string_expression();
6840 go_assert(sexpr != NULL);
6841 sf.set_tag(sexpr->val());
6842 delete sexpr;
6845 imp->require_c_string("; ");
6846 fields->push_back(sf);
6847 if (imp->peek_char() == '}')
6848 break;
6851 imp->require_c_string("}");
6853 return Type::make_struct_type(fields, imp->location());
6856 // Whether we can write this struct type to a C header file.
6857 // We can't if any of the fields are structs defined in a different package.
6859 bool
6860 Struct_type::can_write_to_c_header(
6861 std::vector<const Named_object*>* requires,
6862 std::vector<const Named_object*>* declare) const
6864 const Struct_field_list* fields = this->fields_;
6865 if (fields == NULL || fields->empty())
6866 return false;
6867 int sinks = 0;
6868 for (Struct_field_list::const_iterator p = fields->begin();
6869 p != fields->end();
6870 ++p)
6872 if (p->is_anonymous())
6873 return false;
6874 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6875 return false;
6876 if (Gogo::message_name(p->field_name()) == "_")
6877 sinks++;
6879 if (sinks > 1)
6880 return false;
6881 return true;
6884 // Whether we can write the type T to a C header file.
6886 bool
6887 Struct_type::can_write_type_to_c_header(
6888 const Type* t,
6889 std::vector<const Named_object*>* requires,
6890 std::vector<const Named_object*>* declare) const
6892 t = t->forwarded();
6893 switch (t->classification())
6895 case TYPE_ERROR:
6896 case TYPE_FORWARD:
6897 return false;
6899 case TYPE_VOID:
6900 case TYPE_BOOLEAN:
6901 case TYPE_INTEGER:
6902 case TYPE_FLOAT:
6903 case TYPE_COMPLEX:
6904 case TYPE_STRING:
6905 case TYPE_FUNCTION:
6906 case TYPE_MAP:
6907 case TYPE_CHANNEL:
6908 case TYPE_INTERFACE:
6909 return true;
6911 case TYPE_POINTER:
6912 // Don't try to handle a pointer to an array.
6913 if (t->points_to()->array_type() != NULL
6914 && !t->points_to()->is_slice_type())
6915 return false;
6917 if (t->points_to()->named_type() != NULL
6918 && t->points_to()->struct_type() != NULL)
6919 declare->push_back(t->points_to()->named_type()->named_object());
6920 return true;
6922 case TYPE_STRUCT:
6923 return t->struct_type()->can_write_to_c_header(requires, declare);
6925 case TYPE_ARRAY:
6926 if (t->is_slice_type())
6927 return true;
6928 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6929 requires, declare);
6931 case TYPE_NAMED:
6933 const Named_object* no = t->named_type()->named_object();
6934 if (no->package() != NULL)
6936 if (t->is_unsafe_pointer_type())
6937 return true;
6938 return false;
6940 if (t->struct_type() != NULL)
6942 requires->push_back(no);
6943 return t->struct_type()->can_write_to_c_header(requires, declare);
6945 return this->can_write_type_to_c_header(t->base(), requires, declare);
6948 case TYPE_CALL_MULTIPLE_RESULT:
6949 case TYPE_NIL:
6950 case TYPE_SINK:
6951 default:
6952 go_unreachable();
6956 // Write this struct to a C header file.
6958 void
6959 Struct_type::write_to_c_header(std::ostream& os) const
6961 const Struct_field_list* fields = this->fields_;
6962 for (Struct_field_list::const_iterator p = fields->begin();
6963 p != fields->end();
6964 ++p)
6966 os << '\t';
6967 this->write_field_to_c_header(os, p->field_name(), p->type());
6968 os << ';' << std::endl;
6972 // Write the type of a struct field to a C header file.
6974 void
6975 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6976 const Type *t) const
6978 bool print_name = true;
6979 t = t->forwarded();
6980 switch (t->classification())
6982 case TYPE_VOID:
6983 os << "void";
6984 break;
6986 case TYPE_BOOLEAN:
6987 os << "_Bool";
6988 break;
6990 case TYPE_INTEGER:
6992 const Integer_type* it = t->integer_type();
6993 if (it->is_unsigned())
6994 os << 'u';
6995 os << "int" << it->bits() << "_t";
6997 break;
6999 case TYPE_FLOAT:
7000 switch (t->float_type()->bits())
7002 case 32:
7003 os << "float";
7004 break;
7005 case 64:
7006 os << "double";
7007 break;
7008 default:
7009 go_unreachable();
7011 break;
7013 case TYPE_COMPLEX:
7014 switch (t->complex_type()->bits())
7016 case 64:
7017 os << "float _Complex";
7018 break;
7019 case 128:
7020 os << "double _Complex";
7021 break;
7022 default:
7023 go_unreachable();
7025 break;
7027 case TYPE_STRING:
7028 os << "String";
7029 break;
7031 case TYPE_FUNCTION:
7032 os << "FuncVal*";
7033 break;
7035 case TYPE_POINTER:
7037 std::vector<const Named_object*> requires;
7038 std::vector<const Named_object*> declare;
7039 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
7040 &declare))
7041 os << "void*";
7042 else
7044 this->write_field_to_c_header(os, "", t->points_to());
7045 os << '*';
7048 break;
7050 case TYPE_MAP:
7051 os << "Map*";
7052 break;
7054 case TYPE_CHANNEL:
7055 os << "Chan*";
7056 break;
7058 case TYPE_INTERFACE:
7059 if (t->interface_type()->is_empty())
7060 os << "Eface";
7061 else
7062 os << "Iface";
7063 break;
7065 case TYPE_STRUCT:
7066 os << "struct {" << std::endl;
7067 t->struct_type()->write_to_c_header(os);
7068 os << "\t}";
7069 break;
7071 case TYPE_ARRAY:
7072 if (t->is_slice_type())
7073 os << "Slice";
7074 else
7076 const Type *ele = t;
7077 std::vector<const Type*> array_types;
7078 while (ele->array_type() != NULL && !ele->is_slice_type())
7080 array_types.push_back(ele);
7081 ele = ele->array_type()->element_type();
7083 this->write_field_to_c_header(os, "", ele);
7084 os << ' ' << Gogo::message_name(name);
7085 print_name = false;
7086 while (!array_types.empty())
7088 ele = array_types.back();
7089 array_types.pop_back();
7090 os << '[';
7091 Numeric_constant nc;
7092 if (!ele->array_type()->length()->numeric_constant_value(&nc))
7093 go_unreachable();
7094 mpz_t val;
7095 if (!nc.to_int(&val))
7096 go_unreachable();
7097 char* s = mpz_get_str(NULL, 10, val);
7098 os << s;
7099 free(s);
7100 mpz_clear(val);
7101 os << ']';
7104 break;
7106 case TYPE_NAMED:
7108 const Named_object* no = t->named_type()->named_object();
7109 if (t->struct_type() != NULL)
7110 os << "struct " << no->message_name();
7111 else if (t->is_unsafe_pointer_type())
7112 os << "void*";
7113 else if (t == Type::lookup_integer_type("uintptr"))
7114 os << "uintptr_t";
7115 else
7117 this->write_field_to_c_header(os, name, t->base());
7118 print_name = false;
7121 break;
7123 case TYPE_ERROR:
7124 case TYPE_FORWARD:
7125 case TYPE_CALL_MULTIPLE_RESULT:
7126 case TYPE_NIL:
7127 case TYPE_SINK:
7128 default:
7129 go_unreachable();
7132 if (print_name && !name.empty())
7133 os << ' ' << Gogo::message_name(name);
7136 // Make a struct type.
7138 Struct_type*
7139 Type::make_struct_type(Struct_field_list* fields,
7140 Location location)
7142 return new Struct_type(fields, location);
7145 // Class Array_type.
7147 // Store the length of an array as an int64_t into *PLEN. Return
7148 // false if the length can not be determined. This will assert if
7149 // called for a slice.
7151 bool
7152 Array_type::int_length(int64_t* plen)
7154 go_assert(this->length_ != NULL);
7155 Numeric_constant nc;
7156 if (!this->length_->numeric_constant_value(&nc))
7157 return false;
7158 return nc.to_memory_size(plen);
7161 // Whether two array types are identical.
7163 bool
7164 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
7165 bool errors_are_identical) const
7167 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
7168 cmp_tags, errors_are_identical, NULL))
7169 return false;
7171 if (this->is_array_incomparable_ != t->is_array_incomparable_)
7172 return false;
7174 Expression* l1 = this->length();
7175 Expression* l2 = t->length();
7177 // Slices of the same element type are identical.
7178 if (l1 == NULL && l2 == NULL)
7179 return true;
7181 // Arrays of the same element type are identical if they have the
7182 // same length.
7183 if (l1 != NULL && l2 != NULL)
7185 if (l1 == l2)
7186 return true;
7188 // Try to determine the lengths. If we can't, assume the arrays
7189 // are not identical.
7190 bool ret = false;
7191 Numeric_constant nc1, nc2;
7192 if (l1->numeric_constant_value(&nc1)
7193 && l2->numeric_constant_value(&nc2))
7195 mpz_t v1;
7196 if (nc1.to_int(&v1))
7198 mpz_t v2;
7199 if (nc2.to_int(&v2))
7201 ret = mpz_cmp(v1, v2) == 0;
7202 mpz_clear(v2);
7204 mpz_clear(v1);
7207 return ret;
7210 // Otherwise the arrays are not identical.
7211 return false;
7214 // Traversal.
7217 Array_type::do_traverse(Traverse* traverse)
7219 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7220 return TRAVERSE_EXIT;
7221 if (this->length_ != NULL
7222 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7223 return TRAVERSE_EXIT;
7224 return TRAVERSE_CONTINUE;
7227 // Check that the length is valid.
7229 bool
7230 Array_type::verify_length()
7232 if (this->length_ == NULL)
7233 return true;
7235 Type_context context(Type::lookup_integer_type("int"), false);
7236 this->length_->determine_type(&context);
7238 if (!this->length_->is_constant())
7240 go_error_at(this->length_->location(), "array bound is not constant");
7241 return false;
7244 Numeric_constant nc;
7245 if (!this->length_->numeric_constant_value(&nc))
7247 if (this->length_->type()->integer_type() != NULL
7248 || this->length_->type()->float_type() != NULL)
7249 go_error_at(this->length_->location(), "array bound is not constant");
7250 else
7251 go_error_at(this->length_->location(), "array bound is not numeric");
7252 return false;
7255 Type* int_type = Type::lookup_integer_type("int");
7256 unsigned int tbits = int_type->integer_type()->bits();
7257 unsigned long val;
7258 switch (nc.to_unsigned_long(&val))
7260 case Numeric_constant::NC_UL_VALID:
7261 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7263 go_error_at(this->length_->location(), "array bound overflows");
7264 return false;
7266 break;
7267 case Numeric_constant::NC_UL_NOTINT:
7268 go_error_at(this->length_->location(), "array bound truncated to integer");
7269 return false;
7270 case Numeric_constant::NC_UL_NEGATIVE:
7271 go_error_at(this->length_->location(), "negative array bound");
7272 return false;
7273 case Numeric_constant::NC_UL_BIG:
7275 mpz_t val;
7276 if (!nc.to_int(&val))
7277 go_unreachable();
7278 unsigned int bits = mpz_sizeinbase(val, 2);
7279 mpz_clear(val);
7280 if (bits >= tbits)
7282 go_error_at(this->length_->location(), "array bound overflows");
7283 return false;
7286 break;
7287 default:
7288 go_unreachable();
7291 return true;
7294 // Verify the type.
7296 bool
7297 Array_type::do_verify()
7299 if (this->element_type()->is_error_type())
7300 return false;
7301 if (!this->verify_length())
7302 this->length_ = Expression::make_error(this->length_->location());
7303 return true;
7306 // Whether the type contains pointers. This is always true for a
7307 // slice. For an array it is true if the element type has pointers
7308 // and the length is greater than zero.
7310 bool
7311 Array_type::do_has_pointer() const
7313 if (this->length_ == NULL)
7314 return true;
7315 if (!this->element_type_->has_pointer())
7316 return false;
7318 Numeric_constant nc;
7319 if (!this->length_->numeric_constant_value(&nc))
7321 // Error reported elsewhere.
7322 return false;
7325 unsigned long val;
7326 switch (nc.to_unsigned_long(&val))
7328 case Numeric_constant::NC_UL_VALID:
7329 return val > 0;
7330 case Numeric_constant::NC_UL_BIG:
7331 return true;
7332 default:
7333 // Error reported elsewhere.
7334 return false;
7338 // Whether we can use memcmp to compare this array.
7340 bool
7341 Array_type::do_compare_is_identity(Gogo* gogo)
7343 if (this->length_ == NULL)
7344 return false;
7346 // Check for [...], which indicates that this is not a real type.
7347 if (this->length_->is_nil_expression())
7348 return false;
7350 if (!this->element_type_->compare_is_identity(gogo))
7351 return false;
7353 // If there is any padding, then we can't use memcmp.
7354 int64_t size;
7355 int64_t align;
7356 if (!this->element_type_->backend_type_size(gogo, &size)
7357 || !this->element_type_->backend_type_align(gogo, &align))
7358 return false;
7359 if ((size & (align - 1)) != 0)
7360 return false;
7362 return true;
7365 // Array type hash code.
7367 unsigned int
7368 Array_type::do_hash_for_method(Gogo* gogo) const
7370 unsigned int ret;
7372 // There is no very convenient way to get a hash code for the
7373 // length.
7374 ret = this->element_type_->hash_for_method(gogo) + 1;
7375 if (this->is_array_incomparable_)
7376 ret <<= 1;
7377 return ret;
7380 // Write the hash function for an array which can not use the identify
7381 // function.
7383 void
7384 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7385 Function_type* hash_fntype,
7386 Function_type* equal_fntype)
7388 Location bloc = Linemap::predeclared_location();
7390 // The pointer to the array that we are going to hash. This is an
7391 // argument to the hash function we are implementing here.
7392 Named_object* key_arg = gogo->lookup("key", NULL);
7393 go_assert(key_arg != NULL);
7394 Type* key_arg_type = key_arg->var_value()->type();
7396 // The seed argument to the hash function.
7397 Named_object* seed_arg = gogo->lookup("seed", NULL);
7398 go_assert(seed_arg != NULL);
7400 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7402 // Make a temporary to hold the return value, initialized to the seed.
7403 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7404 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7405 bloc);
7406 gogo->add_statement(retval);
7408 // Make a temporary to hold the key as a uintptr.
7409 ref = Expression::make_var_reference(key_arg, bloc);
7410 ref = Expression::make_cast(uintptr_type, ref, bloc);
7411 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7412 bloc);
7413 gogo->add_statement(key);
7415 // Loop over the array elements.
7416 // for i = range a
7417 Type* int_type = Type::lookup_integer_type("int");
7418 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7419 gogo->add_statement(index);
7421 Expression* iref = Expression::make_temporary_reference(index, bloc);
7422 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7423 Type* pt = Type::make_pointer_type(name != NULL
7424 ? static_cast<Type*>(name)
7425 : static_cast<Type*>(this));
7426 aref = Expression::make_cast(pt, aref, bloc);
7427 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7428 NULL,
7429 aref,
7430 bloc);
7432 gogo->start_block(bloc);
7434 // Get the hash function for the element type.
7435 Named_object* hash_fn;
7436 Named_object* equal_fn;
7437 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7438 hash_fntype, equal_fntype, &hash_fn,
7439 &equal_fn);
7441 // Get a pointer to this element in the loop.
7442 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7443 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7445 // Get the size of each element.
7446 Expression* ele_size = Expression::make_type_info(this->element_type_,
7447 Expression::TYPE_INFO_SIZE);
7449 // Get the hash of this element, passing retval as the seed.
7450 ref = Expression::make_temporary_reference(retval, bloc);
7451 Expression_list* args = new Expression_list();
7452 args->push_back(subkey);
7453 args->push_back(ref);
7454 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7455 Expression* call = Expression::make_call(func, args, false, bloc);
7457 // Set retval to the result.
7458 Temporary_reference_expression* tref =
7459 Expression::make_temporary_reference(retval, bloc);
7460 tref->set_is_lvalue();
7461 Statement* s = Statement::make_assignment(tref, call, bloc);
7462 gogo->add_statement(s);
7464 // Increase the element pointer.
7465 tref = Expression::make_temporary_reference(key, bloc);
7466 tref->set_is_lvalue();
7467 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7468 bloc);
7469 Block* statements = gogo->finish_block(bloc);
7471 for_range->add_statements(statements);
7472 gogo->add_statement(for_range);
7474 // Return retval to the caller of the hash function.
7475 Expression_list* vals = new Expression_list();
7476 ref = Expression::make_temporary_reference(retval, bloc);
7477 vals->push_back(ref);
7478 s = Statement::make_return_statement(vals, bloc);
7479 gogo->add_statement(s);
7482 // Write the equality function for an array which can not use the
7483 // identity function.
7485 void
7486 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7488 Location bloc = Linemap::predeclared_location();
7490 // The pointers to the arrays we are going to compare.
7491 Named_object* key1_arg = gogo->lookup("key1", NULL);
7492 Named_object* key2_arg = gogo->lookup("key2", NULL);
7493 go_assert(key1_arg != NULL && key2_arg != NULL);
7495 // Build temporaries for the keys with the right types.
7496 Type* pt = Type::make_pointer_type(name != NULL
7497 ? static_cast<Type*>(name)
7498 : static_cast<Type*>(this));
7500 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7501 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7502 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7503 gogo->add_statement(p1);
7505 ref = Expression::make_var_reference(key2_arg, bloc);
7506 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7507 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7508 gogo->add_statement(p2);
7510 // Loop over the array elements.
7511 // for i = range a
7512 Type* int_type = Type::lookup_integer_type("int");
7513 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7514 gogo->add_statement(index);
7516 Expression* iref = Expression::make_temporary_reference(index, bloc);
7517 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7518 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7519 NULL,
7520 aref,
7521 bloc);
7523 gogo->start_block(bloc);
7525 // Compare element in P1 and P2.
7526 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7527 e1 = Expression::make_unary(OPERATOR_MULT, e1, bloc);
7528 ref = Expression::make_temporary_reference(index, bloc);
7529 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7531 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7532 e2 = Expression::make_unary(OPERATOR_MULT, e2, bloc);
7533 ref = Expression::make_temporary_reference(index, bloc);
7534 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7536 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7538 // If the elements are not equal, return false.
7539 gogo->start_block(bloc);
7540 Expression_list* vals = new Expression_list();
7541 vals->push_back(Expression::make_boolean(false, bloc));
7542 Statement* s = Statement::make_return_statement(vals, bloc);
7543 gogo->add_statement(s);
7544 Block* then_block = gogo->finish_block(bloc);
7546 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7547 gogo->add_statement(s);
7549 Block* statements = gogo->finish_block(bloc);
7551 for_range->add_statements(statements);
7552 gogo->add_statement(for_range);
7554 // All the elements are equal, so return true.
7555 vals = new Expression_list();
7556 vals->push_back(Expression::make_boolean(true, bloc));
7557 s = Statement::make_return_statement(vals, bloc);
7558 gogo->add_statement(s);
7561 // Get the backend representation of the fields of a slice. This is
7562 // not declared in types.h so that types.h doesn't have to #include
7563 // backend.h.
7565 // We use int for the count and capacity fields. This matches 6g.
7566 // The language more or less assumes that we can't allocate space of a
7567 // size which does not fit in int.
7569 static void
7570 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7571 std::vector<Backend::Btyped_identifier>* bfields)
7573 bfields->resize(3);
7575 Type* pet = Type::make_pointer_type(type->element_type());
7576 Btype* pbet = (use_placeholder
7577 ? pet->get_backend_placeholder(gogo)
7578 : pet->get_backend(gogo));
7579 Location ploc = Linemap::predeclared_location();
7581 Backend::Btyped_identifier* p = &(*bfields)[0];
7582 p->name = "__values";
7583 p->btype = pbet;
7584 p->location = ploc;
7586 Type* int_type = Type::lookup_integer_type("int");
7588 p = &(*bfields)[1];
7589 p->name = "__count";
7590 p->btype = int_type->get_backend(gogo);
7591 p->location = ploc;
7593 p = &(*bfields)[2];
7594 p->name = "__capacity";
7595 p->btype = int_type->get_backend(gogo);
7596 p->location = ploc;
7599 // Get the backend representation for the type of this array. A fixed array is
7600 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7601 // just like an array in C. An open array is a struct with three
7602 // fields: a data pointer, the length, and the capacity.
7604 Btype*
7605 Array_type::do_get_backend(Gogo* gogo)
7607 if (this->length_ == NULL)
7609 std::vector<Backend::Btyped_identifier> bfields;
7610 get_backend_slice_fields(gogo, this, false, &bfields);
7611 return gogo->backend()->struct_type(bfields);
7613 else
7615 Btype* element = this->get_backend_element(gogo, false);
7616 Bexpression* len = this->get_backend_length(gogo);
7617 return gogo->backend()->array_type(element, len);
7621 // Return the backend representation of the element type.
7623 Btype*
7624 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7626 if (use_placeholder)
7627 return this->element_type_->get_backend_placeholder(gogo);
7628 else
7629 return this->element_type_->get_backend(gogo);
7632 // Return the backend representation of the length. The length may be
7633 // computed using a function call, so we must only evaluate it once.
7635 Bexpression*
7636 Array_type::get_backend_length(Gogo* gogo)
7638 go_assert(this->length_ != NULL);
7639 if (this->blength_ == NULL)
7641 Numeric_constant nc;
7642 mpz_t val;
7643 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7645 if (mpz_sgn(val) < 0)
7647 this->blength_ = gogo->backend()->error_expression();
7648 return this->blength_;
7650 Type* t = nc.type();
7651 if (t == NULL)
7652 t = Type::lookup_integer_type("int");
7653 else if (t->is_abstract())
7654 t = t->make_non_abstract_type();
7655 Btype* btype = t->get_backend(gogo);
7656 this->blength_ =
7657 gogo->backend()->integer_constant_expression(btype, val);
7658 mpz_clear(val);
7660 else
7662 // Make up a translation context for the array length
7663 // expression. FIXME: This won't work in general.
7664 Translate_context context(gogo, NULL, NULL, NULL);
7665 this->blength_ = this->length_->get_backend(&context);
7667 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7668 this->blength_ =
7669 gogo->backend()->convert_expression(ibtype, this->blength_,
7670 this->length_->location());
7673 return this->blength_;
7676 // Finish backend representation of the array.
7678 void
7679 Array_type::finish_backend_element(Gogo* gogo)
7681 Type* et = this->array_type()->element_type();
7682 et->get_backend(gogo);
7683 if (this->is_slice_type())
7685 // This relies on the fact that we always use the same
7686 // structure for a pointer to any given type.
7687 Type* pet = Type::make_pointer_type(et);
7688 pet->get_backend(gogo);
7692 // Return an expression for a pointer to the values in ARRAY.
7694 Expression*
7695 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7697 if (this->length() != NULL)
7699 // Fixed array.
7700 go_assert(array->type()->array_type() != NULL);
7701 Type* etype = array->type()->array_type()->element_type();
7702 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7703 return Expression::make_cast(Type::make_pointer_type(etype), array,
7704 array->location());
7707 // Slice.
7709 if (is_lvalue)
7711 Temporary_reference_expression* tref =
7712 array->temporary_reference_expression();
7713 Var_expression* ve = array->var_expression();
7714 if (tref != NULL)
7716 tref = tref->copy()->temporary_reference_expression();
7717 tref->set_is_lvalue();
7718 array = tref;
7720 else if (ve != NULL)
7722 ve = new Var_expression(ve->named_object(), ve->location());
7723 ve->set_in_lvalue_pos();
7724 array = ve;
7728 return Expression::make_slice_info(array,
7729 Expression::SLICE_INFO_VALUE_POINTER,
7730 array->location());
7733 // Return an expression for the length of the array ARRAY which has this
7734 // type.
7736 Expression*
7737 Array_type::get_length(Gogo*, Expression* array) const
7739 if (this->length_ != NULL)
7740 return this->length_;
7742 // This is a slice. We need to read the length field.
7743 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7744 array->location());
7747 // Return an expression for the capacity of the array ARRAY which has this
7748 // type.
7750 Expression*
7751 Array_type::get_capacity(Gogo*, Expression* array) const
7753 if (this->length_ != NULL)
7754 return this->length_;
7756 // This is a slice. We need to read the capacity field.
7757 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7758 array->location());
7761 // Export.
7763 void
7764 Array_type::do_export(Export* exp) const
7766 exp->write_c_string("[");
7767 if (this->length_ != NULL)
7768 this->length_->export_expression(exp);
7769 exp->write_c_string("] ");
7770 exp->write_type(this->element_type_);
7773 // Import.
7775 Array_type*
7776 Array_type::do_import(Import* imp)
7778 imp->require_c_string("[");
7779 Expression* length;
7780 if (imp->peek_char() == ']')
7781 length = NULL;
7782 else
7783 length = Expression::import_expression(imp);
7784 imp->require_c_string("] ");
7785 Type* element_type = imp->read_type();
7786 return Type::make_array_type(element_type, length);
7789 // The type of an array type descriptor.
7791 Type*
7792 Array_type::make_array_type_descriptor_type()
7794 static Type* ret;
7795 if (ret == NULL)
7797 Type* tdt = Type::make_type_descriptor_type();
7798 Type* ptdt = Type::make_type_descriptor_ptr_type();
7800 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7802 Struct_type* sf =
7803 Type::make_builtin_struct_type(4,
7804 "", tdt,
7805 "elem", ptdt,
7806 "slice", ptdt,
7807 "len", uintptr_type);
7809 ret = Type::make_builtin_named_type("ArrayType", sf);
7812 return ret;
7815 // The type of an slice type descriptor.
7817 Type*
7818 Array_type::make_slice_type_descriptor_type()
7820 static Type* ret;
7821 if (ret == NULL)
7823 Type* tdt = Type::make_type_descriptor_type();
7824 Type* ptdt = Type::make_type_descriptor_ptr_type();
7826 Struct_type* sf =
7827 Type::make_builtin_struct_type(2,
7828 "", tdt,
7829 "elem", ptdt);
7831 ret = Type::make_builtin_named_type("SliceType", sf);
7834 return ret;
7837 // Build a type descriptor for an array/slice type.
7839 Expression*
7840 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7842 if (this->length_ != NULL)
7843 return this->array_type_descriptor(gogo, name);
7844 else
7845 return this->slice_type_descriptor(gogo, name);
7848 // Build a type descriptor for an array type.
7850 Expression*
7851 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7853 Location bloc = Linemap::predeclared_location();
7855 Type* atdt = Array_type::make_array_type_descriptor_type();
7857 const Struct_field_list* fields = atdt->struct_type()->fields();
7859 Expression_list* vals = new Expression_list();
7860 vals->reserve(3);
7862 Struct_field_list::const_iterator p = fields->begin();
7863 go_assert(p->is_field_name("_type"));
7864 vals->push_back(this->type_descriptor_constructor(gogo,
7865 RUNTIME_TYPE_KIND_ARRAY,
7866 name, NULL, true));
7868 ++p;
7869 go_assert(p->is_field_name("elem"));
7870 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7872 ++p;
7873 go_assert(p->is_field_name("slice"));
7874 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7875 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7877 ++p;
7878 go_assert(p->is_field_name("len"));
7879 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7881 ++p;
7882 go_assert(p == fields->end());
7884 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7887 // Build a type descriptor for a slice type.
7889 Expression*
7890 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7892 Location bloc = Linemap::predeclared_location();
7894 Type* stdt = Array_type::make_slice_type_descriptor_type();
7896 const Struct_field_list* fields = stdt->struct_type()->fields();
7898 Expression_list* vals = new Expression_list();
7899 vals->reserve(2);
7901 Struct_field_list::const_iterator p = fields->begin();
7902 go_assert(p->is_field_name("_type"));
7903 vals->push_back(this->type_descriptor_constructor(gogo,
7904 RUNTIME_TYPE_KIND_SLICE,
7905 name, NULL, true));
7907 ++p;
7908 go_assert(p->is_field_name("elem"));
7909 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7911 ++p;
7912 go_assert(p == fields->end());
7914 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7917 // Reflection string.
7919 void
7920 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7922 ret->push_back('[');
7923 if (this->length_ != NULL)
7925 Numeric_constant nc;
7926 if (!this->length_->numeric_constant_value(&nc))
7928 go_assert(saw_errors());
7929 return;
7931 mpz_t val;
7932 if (!nc.to_int(&val))
7934 go_assert(saw_errors());
7935 return;
7937 char* s = mpz_get_str(NULL, 10, val);
7938 ret->append(s);
7939 free(s);
7940 mpz_clear(val);
7942 ret->push_back(']');
7944 this->append_reflection(this->element_type_, gogo, ret);
7947 // Mangled name.
7949 void
7950 Array_type::do_mangled_name(Gogo* gogo, std::string* ret) const
7952 ret->push_back('A');
7953 this->append_mangled_name(this->element_type_, gogo, ret);
7954 if (this->length_ != NULL)
7956 Numeric_constant nc;
7957 if (!this->length_->numeric_constant_value(&nc))
7959 go_assert(saw_errors());
7960 return;
7962 mpz_t val;
7963 if (!nc.to_int(&val))
7965 go_assert(saw_errors());
7966 return;
7968 char *s = mpz_get_str(NULL, 10, val);
7969 ret->append(s);
7970 free(s);
7971 mpz_clear(val);
7972 if (this->is_array_incomparable_)
7973 ret->push_back('x');
7975 ret->push_back('e');
7978 // Make an array type.
7980 Array_type*
7981 Type::make_array_type(Type* element_type, Expression* length)
7983 return new Array_type(element_type, length);
7986 // Class Map_type.
7988 Named_object* Map_type::zero_value;
7989 int64_t Map_type::zero_value_size;
7990 int64_t Map_type::zero_value_align;
7992 // If this map requires the "fat" functions, return the pointer to
7993 // pass as the zero value to those functions. Otherwise, in the
7994 // normal case, return NULL. The map requires the "fat" functions if
7995 // the value size is larger than max_zero_size bytes. max_zero_size
7996 // must match maxZero in libgo/go/runtime/hashmap.go.
7998 Expression*
7999 Map_type::fat_zero_value(Gogo* gogo)
8001 int64_t valsize;
8002 if (!this->val_type_->backend_type_size(gogo, &valsize))
8004 go_assert(saw_errors());
8005 return NULL;
8007 if (valsize <= Map_type::max_zero_size)
8008 return NULL;
8010 if (Map_type::zero_value_size < valsize)
8011 Map_type::zero_value_size = valsize;
8013 int64_t valalign;
8014 if (!this->val_type_->backend_type_align(gogo, &valalign))
8016 go_assert(saw_errors());
8017 return NULL;
8020 if (Map_type::zero_value_align < valalign)
8021 Map_type::zero_value_align = valalign;
8023 Location bloc = Linemap::predeclared_location();
8025 if (Map_type::zero_value == NULL)
8027 // The final type will be set in backend_zero_value.
8028 Type* uint8_type = Type::lookup_integer_type("uint8");
8029 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
8030 Array_type* array_type = Type::make_array_type(uint8_type, size);
8031 array_type->set_is_array_incomparable();
8032 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
8033 Map_type::zero_value = Named_object::make_variable("go$zerovalue", NULL,
8034 var);
8037 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
8038 z = Expression::make_unary(OPERATOR_AND, z, bloc);
8039 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8040 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
8041 return z;
8044 // Return whether VAR is the map zero value.
8046 bool
8047 Map_type::is_zero_value(Variable* var)
8049 return (Map_type::zero_value != NULL
8050 && Map_type::zero_value->var_value() == var);
8053 // Return the backend representation for the zero value.
8055 Bvariable*
8056 Map_type::backend_zero_value(Gogo* gogo)
8058 Location bloc = Linemap::predeclared_location();
8060 go_assert(Map_type::zero_value != NULL);
8062 Type* uint8_type = Type::lookup_integer_type("uint8");
8063 Btype* buint8_type = uint8_type->get_backend(gogo);
8065 Type* int_type = Type::lookup_integer_type("int");
8067 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
8068 int_type, bloc);
8069 Translate_context context(gogo, NULL, NULL, NULL);
8070 Bexpression* blength = e->get_backend(&context);
8072 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
8074 std::string zname = Map_type::zero_value->name();
8075 std::string asm_name(go_selectively_encode_id(zname));
8076 Bvariable* zvar =
8077 gogo->backend()->implicit_variable(zname, asm_name,
8078 barray_type, false, true, true,
8079 Map_type::zero_value_align);
8080 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
8081 false, true, true, NULL);
8082 return zvar;
8085 // Traversal.
8088 Map_type::do_traverse(Traverse* traverse)
8090 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
8091 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
8092 return TRAVERSE_EXIT;
8093 return TRAVERSE_CONTINUE;
8096 // Check that the map type is OK.
8098 bool
8099 Map_type::do_verify()
8101 // The runtime support uses "map[void]void".
8102 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
8103 go_error_at(this->location_, "invalid map key type");
8104 if (!this->key_type_->in_heap())
8105 go_error_at(this->location_, "go:notinheap map key not allowed");
8106 if (!this->val_type_->in_heap())
8107 go_error_at(this->location_, "go:notinheap map value not allowed");
8108 return true;
8111 // Whether two map types are identical.
8113 bool
8114 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
8115 bool errors_are_identical) const
8117 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
8118 cmp_tags, errors_are_identical, NULL)
8119 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
8120 cmp_tags, errors_are_identical,
8121 NULL));
8124 // Hash code.
8126 unsigned int
8127 Map_type::do_hash_for_method(Gogo* gogo) const
8129 return (this->key_type_->hash_for_method(gogo)
8130 + this->val_type_->hash_for_method(gogo)
8131 + 2);
8134 // Get the backend representation for a map type. A map type is
8135 // represented as a pointer to a struct. The struct is hmap in
8136 // runtime/hashmap.go.
8138 Btype*
8139 Map_type::do_get_backend(Gogo* gogo)
8141 static Btype* backend_map_type;
8142 if (backend_map_type == NULL)
8144 std::vector<Backend::Btyped_identifier> bfields(9);
8146 Location bloc = Linemap::predeclared_location();
8148 Type* int_type = Type::lookup_integer_type("int");
8149 bfields[0].name = "count";
8150 bfields[0].btype = int_type->get_backend(gogo);
8151 bfields[0].location = bloc;
8153 Type* uint8_type = Type::lookup_integer_type("uint8");
8154 bfields[1].name = "flags";
8155 bfields[1].btype = uint8_type->get_backend(gogo);
8156 bfields[1].location = bloc;
8158 bfields[2].name = "B";
8159 bfields[2].btype = bfields[1].btype;
8160 bfields[2].location = bloc;
8162 Type* uint16_type = Type::lookup_integer_type("uint16");
8163 bfields[3].name = "noverflow";
8164 bfields[3].btype = uint16_type->get_backend(gogo);
8165 bfields[3].location = bloc;
8167 Type* uint32_type = Type::lookup_integer_type("uint32");
8168 bfields[4].name = "hash0";
8169 bfields[4].btype = uint32_type->get_backend(gogo);
8170 bfields[4].location = bloc;
8172 Btype* bvt = gogo->backend()->void_type();
8173 Btype* bpvt = gogo->backend()->pointer_type(bvt);
8174 bfields[5].name = "buckets";
8175 bfields[5].btype = bpvt;
8176 bfields[5].location = bloc;
8178 bfields[6].name = "oldbuckets";
8179 bfields[6].btype = bpvt;
8180 bfields[6].location = bloc;
8182 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8183 bfields[7].name = "nevacuate";
8184 bfields[7].btype = uintptr_type->get_backend(gogo);
8185 bfields[7].location = bloc;
8187 bfields[8].name = "overflow";
8188 bfields[8].btype = bpvt;
8189 bfields[8].location = bloc;
8191 Btype *bt = gogo->backend()->struct_type(bfields);
8192 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
8193 backend_map_type = gogo->backend()->pointer_type(bt);
8195 return backend_map_type;
8198 // The type of a map type descriptor.
8200 Type*
8201 Map_type::make_map_type_descriptor_type()
8203 static Type* ret;
8204 if (ret == NULL)
8206 Type* tdt = Type::make_type_descriptor_type();
8207 Type* ptdt = Type::make_type_descriptor_ptr_type();
8208 Type* uint8_type = Type::lookup_integer_type("uint8");
8209 Type* uint16_type = Type::lookup_integer_type("uint16");
8210 Type* bool_type = Type::lookup_bool_type();
8212 Struct_type* sf =
8213 Type::make_builtin_struct_type(12,
8214 "", tdt,
8215 "key", ptdt,
8216 "elem", ptdt,
8217 "bucket", ptdt,
8218 "hmap", ptdt,
8219 "keysize", uint8_type,
8220 "indirectkey", bool_type,
8221 "valuesize", uint8_type,
8222 "indirectvalue", bool_type,
8223 "bucketsize", uint16_type,
8224 "reflexivekey", bool_type,
8225 "needkeyupdate", bool_type);
8227 ret = Type::make_builtin_named_type("MapType", sf);
8230 return ret;
8233 // Build a type descriptor for a map type.
8235 Expression*
8236 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8238 Location bloc = Linemap::predeclared_location();
8240 Type* mtdt = Map_type::make_map_type_descriptor_type();
8241 Type* uint8_type = Type::lookup_integer_type("uint8");
8242 Type* uint16_type = Type::lookup_integer_type("uint16");
8244 int64_t keysize;
8245 if (!this->key_type_->backend_type_size(gogo, &keysize))
8247 go_error_at(this->location_, "error determining map key type size");
8248 return Expression::make_error(this->location_);
8251 int64_t valsize;
8252 if (!this->val_type_->backend_type_size(gogo, &valsize))
8254 go_error_at(this->location_, "error determining map value type size");
8255 return Expression::make_error(this->location_);
8258 int64_t ptrsize;
8259 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8261 go_assert(saw_errors());
8262 return Expression::make_error(this->location_);
8265 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8266 if (bucket_type == NULL)
8268 go_assert(saw_errors());
8269 return Expression::make_error(this->location_);
8272 int64_t bucketsize;
8273 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8275 go_assert(saw_errors());
8276 return Expression::make_error(this->location_);
8279 const Struct_field_list* fields = mtdt->struct_type()->fields();
8281 Expression_list* vals = new Expression_list();
8282 vals->reserve(12);
8284 Struct_field_list::const_iterator p = fields->begin();
8285 go_assert(p->is_field_name("_type"));
8286 vals->push_back(this->type_descriptor_constructor(gogo,
8287 RUNTIME_TYPE_KIND_MAP,
8288 name, NULL, true));
8290 ++p;
8291 go_assert(p->is_field_name("key"));
8292 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8294 ++p;
8295 go_assert(p->is_field_name("elem"));
8296 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8298 ++p;
8299 go_assert(p->is_field_name("bucket"));
8300 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8302 ++p;
8303 go_assert(p->is_field_name("hmap"));
8304 Type* hmap_type = this->hmap_type(bucket_type);
8305 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8307 ++p;
8308 go_assert(p->is_field_name("keysize"));
8309 if (keysize > Map_type::max_key_size)
8310 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8311 else
8312 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8314 ++p;
8315 go_assert(p->is_field_name("indirectkey"));
8316 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8317 bloc));
8319 ++p;
8320 go_assert(p->is_field_name("valuesize"));
8321 if (valsize > Map_type::max_val_size)
8322 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8323 else
8324 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8326 ++p;
8327 go_assert(p->is_field_name("indirectvalue"));
8328 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8329 bloc));
8331 ++p;
8332 go_assert(p->is_field_name("bucketsize"));
8333 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8334 bloc));
8336 ++p;
8337 go_assert(p->is_field_name("reflexivekey"));
8338 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8339 bloc));
8341 ++p;
8342 go_assert(p->is_field_name("needkeyupdate"));
8343 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8344 bloc));
8346 ++p;
8347 go_assert(p == fields->end());
8349 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8352 // Return the bucket type to use for a map type. This must correspond
8353 // to libgo/go/runtime/hashmap.go.
8355 Type*
8356 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8358 if (this->bucket_type_ != NULL)
8359 return this->bucket_type_;
8361 Type* key_type = this->key_type_;
8362 if (keysize > Map_type::max_key_size)
8363 key_type = Type::make_pointer_type(key_type);
8365 Type* val_type = this->val_type_;
8366 if (valsize > Map_type::max_val_size)
8367 val_type = Type::make_pointer_type(val_type);
8369 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8370 NULL, this->location_);
8372 Type* uint8_type = Type::lookup_integer_type("uint8");
8373 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8374 topbits_type->set_is_array_incomparable();
8375 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8376 keys_type->set_is_array_incomparable();
8377 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8378 values_type->set_is_array_incomparable();
8380 // If keys and values have no pointers, the map implementation can
8381 // keep a list of overflow pointers on the side so that buckets can
8382 // be marked as having no pointers. Arrange for the bucket to have
8383 // no pointers by changing the type of the overflow field to uintptr
8384 // in this case. See comment on the hmap.overflow field in
8385 // libgo/go/runtime/hashmap.go.
8386 Type* overflow_type;
8387 if (!key_type->has_pointer() && !val_type->has_pointer())
8388 overflow_type = Type::lookup_integer_type("uintptr");
8389 else
8391 // This should really be a pointer to the bucket type itself,
8392 // but that would require us to construct a Named_type for it to
8393 // give it a way to refer to itself. Since nothing really cares
8394 // (except perhaps for someone using a debugger) just use an
8395 // unsafe pointer.
8396 overflow_type = Type::make_pointer_type(Type::make_void_type());
8399 // Make sure the overflow pointer is the last memory in the struct,
8400 // because the runtime assumes it can use size-ptrSize as the offset
8401 // of the overflow pointer. We double-check that property below
8402 // once the offsets and size are computed.
8404 int64_t topbits_field_size, topbits_field_align;
8405 int64_t keys_field_size, keys_field_align;
8406 int64_t values_field_size, values_field_align;
8407 int64_t overflow_field_size, overflow_field_align;
8408 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8409 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8410 || !keys_type->backend_type_size(gogo, &keys_field_size)
8411 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8412 || !values_type->backend_type_size(gogo, &values_field_size)
8413 || !values_type->backend_type_field_align(gogo, &values_field_align)
8414 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8415 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8417 go_assert(saw_errors());
8418 return NULL;
8421 Struct_type* ret;
8422 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8423 values_field_align);
8424 if (max_align <= overflow_field_align)
8425 ret = make_builtin_struct_type(4,
8426 "topbits", topbits_type,
8427 "keys", keys_type,
8428 "values", values_type,
8429 "overflow", overflow_type);
8430 else
8432 size_t off = topbits_field_size;
8433 off = ((off + keys_field_align - 1)
8434 &~ static_cast<size_t>(keys_field_align - 1));
8435 off += keys_field_size;
8436 off = ((off + values_field_align - 1)
8437 &~ static_cast<size_t>(values_field_align - 1));
8438 off += values_field_size;
8440 int64_t padded_overflow_field_size =
8441 ((overflow_field_size + max_align - 1)
8442 &~ static_cast<size_t>(max_align - 1));
8444 size_t ovoff = off;
8445 ovoff = ((ovoff + max_align - 1)
8446 &~ static_cast<size_t>(max_align - 1));
8447 size_t pad = (ovoff - off
8448 + padded_overflow_field_size - overflow_field_size);
8450 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8451 this->location_);
8452 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8453 pad_type->set_is_array_incomparable();
8455 ret = make_builtin_struct_type(5,
8456 "topbits", topbits_type,
8457 "keys", keys_type,
8458 "values", values_type,
8459 "pad", pad_type,
8460 "overflow", overflow_type);
8463 // Verify that the overflow field is just before the end of the
8464 // bucket type.
8466 Btype* btype = ret->get_backend(gogo);
8467 int64_t offset = gogo->backend()->type_field_offset(btype,
8468 ret->field_count() - 1);
8469 int64_t size;
8470 if (!ret->backend_type_size(gogo, &size))
8472 go_assert(saw_errors());
8473 return NULL;
8476 int64_t ptr_size;
8477 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8479 go_assert(saw_errors());
8480 return NULL;
8483 go_assert(offset + ptr_size == size);
8485 ret->set_is_struct_incomparable();
8487 this->bucket_type_ = ret;
8488 return ret;
8491 // Return the hashmap type for a map type.
8493 Type*
8494 Map_type::hmap_type(Type* bucket_type)
8496 if (this->hmap_type_ != NULL)
8497 return this->hmap_type_;
8499 Type* int_type = Type::lookup_integer_type("int");
8500 Type* uint8_type = Type::lookup_integer_type("uint8");
8501 Type* uint32_type = Type::lookup_integer_type("uint32");
8502 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8503 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8505 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8507 Struct_type* ret = make_builtin_struct_type(8,
8508 "count", int_type,
8509 "flags", uint8_type,
8510 "B", uint8_type,
8511 "hash0", uint32_type,
8512 "buckets", ptr_bucket_type,
8513 "oldbuckets", ptr_bucket_type,
8514 "nevacuate", uintptr_type,
8515 "overflow", void_ptr_type);
8516 ret->set_is_struct_incomparable();
8517 this->hmap_type_ = ret;
8518 return ret;
8521 // Return the iterator type for a map type. This is the type of the
8522 // value used when doing a range over a map.
8524 Type*
8525 Map_type::hiter_type(Gogo* gogo)
8527 if (this->hiter_type_ != NULL)
8528 return this->hiter_type_;
8530 int64_t keysize, valsize;
8531 if (!this->key_type_->backend_type_size(gogo, &keysize)
8532 || !this->val_type_->backend_type_size(gogo, &valsize))
8534 go_assert(saw_errors());
8535 return NULL;
8538 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8539 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8540 Type* uint8_type = Type::lookup_integer_type("uint8");
8541 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8542 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8543 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8544 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8545 Type* hmap_type = this->hmap_type(bucket_type);
8546 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8547 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8549 Struct_type* ret = make_builtin_struct_type(12,
8550 "key", key_ptr_type,
8551 "val", val_ptr_type,
8552 "t", uint8_ptr_type,
8553 "h", hmap_ptr_type,
8554 "buckets", bucket_ptr_type,
8555 "bptr", bucket_ptr_type,
8556 "overflow0", void_ptr_type,
8557 "overflow1", void_ptr_type,
8558 "startBucket", uintptr_type,
8559 "stuff", uintptr_type,
8560 "bucket", uintptr_type,
8561 "checkBucket", uintptr_type);
8562 ret->set_is_struct_incomparable();
8563 this->hiter_type_ = ret;
8564 return ret;
8567 // Reflection string for a map.
8569 void
8570 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8572 ret->append("map[");
8573 this->append_reflection(this->key_type_, gogo, ret);
8574 ret->append("]");
8575 this->append_reflection(this->val_type_, gogo, ret);
8578 // Mangled name for a map.
8580 void
8581 Map_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8583 ret->push_back('M');
8584 this->append_mangled_name(this->key_type_, gogo, ret);
8585 ret->append("__");
8586 this->append_mangled_name(this->val_type_, gogo, ret);
8589 // Export a map type.
8591 void
8592 Map_type::do_export(Export* exp) const
8594 exp->write_c_string("map [");
8595 exp->write_type(this->key_type_);
8596 exp->write_c_string("] ");
8597 exp->write_type(this->val_type_);
8600 // Import a map type.
8602 Map_type*
8603 Map_type::do_import(Import* imp)
8605 imp->require_c_string("map [");
8606 Type* key_type = imp->read_type();
8607 imp->require_c_string("] ");
8608 Type* val_type = imp->read_type();
8609 return Type::make_map_type(key_type, val_type, imp->location());
8612 // Make a map type.
8614 Map_type*
8615 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8617 return new Map_type(key_type, val_type, location);
8620 // Class Channel_type.
8622 // Verify.
8624 bool
8625 Channel_type::do_verify()
8627 // We have no location for this error, but this is not something the
8628 // ordinary user will see.
8629 if (!this->element_type_->in_heap())
8630 go_error_at(Linemap::unknown_location(),
8631 "chan of go:notinheap type not allowed");
8632 return true;
8635 // Hash code.
8637 unsigned int
8638 Channel_type::do_hash_for_method(Gogo* gogo) const
8640 unsigned int ret = 0;
8641 if (this->may_send_)
8642 ret += 1;
8643 if (this->may_receive_)
8644 ret += 2;
8645 if (this->element_type_ != NULL)
8646 ret += this->element_type_->hash_for_method(gogo) << 2;
8647 return ret << 3;
8650 // Whether this type is the same as T.
8652 bool
8653 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8654 bool errors_are_identical) const
8656 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8657 cmp_tags, errors_are_identical, NULL))
8658 return false;
8659 return (this->may_send_ == t->may_send_
8660 && this->may_receive_ == t->may_receive_);
8663 // Return the backend representation for a channel type. A channel is a pointer
8664 // to a __go_channel struct. The __go_channel struct is defined in
8665 // libgo/runtime/channel.h.
8667 Btype*
8668 Channel_type::do_get_backend(Gogo* gogo)
8670 static Btype* backend_channel_type;
8671 if (backend_channel_type == NULL)
8673 std::vector<Backend::Btyped_identifier> bfields;
8674 Btype* bt = gogo->backend()->struct_type(bfields);
8675 bt = gogo->backend()->named_type("__go_channel", bt,
8676 Linemap::predeclared_location());
8677 backend_channel_type = gogo->backend()->pointer_type(bt);
8679 return backend_channel_type;
8682 // Build a type descriptor for a channel type.
8684 Type*
8685 Channel_type::make_chan_type_descriptor_type()
8687 static Type* ret;
8688 if (ret == NULL)
8690 Type* tdt = Type::make_type_descriptor_type();
8691 Type* ptdt = Type::make_type_descriptor_ptr_type();
8693 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8695 Struct_type* sf =
8696 Type::make_builtin_struct_type(3,
8697 "", tdt,
8698 "elem", ptdt,
8699 "dir", uintptr_type);
8701 ret = Type::make_builtin_named_type("ChanType", sf);
8704 return ret;
8707 // Build a type descriptor for a map type.
8709 Expression*
8710 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8712 Location bloc = Linemap::predeclared_location();
8714 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8716 const Struct_field_list* fields = ctdt->struct_type()->fields();
8718 Expression_list* vals = new Expression_list();
8719 vals->reserve(3);
8721 Struct_field_list::const_iterator p = fields->begin();
8722 go_assert(p->is_field_name("_type"));
8723 vals->push_back(this->type_descriptor_constructor(gogo,
8724 RUNTIME_TYPE_KIND_CHAN,
8725 name, NULL, true));
8727 ++p;
8728 go_assert(p->is_field_name("elem"));
8729 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8731 ++p;
8732 go_assert(p->is_field_name("dir"));
8733 // These bits must match the ones in libgo/runtime/go-type.h.
8734 int val = 0;
8735 if (this->may_receive_)
8736 val |= 1;
8737 if (this->may_send_)
8738 val |= 2;
8739 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8741 ++p;
8742 go_assert(p == fields->end());
8744 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8747 // Reflection string.
8749 void
8750 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8752 if (!this->may_send_)
8753 ret->append("<-");
8754 ret->append("chan");
8755 if (!this->may_receive_)
8756 ret->append("<-");
8757 ret->push_back(' ');
8758 this->append_reflection(this->element_type_, gogo, ret);
8761 // Mangled name.
8763 void
8764 Channel_type::do_mangled_name(Gogo* gogo, std::string* ret) const
8766 ret->push_back('C');
8767 this->append_mangled_name(this->element_type_, gogo, ret);
8768 if (this->may_send_)
8769 ret->push_back('s');
8770 if (this->may_receive_)
8771 ret->push_back('r');
8772 ret->push_back('e');
8775 // Export.
8777 void
8778 Channel_type::do_export(Export* exp) const
8780 exp->write_c_string("chan ");
8781 if (this->may_send_ && !this->may_receive_)
8782 exp->write_c_string("-< ");
8783 else if (this->may_receive_ && !this->may_send_)
8784 exp->write_c_string("<- ");
8785 exp->write_type(this->element_type_);
8788 // Import.
8790 Channel_type*
8791 Channel_type::do_import(Import* imp)
8793 imp->require_c_string("chan ");
8795 bool may_send;
8796 bool may_receive;
8797 if (imp->match_c_string("-< "))
8799 imp->advance(3);
8800 may_send = true;
8801 may_receive = false;
8803 else if (imp->match_c_string("<- "))
8805 imp->advance(3);
8806 may_receive = true;
8807 may_send = false;
8809 else
8811 may_send = true;
8812 may_receive = true;
8815 Type* element_type = imp->read_type();
8817 return Type::make_channel_type(may_send, may_receive, element_type);
8820 // Return the type to manage a select statement with ncases case
8821 // statements. A value of this type is allocated on the stack. This
8822 // must match the type hselect in libgo/go/runtime/select.go.
8824 Type*
8825 Channel_type::select_type(int ncases)
8827 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8828 Type* uint16_type = Type::lookup_integer_type("uint16");
8830 static Struct_type* scase_type;
8831 if (scase_type == NULL)
8833 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8834 Type* uint64_type = Type::lookup_integer_type("uint64");
8835 scase_type =
8836 Type::make_builtin_struct_type(7,
8837 "elem", unsafe_pointer_type,
8838 "chan", unsafe_pointer_type,
8839 "pc", uintptr_type,
8840 "kind", uint16_type,
8841 "index", uint16_type,
8842 "receivedp", unsafe_pointer_type,
8843 "releasetime", uint64_type);
8844 scase_type->set_is_struct_incomparable();
8847 Expression* ncases_expr =
8848 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8849 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8850 scases->set_is_array_incomparable();
8851 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8852 order->set_is_array_incomparable();
8854 Struct_type* ret =
8855 Type::make_builtin_struct_type(7,
8856 "tcase", uint16_type,
8857 "ncase", uint16_type,
8858 "pollorder", unsafe_pointer_type,
8859 "lockorder", unsafe_pointer_type,
8860 "scase", scases,
8861 "lockorderarr", order,
8862 "pollorderarr", order);
8863 ret->set_is_struct_incomparable();
8864 return ret;
8867 // Make a new channel type.
8869 Channel_type*
8870 Type::make_channel_type(bool send, bool receive, Type* element_type)
8872 return new Channel_type(send, receive, element_type);
8875 // Class Interface_type.
8877 // Return the list of methods.
8879 const Typed_identifier_list*
8880 Interface_type::methods() const
8882 go_assert(this->methods_are_finalized_ || saw_errors());
8883 return this->all_methods_;
8886 // Return the number of methods.
8888 size_t
8889 Interface_type::method_count() const
8891 go_assert(this->methods_are_finalized_ || saw_errors());
8892 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8895 // Traversal.
8898 Interface_type::do_traverse(Traverse* traverse)
8900 Typed_identifier_list* methods = (this->methods_are_finalized_
8901 ? this->all_methods_
8902 : this->parse_methods_);
8903 if (methods == NULL)
8904 return TRAVERSE_CONTINUE;
8905 return methods->traverse(traverse);
8908 // Finalize the methods. This handles interface inheritance.
8910 void
8911 Interface_type::finalize_methods()
8913 if (this->methods_are_finalized_)
8914 return;
8915 this->methods_are_finalized_ = true;
8916 if (this->parse_methods_ == NULL)
8917 return;
8919 this->all_methods_ = new Typed_identifier_list();
8920 this->all_methods_->reserve(this->parse_methods_->size());
8921 Typed_identifier_list inherit;
8922 for (Typed_identifier_list::const_iterator pm =
8923 this->parse_methods_->begin();
8924 pm != this->parse_methods_->end();
8925 ++pm)
8927 const Typed_identifier* p = &*pm;
8928 if (p->name().empty())
8929 inherit.push_back(*p);
8930 else if (this->find_method(p->name()) == NULL)
8931 this->all_methods_->push_back(*p);
8932 else
8933 go_error_at(p->location(), "duplicate method %qs",
8934 Gogo::message_name(p->name()).c_str());
8937 std::vector<Named_type*> seen;
8938 seen.reserve(inherit.size());
8939 bool issued_recursive_error = false;
8940 while (!inherit.empty())
8942 Type* t = inherit.back().type();
8943 Location tl = inherit.back().location();
8944 inherit.pop_back();
8946 Interface_type* it = t->interface_type();
8947 if (it == NULL)
8949 if (!t->is_error())
8950 go_error_at(tl, "interface contains embedded non-interface");
8951 continue;
8953 if (it == this)
8955 if (!issued_recursive_error)
8957 go_error_at(tl, "invalid recursive interface");
8958 issued_recursive_error = true;
8960 continue;
8963 Named_type* nt = t->named_type();
8964 if (nt != NULL && it->parse_methods_ != NULL)
8966 std::vector<Named_type*>::const_iterator q;
8967 for (q = seen.begin(); q != seen.end(); ++q)
8969 if (*q == nt)
8971 go_error_at(tl, "inherited interface loop");
8972 break;
8975 if (q != seen.end())
8976 continue;
8977 seen.push_back(nt);
8980 const Typed_identifier_list* imethods = it->parse_methods_;
8981 if (imethods == NULL)
8982 continue;
8983 for (Typed_identifier_list::const_iterator q = imethods->begin();
8984 q != imethods->end();
8985 ++q)
8987 if (q->name().empty())
8988 inherit.push_back(*q);
8989 else if (this->find_method(q->name()) == NULL)
8990 this->all_methods_->push_back(Typed_identifier(q->name(),
8991 q->type(), tl));
8992 else
8993 go_error_at(tl, "inherited method %qs is ambiguous",
8994 Gogo::message_name(q->name()).c_str());
8998 if (!this->all_methods_->empty())
8999 this->all_methods_->sort_by_name();
9000 else
9002 delete this->all_methods_;
9003 this->all_methods_ = NULL;
9007 // Return the method NAME, or NULL.
9009 const Typed_identifier*
9010 Interface_type::find_method(const std::string& name) const
9012 go_assert(this->methods_are_finalized_);
9013 if (this->all_methods_ == NULL)
9014 return NULL;
9015 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9016 p != this->all_methods_->end();
9017 ++p)
9018 if (p->name() == name)
9019 return &*p;
9020 return NULL;
9023 // Return the method index.
9025 size_t
9026 Interface_type::method_index(const std::string& name) const
9028 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
9029 size_t ret = 0;
9030 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9031 p != this->all_methods_->end();
9032 ++p, ++ret)
9033 if (p->name() == name)
9034 return ret;
9035 go_unreachable();
9038 // Return whether NAME is an unexported method, for better error
9039 // reporting.
9041 bool
9042 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
9044 go_assert(this->methods_are_finalized_);
9045 if (this->all_methods_ == NULL)
9046 return false;
9047 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9048 p != this->all_methods_->end();
9049 ++p)
9051 const std::string& method_name(p->name());
9052 if (Gogo::is_hidden_name(method_name)
9053 && name == Gogo::unpack_hidden_name(method_name)
9054 && gogo->pack_hidden_name(name, false) != method_name)
9055 return true;
9057 return false;
9060 // Whether this type is identical with T.
9062 bool
9063 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
9064 bool errors_are_identical) const
9066 // If methods have not been finalized, then we are asking whether
9067 // func redeclarations are the same. This is an error, so for
9068 // simplicity we say they are never the same.
9069 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
9070 return false;
9072 // We require the same methods with the same types. The methods
9073 // have already been sorted.
9074 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
9075 return this->all_methods_ == t->all_methods_;
9077 if (this->assume_identical(this, t) || t->assume_identical(t, this))
9078 return true;
9080 Assume_identical* hold_ai = this->assume_identical_;
9081 Assume_identical ai;
9082 ai.t1 = this;
9083 ai.t2 = t;
9084 ai.next = hold_ai;
9085 this->assume_identical_ = &ai;
9087 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
9088 Typed_identifier_list::const_iterator p2;
9089 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
9091 if (p1 == this->all_methods_->end())
9092 break;
9093 if (p1->name() != p2->name()
9094 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
9095 errors_are_identical, NULL))
9096 break;
9099 this->assume_identical_ = hold_ai;
9101 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
9104 // Return true if T1 and T2 are assumed to be identical during a type
9105 // comparison.
9107 bool
9108 Interface_type::assume_identical(const Interface_type* t1,
9109 const Interface_type* t2) const
9111 for (Assume_identical* p = this->assume_identical_;
9112 p != NULL;
9113 p = p->next)
9114 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
9115 return true;
9116 return false;
9119 // Whether we can assign the interface type T to this type. The types
9120 // are known to not be identical. An interface assignment is only
9121 // permitted if T is known to implement all methods in THIS.
9122 // Otherwise a type guard is required.
9124 bool
9125 Interface_type::is_compatible_for_assign(const Interface_type* t,
9126 std::string* reason) const
9128 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
9129 if (this->all_methods_ == NULL)
9130 return true;
9131 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9132 p != this->all_methods_->end();
9133 ++p)
9135 const Typed_identifier* m = t->find_method(p->name());
9136 if (m == NULL)
9138 if (reason != NULL)
9140 char buf[200];
9141 snprintf(buf, sizeof buf,
9142 _("need explicit conversion; missing method %s%s%s"),
9143 go_open_quote(), Gogo::message_name(p->name()).c_str(),
9144 go_close_quote());
9145 reason->assign(buf);
9147 return false;
9150 std::string subreason;
9151 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
9153 if (reason != NULL)
9155 std::string n = Gogo::message_name(p->name());
9156 size_t len = 100 + n.length() + subreason.length();
9157 char* buf = new char[len];
9158 if (subreason.empty())
9159 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9160 go_open_quote(), n.c_str(), go_close_quote());
9161 else
9162 snprintf(buf, len,
9163 _("incompatible type for method %s%s%s (%s)"),
9164 go_open_quote(), n.c_str(), go_close_quote(),
9165 subreason.c_str());
9166 reason->assign(buf);
9167 delete[] buf;
9169 return false;
9173 return true;
9176 // Hash code.
9178 unsigned int
9179 Interface_type::do_hash_for_method(Gogo*) const
9181 go_assert(this->methods_are_finalized_);
9182 unsigned int ret = 0;
9183 if (this->all_methods_ != NULL)
9185 for (Typed_identifier_list::const_iterator p =
9186 this->all_methods_->begin();
9187 p != this->all_methods_->end();
9188 ++p)
9190 ret = Type::hash_string(p->name(), ret);
9191 // We don't use the method type in the hash, to avoid
9192 // infinite recursion if an interface method uses a type
9193 // which is an interface which inherits from the interface
9194 // itself.
9195 // type T interface { F() interface {T}}
9196 ret <<= 1;
9199 return ret;
9202 // Return true if T implements the interface. If it does not, and
9203 // REASON is not NULL, set *REASON to a useful error message.
9205 bool
9206 Interface_type::implements_interface(const Type* t, std::string* reason) const
9208 go_assert(this->methods_are_finalized_);
9209 if (this->all_methods_ == NULL)
9210 return true;
9212 bool is_pointer = false;
9213 const Named_type* nt = t->named_type();
9214 const Struct_type* st = t->struct_type();
9215 // If we start with a named type, we don't dereference it to find
9216 // methods.
9217 if (nt == NULL)
9219 const Type* pt = t->points_to();
9220 if (pt != NULL)
9222 // If T is a pointer to a named type, then we need to look at
9223 // the type to which it points.
9224 is_pointer = true;
9225 nt = pt->named_type();
9226 st = pt->struct_type();
9230 // If we have a named type, get the methods from it rather than from
9231 // any struct type.
9232 if (nt != NULL)
9233 st = NULL;
9235 // Only named and struct types have methods.
9236 if (nt == NULL && st == NULL)
9238 if (reason != NULL)
9240 if (t->points_to() != NULL
9241 && t->points_to()->interface_type() != NULL)
9242 reason->assign(_("pointer to interface type has no methods"));
9243 else
9244 reason->assign(_("type has no methods"));
9246 return false;
9249 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
9251 if (reason != NULL)
9253 if (t->points_to() != NULL
9254 && t->points_to()->interface_type() != NULL)
9255 reason->assign(_("pointer to interface type has no methods"));
9256 else
9257 reason->assign(_("type has no methods"));
9259 return false;
9262 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9263 p != this->all_methods_->end();
9264 ++p)
9266 bool is_ambiguous = false;
9267 Method* m = (nt != NULL
9268 ? nt->method_function(p->name(), &is_ambiguous)
9269 : st->method_function(p->name(), &is_ambiguous));
9270 if (m == NULL)
9272 if (reason != NULL)
9274 std::string n = Gogo::message_name(p->name());
9275 size_t len = n.length() + 100;
9276 char* buf = new char[len];
9277 if (is_ambiguous)
9278 snprintf(buf, len, _("ambiguous method %s%s%s"),
9279 go_open_quote(), n.c_str(), go_close_quote());
9280 else
9281 snprintf(buf, len, _("missing method %s%s%s"),
9282 go_open_quote(), n.c_str(), go_close_quote());
9283 reason->assign(buf);
9284 delete[] buf;
9286 return false;
9289 Function_type *p_fn_type = p->type()->function_type();
9290 Function_type* m_fn_type = m->type()->function_type();
9291 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9292 std::string subreason;
9293 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9294 &subreason))
9296 if (reason != NULL)
9298 std::string n = Gogo::message_name(p->name());
9299 size_t len = 100 + n.length() + subreason.length();
9300 char* buf = new char[len];
9301 if (subreason.empty())
9302 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9303 go_open_quote(), n.c_str(), go_close_quote());
9304 else
9305 snprintf(buf, len,
9306 _("incompatible type for method %s%s%s (%s)"),
9307 go_open_quote(), n.c_str(), go_close_quote(),
9308 subreason.c_str());
9309 reason->assign(buf);
9310 delete[] buf;
9312 return false;
9315 if (!is_pointer && !m->is_value_method())
9317 if (reason != NULL)
9319 std::string n = Gogo::message_name(p->name());
9320 size_t len = 100 + n.length();
9321 char* buf = new char[len];
9322 snprintf(buf, len,
9323 _("method %s%s%s requires a pointer receiver"),
9324 go_open_quote(), n.c_str(), go_close_quote());
9325 reason->assign(buf);
9326 delete[] buf;
9328 return false;
9331 // If the magic //go:nointerface comment was used, the method
9332 // may not be used to implement interfaces.
9333 if (m->nointerface())
9335 if (reason != NULL)
9337 std::string n = Gogo::message_name(p->name());
9338 size_t len = 100 + n.length();
9339 char* buf = new char[len];
9340 snprintf(buf, len,
9341 _("method %s%s%s is marked go:nointerface"),
9342 go_open_quote(), n.c_str(), go_close_quote());
9343 reason->assign(buf);
9344 delete[] buf;
9346 return false;
9350 return true;
9353 // Return the backend representation of the empty interface type. We
9354 // use the same struct for all empty interfaces.
9356 Btype*
9357 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9359 static Btype* empty_interface_type;
9360 if (empty_interface_type == NULL)
9362 std::vector<Backend::Btyped_identifier> bfields(2);
9364 Location bloc = Linemap::predeclared_location();
9366 Type* pdt = Type::make_type_descriptor_ptr_type();
9367 bfields[0].name = "__type_descriptor";
9368 bfields[0].btype = pdt->get_backend(gogo);
9369 bfields[0].location = bloc;
9371 Type* vt = Type::make_pointer_type(Type::make_void_type());
9372 bfields[1].name = "__object";
9373 bfields[1].btype = vt->get_backend(gogo);
9374 bfields[1].location = bloc;
9376 empty_interface_type = gogo->backend()->struct_type(bfields);
9378 return empty_interface_type;
9381 // Return a pointer to the backend representation of the method table.
9383 Btype*
9384 Interface_type::get_backend_methods(Gogo* gogo)
9386 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9387 return this->bmethods_;
9389 Location loc = this->location();
9391 std::vector<Backend::Btyped_identifier>
9392 mfields(this->all_methods_->size() + 1);
9394 Type* pdt = Type::make_type_descriptor_ptr_type();
9395 mfields[0].name = "__type_descriptor";
9396 mfields[0].btype = pdt->get_backend(gogo);
9397 mfields[0].location = loc;
9399 std::string last_name = "";
9400 size_t i = 1;
9401 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9402 p != this->all_methods_->end();
9403 ++p, ++i)
9405 // The type of the method in Go only includes the parameters.
9406 // The actual method also has a receiver, which is always a
9407 // pointer. We need to add that pointer type here in order to
9408 // generate the correct type for the backend.
9409 Function_type* ft = p->type()->function_type();
9410 go_assert(ft->receiver() == NULL);
9412 const Typed_identifier_list* params = ft->parameters();
9413 Typed_identifier_list* mparams = new Typed_identifier_list();
9414 if (params != NULL)
9415 mparams->reserve(params->size() + 1);
9416 Type* vt = Type::make_pointer_type(Type::make_void_type());
9417 mparams->push_back(Typed_identifier("", vt, ft->location()));
9418 if (params != NULL)
9420 for (Typed_identifier_list::const_iterator pp = params->begin();
9421 pp != params->end();
9422 ++pp)
9423 mparams->push_back(*pp);
9426 Typed_identifier_list* mresults = (ft->results() == NULL
9427 ? NULL
9428 : ft->results()->copy());
9429 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9430 ft->location());
9432 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9433 mfields[i].btype = mft->get_backend_fntype(gogo);
9434 mfields[i].location = loc;
9436 // Sanity check: the names should be sorted.
9437 go_assert(Gogo::unpack_hidden_name(p->name())
9438 > Gogo::unpack_hidden_name(last_name));
9439 last_name = p->name();
9442 Btype* st = gogo->backend()->struct_type(mfields);
9443 Btype* ret = gogo->backend()->pointer_type(st);
9445 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
9446 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
9447 this->bmethods_ = ret;
9448 this->bmethods_is_placeholder_ = false;
9449 return ret;
9452 // Return a placeholder for the pointer to the backend methods table.
9454 Btype*
9455 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9457 if (this->bmethods_ == NULL)
9459 Location loc = this->location();
9460 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
9461 false);
9462 this->bmethods_is_placeholder_ = true;
9464 return this->bmethods_;
9467 // Return the fields of a non-empty interface type. This is not
9468 // declared in types.h so that types.h doesn't have to #include
9469 // backend.h.
9471 static void
9472 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9473 bool use_placeholder,
9474 std::vector<Backend::Btyped_identifier>* bfields)
9476 Location loc = type->location();
9478 bfields->resize(2);
9480 (*bfields)[0].name = "__methods";
9481 (*bfields)[0].btype = (use_placeholder
9482 ? type->get_backend_methods_placeholder(gogo)
9483 : type->get_backend_methods(gogo));
9484 (*bfields)[0].location = loc;
9486 Type* vt = Type::make_pointer_type(Type::make_void_type());
9487 (*bfields)[1].name = "__object";
9488 (*bfields)[1].btype = vt->get_backend(gogo);
9489 (*bfields)[1].location = Linemap::predeclared_location();
9492 // Return the backend representation for an interface type. An interface is a
9493 // pointer to a struct. The struct has three fields. The first field is a
9494 // pointer to the type descriptor for the dynamic type of the object.
9495 // The second field is a pointer to a table of methods for the
9496 // interface to be used with the object. The third field is the value
9497 // of the object itself.
9499 Btype*
9500 Interface_type::do_get_backend(Gogo* gogo)
9502 if (this->is_empty())
9503 return Interface_type::get_backend_empty_interface_type(gogo);
9504 else
9506 if (this->interface_btype_ != NULL)
9507 return this->interface_btype_;
9508 this->interface_btype_ =
9509 gogo->backend()->placeholder_struct_type("", this->location_);
9510 std::vector<Backend::Btyped_identifier> bfields;
9511 get_backend_interface_fields(gogo, this, false, &bfields);
9512 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9513 bfields))
9514 this->interface_btype_ = gogo->backend()->error_type();
9515 return this->interface_btype_;
9519 // Finish the backend representation of the methods.
9521 void
9522 Interface_type::finish_backend_methods(Gogo* gogo)
9524 if (!this->is_empty())
9526 const Typed_identifier_list* methods = this->methods();
9527 if (methods != NULL)
9529 for (Typed_identifier_list::const_iterator p = methods->begin();
9530 p != methods->end();
9531 ++p)
9532 p->type()->get_backend(gogo);
9535 // Getting the backend methods now will set the placeholder
9536 // pointer.
9537 this->get_backend_methods(gogo);
9541 // The type of an interface type descriptor.
9543 Type*
9544 Interface_type::make_interface_type_descriptor_type()
9546 static Type* ret;
9547 if (ret == NULL)
9549 Type* tdt = Type::make_type_descriptor_type();
9550 Type* ptdt = Type::make_type_descriptor_ptr_type();
9552 Type* string_type = Type::lookup_string_type();
9553 Type* pointer_string_type = Type::make_pointer_type(string_type);
9555 Struct_type* sm =
9556 Type::make_builtin_struct_type(3,
9557 "name", pointer_string_type,
9558 "pkgPath", pointer_string_type,
9559 "typ", ptdt);
9561 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9563 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9565 Struct_type* s = Type::make_builtin_struct_type(2,
9566 "", tdt,
9567 "methods", slice_nsm);
9569 ret = Type::make_builtin_named_type("InterfaceType", s);
9572 return ret;
9575 // Build a type descriptor for an interface type.
9577 Expression*
9578 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9580 Location bloc = Linemap::predeclared_location();
9582 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9584 const Struct_field_list* ifields = itdt->struct_type()->fields();
9586 Expression_list* ivals = new Expression_list();
9587 ivals->reserve(2);
9589 Struct_field_list::const_iterator pif = ifields->begin();
9590 go_assert(pif->is_field_name("_type"));
9591 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9592 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9593 true));
9595 ++pif;
9596 go_assert(pif->is_field_name("methods"));
9598 Expression_list* methods = new Expression_list();
9599 if (this->all_methods_ != NULL)
9601 Type* elemtype = pif->type()->array_type()->element_type();
9603 methods->reserve(this->all_methods_->size());
9604 for (Typed_identifier_list::const_iterator pm =
9605 this->all_methods_->begin();
9606 pm != this->all_methods_->end();
9607 ++pm)
9609 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9611 Expression_list* mvals = new Expression_list();
9612 mvals->reserve(3);
9614 Struct_field_list::const_iterator pmf = mfields->begin();
9615 go_assert(pmf->is_field_name("name"));
9616 std::string s = Gogo::unpack_hidden_name(pm->name());
9617 Expression* e = Expression::make_string(s, bloc);
9618 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9620 ++pmf;
9621 go_assert(pmf->is_field_name("pkgPath"));
9622 if (!Gogo::is_hidden_name(pm->name()))
9623 mvals->push_back(Expression::make_nil(bloc));
9624 else
9626 s = Gogo::hidden_name_pkgpath(pm->name());
9627 e = Expression::make_string(s, bloc);
9628 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9631 ++pmf;
9632 go_assert(pmf->is_field_name("typ"));
9633 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9635 ++pmf;
9636 go_assert(pmf == mfields->end());
9638 e = Expression::make_struct_composite_literal(elemtype, mvals,
9639 bloc);
9640 methods->push_back(e);
9644 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9645 methods, bloc));
9647 ++pif;
9648 go_assert(pif == ifields->end());
9650 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9653 // Reflection string.
9655 void
9656 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9658 ret->append("interface {");
9659 const Typed_identifier_list* methods = this->parse_methods_;
9660 if (methods != NULL)
9662 ret->push_back(' ');
9663 for (Typed_identifier_list::const_iterator p = methods->begin();
9664 p != methods->end();
9665 ++p)
9667 if (p != methods->begin())
9668 ret->append("; ");
9669 if (p->name().empty())
9670 this->append_reflection(p->type(), gogo, ret);
9671 else
9673 if (!Gogo::is_hidden_name(p->name()))
9674 ret->append(p->name());
9675 else if (gogo->pkgpath_from_option())
9676 ret->append(p->name().substr(1));
9677 else
9679 // If no -fgo-pkgpath option, backward compatibility
9680 // for how this used to work before -fgo-pkgpath was
9681 // introduced.
9682 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9683 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9684 ret->push_back('.');
9685 ret->append(Gogo::unpack_hidden_name(p->name()));
9687 std::string sub = p->type()->reflection(gogo);
9688 go_assert(sub.compare(0, 4, "func") == 0);
9689 sub = sub.substr(4);
9690 ret->append(sub);
9693 ret->push_back(' ');
9695 ret->append("}");
9698 // Mangled name.
9700 void
9701 Interface_type::do_mangled_name(Gogo* gogo, std::string* ret) const
9703 go_assert(this->methods_are_finalized_);
9705 ret->push_back('I');
9707 const Typed_identifier_list* methods = this->all_methods_;
9708 if (methods != NULL && !this->seen_)
9710 this->seen_ = true;
9711 for (Typed_identifier_list::const_iterator p = methods->begin();
9712 p != methods->end();
9713 ++p)
9715 if (!p->name().empty())
9717 std::string n(Gogo::mangle_possibly_hidden_name(p->name()));
9718 char buf[20];
9719 snprintf(buf, sizeof buf, "%u_",
9720 static_cast<unsigned int>(n.length()));
9721 ret->append(buf);
9722 ret->append(n);
9724 this->append_mangled_name(p->type(), gogo, ret);
9726 this->seen_ = false;
9729 ret->push_back('e');
9732 // Export.
9734 void
9735 Interface_type::do_export(Export* exp) const
9737 exp->write_c_string("interface { ");
9739 const Typed_identifier_list* methods = this->parse_methods_;
9740 if (methods != NULL)
9742 for (Typed_identifier_list::const_iterator pm = methods->begin();
9743 pm != methods->end();
9744 ++pm)
9746 if (pm->name().empty())
9748 exp->write_c_string("? ");
9749 exp->write_type(pm->type());
9751 else
9753 exp->write_string(pm->name());
9754 exp->write_c_string(" (");
9756 const Function_type* fntype = pm->type()->function_type();
9758 bool first = true;
9759 const Typed_identifier_list* parameters = fntype->parameters();
9760 if (parameters != NULL)
9762 bool is_varargs = fntype->is_varargs();
9763 for (Typed_identifier_list::const_iterator pp =
9764 parameters->begin();
9765 pp != parameters->end();
9766 ++pp)
9768 if (first)
9769 first = false;
9770 else
9771 exp->write_c_string(", ");
9772 exp->write_name(pp->name());
9773 exp->write_c_string(" ");
9774 if (!is_varargs || pp + 1 != parameters->end())
9775 exp->write_type(pp->type());
9776 else
9778 exp->write_c_string("...");
9779 Type *pptype = pp->type();
9780 exp->write_type(pptype->array_type()->element_type());
9785 exp->write_c_string(")");
9787 const Typed_identifier_list* results = fntype->results();
9788 if (results != NULL)
9790 exp->write_c_string(" ");
9791 if (results->size() == 1 && results->begin()->name().empty())
9792 exp->write_type(results->begin()->type());
9793 else
9795 first = true;
9796 exp->write_c_string("(");
9797 for (Typed_identifier_list::const_iterator p =
9798 results->begin();
9799 p != results->end();
9800 ++p)
9802 if (first)
9803 first = false;
9804 else
9805 exp->write_c_string(", ");
9806 exp->write_name(p->name());
9807 exp->write_c_string(" ");
9808 exp->write_type(p->type());
9810 exp->write_c_string(")");
9815 exp->write_c_string("; ");
9819 exp->write_c_string("}");
9822 // Import an interface type.
9824 Interface_type*
9825 Interface_type::do_import(Import* imp)
9827 imp->require_c_string("interface { ");
9829 Typed_identifier_list* methods = new Typed_identifier_list;
9830 while (imp->peek_char() != '}')
9832 std::string name = imp->read_identifier();
9834 if (name == "?")
9836 imp->require_c_string(" ");
9837 Type* t = imp->read_type();
9838 methods->push_back(Typed_identifier("", t, imp->location()));
9839 imp->require_c_string("; ");
9840 continue;
9843 imp->require_c_string(" (");
9845 Typed_identifier_list* parameters;
9846 bool is_varargs = false;
9847 if (imp->peek_char() == ')')
9848 parameters = NULL;
9849 else
9851 parameters = new Typed_identifier_list;
9852 while (true)
9854 std::string name = imp->read_name();
9855 imp->require_c_string(" ");
9857 if (imp->match_c_string("..."))
9859 imp->advance(3);
9860 is_varargs = true;
9863 Type* ptype = imp->read_type();
9864 if (is_varargs)
9865 ptype = Type::make_array_type(ptype, NULL);
9866 parameters->push_back(Typed_identifier(name, ptype,
9867 imp->location()));
9868 if (imp->peek_char() != ',')
9869 break;
9870 go_assert(!is_varargs);
9871 imp->require_c_string(", ");
9874 imp->require_c_string(")");
9876 Typed_identifier_list* results;
9877 if (imp->peek_char() != ' ')
9878 results = NULL;
9879 else
9881 results = new Typed_identifier_list;
9882 imp->advance(1);
9883 if (imp->peek_char() != '(')
9885 Type* rtype = imp->read_type();
9886 results->push_back(Typed_identifier("", rtype, imp->location()));
9888 else
9890 imp->advance(1);
9891 while (true)
9893 std::string name = imp->read_name();
9894 imp->require_c_string(" ");
9895 Type* rtype = imp->read_type();
9896 results->push_back(Typed_identifier(name, rtype,
9897 imp->location()));
9898 if (imp->peek_char() != ',')
9899 break;
9900 imp->require_c_string(", ");
9902 imp->require_c_string(")");
9906 Function_type* fntype = Type::make_function_type(NULL, parameters,
9907 results,
9908 imp->location());
9909 if (is_varargs)
9910 fntype->set_is_varargs();
9911 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9913 imp->require_c_string("; ");
9916 imp->require_c_string("}");
9918 if (methods->empty())
9920 delete methods;
9921 methods = NULL;
9924 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9925 ret->package_ = imp->package();
9926 return ret;
9929 // Make an interface type.
9931 Interface_type*
9932 Type::make_interface_type(Typed_identifier_list* methods,
9933 Location location)
9935 return new Interface_type(methods, location);
9938 // Make an empty interface type.
9940 Interface_type*
9941 Type::make_empty_interface_type(Location location)
9943 Interface_type* ret = new Interface_type(NULL, location);
9944 ret->finalize_methods();
9945 return ret;
9948 // Class Method.
9950 // Bind a method to an object.
9952 Expression*
9953 Method::bind_method(Expression* expr, Location location) const
9955 if (this->stub_ == NULL)
9957 // When there is no stub object, the binding is determined by
9958 // the child class.
9959 return this->do_bind_method(expr, location);
9961 return Expression::make_bound_method(expr, this, this->stub_, location);
9964 // Return the named object associated with a method. This may only be
9965 // called after methods are finalized.
9967 Named_object*
9968 Method::named_object() const
9970 if (this->stub_ != NULL)
9971 return this->stub_;
9972 return this->do_named_object();
9975 // Class Named_method.
9977 // The type of the method.
9979 Function_type*
9980 Named_method::do_type() const
9982 if (this->named_object_->is_function())
9983 return this->named_object_->func_value()->type();
9984 else if (this->named_object_->is_function_declaration())
9985 return this->named_object_->func_declaration_value()->type();
9986 else
9987 go_unreachable();
9990 // Return the location of the method receiver.
9992 Location
9993 Named_method::do_receiver_location() const
9995 return this->do_type()->receiver()->location();
9998 // Bind a method to an object.
10000 Expression*
10001 Named_method::do_bind_method(Expression* expr, Location location) const
10003 Named_object* no = this->named_object_;
10004 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
10005 no, location);
10006 // If this is not a local method, and it does not use a stub, then
10007 // the real method expects a different type. We need to cast the
10008 // first argument.
10009 if (this->depth() > 0 && !this->needs_stub_method())
10011 Function_type* ftype = this->do_type();
10012 go_assert(ftype->is_method());
10013 Type* frtype = ftype->receiver()->type();
10014 bme->set_first_argument_type(frtype);
10016 return bme;
10019 // Return whether this method should not participate in interfaces.
10021 bool
10022 Named_method::do_nointerface() const
10024 Named_object* no = this->named_object_;
10025 return no->is_function() && no->func_value()->nointerface();
10028 // Class Interface_method.
10030 // Bind a method to an object.
10032 Expression*
10033 Interface_method::do_bind_method(Expression* expr,
10034 Location location) const
10036 return Expression::make_interface_field_reference(expr, this->name_,
10037 location);
10040 // Class Methods.
10042 // Insert a new method. Return true if it was inserted, false
10043 // otherwise.
10045 bool
10046 Methods::insert(const std::string& name, Method* m)
10048 std::pair<Method_map::iterator, bool> ins =
10049 this->methods_.insert(std::make_pair(name, m));
10050 if (ins.second)
10051 return true;
10052 else
10054 Method* old_method = ins.first->second;
10055 if (m->depth() < old_method->depth())
10057 delete old_method;
10058 ins.first->second = m;
10059 return true;
10061 else
10063 if (m->depth() == old_method->depth())
10064 old_method->set_is_ambiguous();
10065 return false;
10070 // Return the number of unambiguous methods.
10072 size_t
10073 Methods::count() const
10075 size_t ret = 0;
10076 for (Method_map::const_iterator p = this->methods_.begin();
10077 p != this->methods_.end();
10078 ++p)
10079 if (!p->second->is_ambiguous())
10080 ++ret;
10081 return ret;
10084 // Class Named_type.
10086 // Return the name of the type.
10088 const std::string&
10089 Named_type::name() const
10091 return this->named_object_->name();
10094 // Return the name of the type to use in an error message.
10096 std::string
10097 Named_type::message_name() const
10099 return this->named_object_->message_name();
10102 // Return the base type for this type. We have to be careful about
10103 // circular type definitions, which are invalid but may be seen here.
10105 Type*
10106 Named_type::named_base()
10108 if (this->seen_)
10109 return this;
10110 this->seen_ = true;
10111 Type* ret = this->type_->base();
10112 this->seen_ = false;
10113 return ret;
10116 const Type*
10117 Named_type::named_base() const
10119 if (this->seen_)
10120 return this;
10121 this->seen_ = true;
10122 const Type* ret = this->type_->base();
10123 this->seen_ = false;
10124 return ret;
10127 // Return whether this is an error type. We have to be careful about
10128 // circular type definitions, which are invalid but may be seen here.
10130 bool
10131 Named_type::is_named_error_type() const
10133 if (this->seen_)
10134 return false;
10135 this->seen_ = true;
10136 bool ret = this->type_->is_error_type();
10137 this->seen_ = false;
10138 return ret;
10141 // Whether this type is comparable. We have to be careful about
10142 // circular type definitions.
10144 bool
10145 Named_type::named_type_is_comparable(std::string* reason) const
10147 if (this->seen_)
10148 return false;
10149 this->seen_ = true;
10150 bool ret = Type::are_compatible_for_comparison(true, this->type_,
10151 this->type_, reason);
10152 this->seen_ = false;
10153 return ret;
10156 // Add a method to this type.
10158 Named_object*
10159 Named_type::add_method(const std::string& name, Function* function)
10161 go_assert(!this->is_alias_);
10162 if (this->local_methods_ == NULL)
10163 this->local_methods_ = new Bindings(NULL);
10164 return this->local_methods_->add_function(name, NULL, function);
10167 // Add a method declaration to this type.
10169 Named_object*
10170 Named_type::add_method_declaration(const std::string& name, Package* package,
10171 Function_type* type,
10172 Location location)
10174 go_assert(!this->is_alias_);
10175 if (this->local_methods_ == NULL)
10176 this->local_methods_ = new Bindings(NULL);
10177 return this->local_methods_->add_function_declaration(name, package, type,
10178 location);
10181 // Add an existing method to this type.
10183 void
10184 Named_type::add_existing_method(Named_object* no)
10186 go_assert(!this->is_alias_);
10187 if (this->local_methods_ == NULL)
10188 this->local_methods_ = new Bindings(NULL);
10189 this->local_methods_->add_named_object(no);
10192 // Look for a local method NAME, and returns its named object, or NULL
10193 // if not there.
10195 Named_object*
10196 Named_type::find_local_method(const std::string& name) const
10198 if (this->is_error_)
10199 return NULL;
10200 if (this->is_alias_)
10202 Named_type* nt = this->type_->named_type();
10203 if (nt != NULL)
10205 if (this->seen_alias_)
10206 return NULL;
10207 this->seen_alias_ = true;
10208 Named_object* ret = nt->find_local_method(name);
10209 this->seen_alias_ = false;
10210 return ret;
10212 return NULL;
10214 if (this->local_methods_ == NULL)
10215 return NULL;
10216 return this->local_methods_->lookup(name);
10219 // Return the list of local methods.
10221 const Bindings*
10222 Named_type::local_methods() const
10224 if (this->is_error_)
10225 return NULL;
10226 if (this->is_alias_)
10228 Named_type* nt = this->type_->named_type();
10229 if (nt != NULL)
10231 if (this->seen_alias_)
10232 return NULL;
10233 this->seen_alias_ = true;
10234 const Bindings* ret = nt->local_methods();
10235 this->seen_alias_ = false;
10236 return ret;
10238 return NULL;
10240 return this->local_methods_;
10243 // Return whether NAME is an unexported field or method, for better
10244 // error reporting.
10246 bool
10247 Named_type::is_unexported_local_method(Gogo* gogo,
10248 const std::string& name) const
10250 if (this->is_error_)
10251 return false;
10252 if (this->is_alias_)
10254 Named_type* nt = this->type_->named_type();
10255 if (nt != NULL)
10257 if (this->seen_alias_)
10258 return false;
10259 this->seen_alias_ = true;
10260 bool ret = nt->is_unexported_local_method(gogo, name);
10261 this->seen_alias_ = false;
10262 return ret;
10264 return false;
10266 Bindings* methods = this->local_methods_;
10267 if (methods != NULL)
10269 for (Bindings::const_declarations_iterator p =
10270 methods->begin_declarations();
10271 p != methods->end_declarations();
10272 ++p)
10274 if (Gogo::is_hidden_name(p->first)
10275 && name == Gogo::unpack_hidden_name(p->first)
10276 && gogo->pack_hidden_name(name, false) != p->first)
10277 return true;
10280 return false;
10283 // Build the complete list of methods for this type, which means
10284 // recursively including all methods for anonymous fields. Create all
10285 // stub methods.
10287 void
10288 Named_type::finalize_methods(Gogo* gogo)
10290 if (this->is_alias_)
10291 return;
10292 if (this->all_methods_ != NULL)
10293 return;
10295 if (this->local_methods_ != NULL
10296 && (this->points_to() != NULL || this->interface_type() != NULL))
10298 const Bindings* lm = this->local_methods_;
10299 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10300 p != lm->end_declarations();
10301 ++p)
10302 go_error_at(p->second->location(),
10303 "invalid pointer or interface receiver type");
10304 delete this->local_methods_;
10305 this->local_methods_ = NULL;
10306 return;
10309 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10312 // Return whether this type has any methods.
10314 bool
10315 Named_type::has_any_methods() const
10317 if (this->is_error_)
10318 return false;
10319 if (this->is_alias_)
10321 if (this->type_->named_type() != NULL)
10323 if (this->seen_alias_)
10324 return false;
10325 this->seen_alias_ = true;
10326 bool ret = this->type_->named_type()->has_any_methods();
10327 this->seen_alias_ = false;
10328 return ret;
10330 if (this->type_->struct_type() != NULL)
10331 return this->type_->struct_type()->has_any_methods();
10332 return false;
10334 return this->all_methods_ != NULL;
10337 // Return the methods for this type.
10339 const Methods*
10340 Named_type::methods() const
10342 if (this->is_error_)
10343 return NULL;
10344 if (this->is_alias_)
10346 if (this->type_->named_type() != NULL)
10348 if (this->seen_alias_)
10349 return NULL;
10350 this->seen_alias_ = true;
10351 const Methods* ret = this->type_->named_type()->methods();
10352 this->seen_alias_ = false;
10353 return ret;
10355 if (this->type_->struct_type() != NULL)
10356 return this->type_->struct_type()->methods();
10357 return NULL;
10359 return this->all_methods_;
10362 // Return the method NAME, or NULL if there isn't one or if it is
10363 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10364 // ambiguous.
10366 Method*
10367 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10369 if (this->is_error_)
10370 return NULL;
10371 if (this->is_alias_)
10373 if (is_ambiguous != NULL)
10374 *is_ambiguous = false;
10375 if (this->type_->named_type() != NULL)
10377 if (this->seen_alias_)
10378 return NULL;
10379 this->seen_alias_ = true;
10380 Named_type* nt = this->type_->named_type();
10381 Method* ret = nt->method_function(name, is_ambiguous);
10382 this->seen_alias_ = false;
10383 return ret;
10385 if (this->type_->struct_type() != NULL)
10386 return this->type_->struct_type()->method_function(name, is_ambiguous);
10387 return NULL;
10389 return Type::method_function(this->all_methods_, name, is_ambiguous);
10392 // Return a pointer to the interface method table for this type for
10393 // the interface INTERFACE. IS_POINTER is true if this is for a
10394 // pointer to THIS.
10396 Expression*
10397 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10399 if (this->is_error_)
10400 return Expression::make_error(this->location_);
10401 if (this->is_alias_)
10403 if (this->type_->named_type() != NULL)
10405 if (this->seen_alias_)
10406 return Expression::make_error(this->location_);
10407 this->seen_alias_ = true;
10408 Named_type* nt = this->type_->named_type();
10409 Expression* ret = nt->interface_method_table(interface, is_pointer);
10410 this->seen_alias_ = false;
10411 return ret;
10413 if (this->type_->struct_type() != NULL)
10414 return this->type_->struct_type()->interface_method_table(interface,
10415 is_pointer);
10416 go_unreachable();
10418 return Type::interface_method_table(this, interface, is_pointer,
10419 &this->interface_method_tables_,
10420 &this->pointer_interface_method_tables_);
10423 // Look for a use of a complete type within another type. This is
10424 // used to check that we don't try to use a type within itself.
10426 class Find_type_use : public Traverse
10428 public:
10429 Find_type_use(Named_type* find_type)
10430 : Traverse(traverse_types),
10431 find_type_(find_type), found_(false)
10434 // Whether we found the type.
10435 bool
10436 found() const
10437 { return this->found_; }
10439 protected:
10441 type(Type*);
10443 private:
10444 // The type we are looking for.
10445 Named_type* find_type_;
10446 // Whether we found the type.
10447 bool found_;
10450 // Check for FIND_TYPE in TYPE.
10453 Find_type_use::type(Type* type)
10455 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10457 this->found_ = true;
10458 return TRAVERSE_EXIT;
10461 // It's OK if we see a reference to the type in any type which is
10462 // essentially a pointer: a pointer, a slice, a function, a map, or
10463 // a channel.
10464 if (type->points_to() != NULL
10465 || type->is_slice_type()
10466 || type->function_type() != NULL
10467 || type->map_type() != NULL
10468 || type->channel_type() != NULL)
10469 return TRAVERSE_SKIP_COMPONENTS;
10471 // For an interface, a reference to the type in a method type should
10472 // be ignored, but we have to consider direct inheritance. When
10473 // this is called, there may be cases of direct inheritance
10474 // represented as a method with no name.
10475 if (type->interface_type() != NULL)
10477 const Typed_identifier_list* methods = type->interface_type()->methods();
10478 if (methods != NULL)
10480 for (Typed_identifier_list::const_iterator p = methods->begin();
10481 p != methods->end();
10482 ++p)
10484 if (p->name().empty())
10486 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10487 return TRAVERSE_EXIT;
10491 return TRAVERSE_SKIP_COMPONENTS;
10494 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10495 // to convert TYPE to the backend representation before we convert
10496 // FIND_TYPE_.
10497 if (type->named_type() != NULL)
10499 switch (type->base()->classification())
10501 case Type::TYPE_ERROR:
10502 case Type::TYPE_BOOLEAN:
10503 case Type::TYPE_INTEGER:
10504 case Type::TYPE_FLOAT:
10505 case Type::TYPE_COMPLEX:
10506 case Type::TYPE_STRING:
10507 case Type::TYPE_NIL:
10508 break;
10510 case Type::TYPE_ARRAY:
10511 case Type::TYPE_STRUCT:
10512 this->find_type_->add_dependency(type->named_type());
10513 break;
10515 case Type::TYPE_NAMED:
10516 case Type::TYPE_FORWARD:
10517 go_assert(saw_errors());
10518 break;
10520 case Type::TYPE_VOID:
10521 case Type::TYPE_SINK:
10522 case Type::TYPE_FUNCTION:
10523 case Type::TYPE_POINTER:
10524 case Type::TYPE_CALL_MULTIPLE_RESULT:
10525 case Type::TYPE_MAP:
10526 case Type::TYPE_CHANNEL:
10527 case Type::TYPE_INTERFACE:
10528 default:
10529 go_unreachable();
10533 return TRAVERSE_CONTINUE;
10536 // Look for a circular reference of an alias.
10538 class Find_alias : public Traverse
10540 public:
10541 Find_alias(Named_type* find_type)
10542 : Traverse(traverse_types),
10543 find_type_(find_type), found_(false)
10546 // Whether we found the type.
10547 bool
10548 found() const
10549 { return this->found_; }
10551 protected:
10553 type(Type*);
10555 private:
10556 // The type we are looking for.
10557 Named_type* find_type_;
10558 // Whether we found the type.
10559 bool found_;
10563 Find_alias::type(Type* type)
10565 Named_type* nt = type->named_type();
10566 if (nt != NULL)
10568 if (nt == this->find_type_)
10570 this->found_ = true;
10571 return TRAVERSE_EXIT;
10574 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10575 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10576 // an alias itself, it's OK if whatever T2 is defined as refers
10577 // to T1.
10578 if (!nt->is_alias())
10579 return TRAVERSE_SKIP_COMPONENTS;
10582 return TRAVERSE_CONTINUE;
10585 // Verify that a named type does not refer to itself.
10587 bool
10588 Named_type::do_verify()
10590 if (this->is_verified_)
10591 return true;
10592 this->is_verified_ = true;
10594 if (this->is_error_)
10595 return false;
10597 if (this->is_alias_)
10599 Find_alias find(this);
10600 Type::traverse(this->type_, &find);
10601 if (find.found())
10603 go_error_at(this->location_, "invalid recursive alias %qs",
10604 this->message_name().c_str());
10605 this->is_error_ = true;
10606 return false;
10610 Find_type_use find(this);
10611 Type::traverse(this->type_, &find);
10612 if (find.found())
10614 go_error_at(this->location_, "invalid recursive type %qs",
10615 this->message_name().c_str());
10616 this->is_error_ = true;
10617 return false;
10620 // Check whether any of the local methods overloads an existing
10621 // struct field or interface method. We don't need to check the
10622 // list of methods against itself: that is handled by the Bindings
10623 // code.
10624 if (this->local_methods_ != NULL)
10626 Struct_type* st = this->type_->struct_type();
10627 if (st != NULL)
10629 for (Bindings::const_declarations_iterator p =
10630 this->local_methods_->begin_declarations();
10631 p != this->local_methods_->end_declarations();
10632 ++p)
10634 const std::string& name(p->first);
10635 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10637 go_error_at(p->second->location(),
10638 "method %qs redeclares struct field name",
10639 Gogo::message_name(name).c_str());
10645 return true;
10648 // Return whether this type is or contains a pointer.
10650 bool
10651 Named_type::do_has_pointer() const
10653 if (this->seen_)
10654 return false;
10655 this->seen_ = true;
10656 bool ret = this->type_->has_pointer();
10657 this->seen_ = false;
10658 return ret;
10661 // Return whether comparisons for this type can use the identity
10662 // function.
10664 bool
10665 Named_type::do_compare_is_identity(Gogo* gogo)
10667 // We don't use this->seen_ here because compare_is_identity may
10668 // call base() later, and that will mess up if seen_ is set here.
10669 if (this->seen_in_compare_is_identity_)
10670 return false;
10671 this->seen_in_compare_is_identity_ = true;
10672 bool ret = this->type_->compare_is_identity(gogo);
10673 this->seen_in_compare_is_identity_ = false;
10674 return ret;
10677 // Return whether this type is reflexive--whether it is always equal
10678 // to itself.
10680 bool
10681 Named_type::do_is_reflexive()
10683 if (this->seen_in_compare_is_identity_)
10684 return false;
10685 this->seen_in_compare_is_identity_ = true;
10686 bool ret = this->type_->is_reflexive();
10687 this->seen_in_compare_is_identity_ = false;
10688 return ret;
10691 // Return whether this type needs a key update when used as a map key.
10693 bool
10694 Named_type::do_needs_key_update()
10696 if (this->seen_in_compare_is_identity_)
10697 return true;
10698 this->seen_in_compare_is_identity_ = true;
10699 bool ret = this->type_->needs_key_update();
10700 this->seen_in_compare_is_identity_ = false;
10701 return ret;
10704 // Return a hash code. This is used for method lookup. We simply
10705 // hash on the name itself.
10707 unsigned int
10708 Named_type::do_hash_for_method(Gogo* gogo) const
10710 if (this->is_error_)
10711 return 0;
10713 // Aliases are handled in Type::hash_for_method.
10714 go_assert(!this->is_alias_);
10716 const std::string& name(this->named_object()->name());
10717 unsigned int ret = Type::hash_string(name, 0);
10719 // GOGO will be NULL here when called from Type_hash_identical.
10720 // That is OK because that is only used for internal hash tables
10721 // where we are going to be comparing named types for equality. In
10722 // other cases, which are cases where the runtime is going to
10723 // compare hash codes to see if the types are the same, we need to
10724 // include the pkgpath in the hash.
10725 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10727 const Package* package = this->named_object()->package();
10728 if (package == NULL)
10729 ret = Type::hash_string(gogo->pkgpath(), ret);
10730 else
10731 ret = Type::hash_string(package->pkgpath(), ret);
10734 return ret;
10737 // Convert a named type to the backend representation. In order to
10738 // get dependencies right, we fill in a dummy structure for this type,
10739 // then convert all the dependencies, then complete this type. When
10740 // this function is complete, the size of the type is known.
10742 void
10743 Named_type::convert(Gogo* gogo)
10745 if (this->is_error_ || this->is_converted_)
10746 return;
10748 this->create_placeholder(gogo);
10750 // If we are called to turn unsafe.Sizeof into a constant, we may
10751 // not have verified the type yet. We have to make sure it is
10752 // verified, since that sets the list of dependencies.
10753 this->verify();
10755 // Convert all the dependencies. If they refer indirectly back to
10756 // this type, they will pick up the intermediate representation we just
10757 // created.
10758 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10759 p != this->dependencies_.end();
10760 ++p)
10761 (*p)->convert(gogo);
10763 // Complete this type.
10764 Btype* bt = this->named_btype_;
10765 Type* base = this->type_->base();
10766 switch (base->classification())
10768 case TYPE_VOID:
10769 case TYPE_BOOLEAN:
10770 case TYPE_INTEGER:
10771 case TYPE_FLOAT:
10772 case TYPE_COMPLEX:
10773 case TYPE_STRING:
10774 case TYPE_NIL:
10775 break;
10777 case TYPE_MAP:
10778 case TYPE_CHANNEL:
10779 break;
10781 case TYPE_FUNCTION:
10782 case TYPE_POINTER:
10783 // The size of these types is already correct. We don't worry
10784 // about filling them in until later, when we also track
10785 // circular references.
10786 break;
10788 case TYPE_STRUCT:
10790 std::vector<Backend::Btyped_identifier> bfields;
10791 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10792 true, &bfields);
10793 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10794 bt = gogo->backend()->error_type();
10796 break;
10798 case TYPE_ARRAY:
10799 // Slice types were completed in create_placeholder.
10800 if (!base->is_slice_type())
10802 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10803 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10804 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10805 bt = gogo->backend()->error_type();
10807 break;
10809 case TYPE_INTERFACE:
10810 // Interface types were completed in create_placeholder.
10811 break;
10813 case TYPE_ERROR:
10814 return;
10816 default:
10817 case TYPE_SINK:
10818 case TYPE_CALL_MULTIPLE_RESULT:
10819 case TYPE_NAMED:
10820 case TYPE_FORWARD:
10821 go_unreachable();
10824 this->named_btype_ = bt;
10825 this->is_converted_ = true;
10826 this->is_placeholder_ = false;
10829 // Create the placeholder for a named type. This is the first step in
10830 // converting to the backend representation.
10832 void
10833 Named_type::create_placeholder(Gogo* gogo)
10835 if (this->is_error_)
10836 this->named_btype_ = gogo->backend()->error_type();
10838 if (this->named_btype_ != NULL)
10839 return;
10841 // Create the structure for this type. Note that because we call
10842 // base() here, we don't attempt to represent a named type defined
10843 // as another named type. Instead both named types will point to
10844 // different base representations.
10845 Type* base = this->type_->base();
10846 Btype* bt;
10847 bool set_name = true;
10848 switch (base->classification())
10850 case TYPE_ERROR:
10851 this->is_error_ = true;
10852 this->named_btype_ = gogo->backend()->error_type();
10853 return;
10855 case TYPE_VOID:
10856 case TYPE_BOOLEAN:
10857 case TYPE_INTEGER:
10858 case TYPE_FLOAT:
10859 case TYPE_COMPLEX:
10860 case TYPE_STRING:
10861 case TYPE_NIL:
10862 // These are simple basic types, we can just create them
10863 // directly.
10864 bt = Type::get_named_base_btype(gogo, base);
10865 break;
10867 case TYPE_MAP:
10868 case TYPE_CHANNEL:
10869 // All maps and channels have the same backend representation.
10870 bt = Type::get_named_base_btype(gogo, base);
10871 break;
10873 case TYPE_FUNCTION:
10874 case TYPE_POINTER:
10876 bool for_function = base->classification() == TYPE_FUNCTION;
10877 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10878 this->location_,
10879 for_function);
10880 set_name = false;
10882 break;
10884 case TYPE_STRUCT:
10885 bt = gogo->backend()->placeholder_struct_type(this->name(),
10886 this->location_);
10887 this->is_placeholder_ = true;
10888 set_name = false;
10889 break;
10891 case TYPE_ARRAY:
10892 if (base->is_slice_type())
10893 bt = gogo->backend()->placeholder_struct_type(this->name(),
10894 this->location_);
10895 else
10897 bt = gogo->backend()->placeholder_array_type(this->name(),
10898 this->location_);
10899 this->is_placeholder_ = true;
10901 set_name = false;
10902 break;
10904 case TYPE_INTERFACE:
10905 if (base->interface_type()->is_empty())
10906 bt = Interface_type::get_backend_empty_interface_type(gogo);
10907 else
10909 bt = gogo->backend()->placeholder_struct_type(this->name(),
10910 this->location_);
10911 set_name = false;
10913 break;
10915 default:
10916 case TYPE_SINK:
10917 case TYPE_CALL_MULTIPLE_RESULT:
10918 case TYPE_NAMED:
10919 case TYPE_FORWARD:
10920 go_unreachable();
10923 if (set_name)
10924 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10926 this->named_btype_ = bt;
10928 if (base->is_slice_type())
10930 // We do not record slices as dependencies of other types,
10931 // because we can fill them in completely here with the final
10932 // size.
10933 std::vector<Backend::Btyped_identifier> bfields;
10934 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10935 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10936 this->named_btype_ = gogo->backend()->error_type();
10938 else if (base->interface_type() != NULL
10939 && !base->interface_type()->is_empty())
10941 // We do not record interfaces as dependencies of other types,
10942 // because we can fill them in completely here with the final
10943 // size.
10944 std::vector<Backend::Btyped_identifier> bfields;
10945 get_backend_interface_fields(gogo, base->interface_type(), true,
10946 &bfields);
10947 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10948 this->named_btype_ = gogo->backend()->error_type();
10952 // Get the backend representation for a named type.
10954 Btype*
10955 Named_type::do_get_backend(Gogo* gogo)
10957 if (this->is_error_)
10958 return gogo->backend()->error_type();
10960 Btype* bt = this->named_btype_;
10962 if (!gogo->named_types_are_converted())
10964 // We have not completed converting named types. NAMED_BTYPE_
10965 // is a placeholder and we shouldn't do anything further.
10966 if (bt != NULL)
10967 return bt;
10969 // We don't build dependencies for types whose sizes do not
10970 // change or are not relevant, so we may see them here while
10971 // converting types.
10972 this->create_placeholder(gogo);
10973 bt = this->named_btype_;
10974 go_assert(bt != NULL);
10975 return bt;
10978 // We are not converting types. This should only be called if the
10979 // type has already been converted.
10980 if (!this->is_converted_)
10982 go_assert(saw_errors());
10983 return gogo->backend()->error_type();
10986 go_assert(bt != NULL);
10988 // Complete the backend representation.
10989 Type* base = this->type_->base();
10990 Btype* bt1;
10991 switch (base->classification())
10993 case TYPE_ERROR:
10994 return gogo->backend()->error_type();
10996 case TYPE_VOID:
10997 case TYPE_BOOLEAN:
10998 case TYPE_INTEGER:
10999 case TYPE_FLOAT:
11000 case TYPE_COMPLEX:
11001 case TYPE_STRING:
11002 case TYPE_NIL:
11003 case TYPE_MAP:
11004 case TYPE_CHANNEL:
11005 return bt;
11007 case TYPE_STRUCT:
11008 if (!this->seen_in_get_backend_)
11010 this->seen_in_get_backend_ = true;
11011 base->struct_type()->finish_backend_fields(gogo);
11012 this->seen_in_get_backend_ = false;
11014 return bt;
11016 case TYPE_ARRAY:
11017 if (!this->seen_in_get_backend_)
11019 this->seen_in_get_backend_ = true;
11020 base->array_type()->finish_backend_element(gogo);
11021 this->seen_in_get_backend_ = false;
11023 return bt;
11025 case TYPE_INTERFACE:
11026 if (!this->seen_in_get_backend_)
11028 this->seen_in_get_backend_ = true;
11029 base->interface_type()->finish_backend_methods(gogo);
11030 this->seen_in_get_backend_ = false;
11032 return bt;
11034 case TYPE_FUNCTION:
11035 // Don't build a circular data structure. GENERIC can't handle
11036 // it.
11037 if (this->seen_in_get_backend_)
11039 this->is_circular_ = true;
11040 return gogo->backend()->circular_pointer_type(bt, true);
11042 this->seen_in_get_backend_ = true;
11043 bt1 = Type::get_named_base_btype(gogo, base);
11044 this->seen_in_get_backend_ = false;
11045 if (this->is_circular_)
11046 bt1 = gogo->backend()->circular_pointer_type(bt, true);
11047 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11048 bt = gogo->backend()->error_type();
11049 return bt;
11051 case TYPE_POINTER:
11052 // Don't build a circular data structure. GENERIC can't handle
11053 // it.
11054 if (this->seen_in_get_backend_)
11056 this->is_circular_ = true;
11057 return gogo->backend()->circular_pointer_type(bt, false);
11059 this->seen_in_get_backend_ = true;
11060 bt1 = Type::get_named_base_btype(gogo, base);
11061 this->seen_in_get_backend_ = false;
11062 if (this->is_circular_)
11063 bt1 = gogo->backend()->circular_pointer_type(bt, false);
11064 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11065 bt = gogo->backend()->error_type();
11066 return bt;
11068 default:
11069 case TYPE_SINK:
11070 case TYPE_CALL_MULTIPLE_RESULT:
11071 case TYPE_NAMED:
11072 case TYPE_FORWARD:
11073 go_unreachable();
11076 go_unreachable();
11079 // Build a type descriptor for a named type.
11081 Expression*
11082 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11084 if (this->is_error_)
11085 return Expression::make_error(this->location_);
11086 if (name == NULL && this->is_alias_)
11088 if (this->seen_alias_)
11089 return Expression::make_error(this->location_);
11090 this->seen_alias_ = true;
11091 Expression* ret = this->type_->type_descriptor(gogo, NULL);
11092 this->seen_alias_ = false;
11093 return ret;
11096 // If NAME is not NULL, then we don't really want the type
11097 // descriptor for this type; we want the descriptor for the
11098 // underlying type, giving it the name NAME.
11099 return this->named_type_descriptor(gogo, this->type_,
11100 name == NULL ? this : name);
11103 // Add to the reflection string. This is used mostly for the name of
11104 // the type used in a type descriptor, not for actual reflection
11105 // strings.
11107 void
11108 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
11110 this->append_reflection_type_name(gogo, false, ret);
11113 // Add to the reflection string. For an alias we normally use the
11114 // real name, but if USE_ALIAS is true we use the alias name itself.
11116 void
11117 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
11118 std::string* ret) const
11120 if (this->is_error_)
11121 return;
11122 if (this->is_alias_ && !use_alias)
11124 if (this->seen_alias_)
11125 return;
11126 this->seen_alias_ = true;
11127 this->append_reflection(this->type_, gogo, ret);
11128 this->seen_alias_ = false;
11129 return;
11131 if (!this->is_builtin())
11133 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
11134 // make a unique reflection string, so that the type
11135 // canonicalization in the reflect package will work. In order
11136 // to be compatible with the gc compiler, we put tabs into the
11137 // package path, so that the reflect methods can discard it.
11138 const Package* package = this->named_object_->package();
11139 ret->push_back('\t');
11140 ret->append(package != NULL
11141 ? package->pkgpath_symbol()
11142 : gogo->pkgpath_symbol());
11143 ret->push_back('\t');
11144 ret->append(package != NULL
11145 ? package->package_name()
11146 : gogo->package_name());
11147 ret->push_back('.');
11149 if (this->in_function_ != NULL)
11151 ret->push_back('\t');
11152 const Typed_identifier* rcvr =
11153 this->in_function_->func_value()->type()->receiver();
11154 if (rcvr != NULL)
11156 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11157 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
11158 ret->push_back('.');
11160 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
11161 ret->push_back('$');
11162 if (this->in_function_index_ > 0)
11164 char buf[30];
11165 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11166 ret->append(buf);
11167 ret->push_back('$');
11169 ret->push_back('\t');
11171 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
11174 // Get the mangled name.
11176 void
11177 Named_type::do_mangled_name(Gogo* gogo, std::string* ret) const
11179 this->append_mangled_type_name(gogo, false, ret);
11182 // Get the mangled name. For an alias we normally get the real name,
11183 // but if USE_ALIAS is true we use the alias name itself.
11185 void
11186 Named_type::append_mangled_type_name(Gogo* gogo, bool use_alias,
11187 std::string* ret) const
11189 if (this->is_error_)
11190 return;
11191 if (this->is_alias_ && !use_alias)
11193 if (this->seen_alias_)
11194 return;
11195 this->seen_alias_ = true;
11196 this->append_mangled_name(this->type_, gogo, ret);
11197 this->seen_alias_ = false;
11198 return;
11200 Named_object* no = this->named_object_;
11201 std::string name;
11202 if (this->is_builtin())
11203 go_assert(this->in_function_ == NULL);
11204 else
11206 const std::string& pkgpath(no->package() == NULL
11207 ? gogo->pkgpath_symbol()
11208 : no->package()->pkgpath_symbol());
11209 name = pkgpath;
11210 name.append(1, '.');
11211 if (this->in_function_ != NULL)
11213 const Typed_identifier* rcvr =
11214 this->in_function_->func_value()->type()->receiver();
11215 if (rcvr != NULL)
11217 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11218 name.append(Gogo::unpack_hidden_name(rcvr_type->name()));
11219 name.append(1, '.');
11221 name.append(Gogo::unpack_hidden_name(this->in_function_->name()));
11222 name.append(1, '$');
11223 if (this->in_function_index_ > 0)
11225 char buf[30];
11226 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11227 name.append(buf);
11228 name.append(1, '$');
11232 name.append(Gogo::unpack_hidden_name(no->name()));
11233 char buf[20];
11234 snprintf(buf, sizeof buf, "N%u_", static_cast<unsigned int>(name.length()));
11235 ret->append(buf);
11236 ret->append(name);
11239 // Export the type. This is called to export a global type.
11241 void
11242 Named_type::export_named_type(Export* exp, const std::string&) const
11244 // We don't need to write the name of the type here, because it will
11245 // be written by Export::write_type anyhow.
11246 exp->write_c_string("type ");
11247 exp->write_type(this);
11248 exp->write_c_string(";\n");
11251 // Import a named type.
11253 void
11254 Named_type::import_named_type(Import* imp, Named_type** ptype)
11256 imp->require_c_string("type ");
11257 Type *type = imp->read_type();
11258 *ptype = type->named_type();
11259 go_assert(*ptype != NULL);
11260 imp->require_c_string(";\n");
11263 // Export the type when it is referenced by another type. In this
11264 // case Export::export_type will already have issued the name.
11266 void
11267 Named_type::do_export(Export* exp) const
11269 exp->write_type(this->type_);
11271 // To save space, we only export the methods directly attached to
11272 // this type.
11273 Bindings* methods = this->local_methods_;
11274 if (methods == NULL)
11275 return;
11277 exp->write_c_string("\n");
11278 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
11279 p != methods->end_definitions();
11280 ++p)
11282 exp->write_c_string(" ");
11283 (*p)->export_named_object(exp);
11286 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
11287 p != methods->end_declarations();
11288 ++p)
11290 if (p->second->is_function_declaration())
11292 exp->write_c_string(" ");
11293 p->second->export_named_object(exp);
11298 // Make a named type.
11300 Named_type*
11301 Type::make_named_type(Named_object* named_object, Type* type,
11302 Location location)
11304 return new Named_type(named_object, type, location);
11307 // Finalize the methods for TYPE. It will be a named type or a struct
11308 // type. This sets *ALL_METHODS to the list of methods, and builds
11309 // all required stubs.
11311 void
11312 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
11313 Methods** all_methods)
11315 *all_methods = new Methods();
11316 std::vector<const Named_type*> seen;
11317 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
11318 if ((*all_methods)->empty())
11320 delete *all_methods;
11321 *all_methods = NULL;
11323 Type::build_stub_methods(gogo, type, *all_methods, location);
11326 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11327 // build up the struct field indexes as we go. DEPTH is the depth of
11328 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11329 // adding these methods for an anonymous field with pointer type.
11330 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11331 // calls the real method. TYPES_SEEN is used to avoid infinite
11332 // recursion.
11334 void
11335 Type::add_methods_for_type(const Type* type,
11336 const Method::Field_indexes* field_indexes,
11337 unsigned int depth,
11338 bool is_embedded_pointer,
11339 bool needs_stub_method,
11340 std::vector<const Named_type*>* seen,
11341 Methods* methods)
11343 // Pointer types may not have methods.
11344 if (type->points_to() != NULL)
11345 return;
11347 const Named_type* nt = type->named_type();
11348 if (nt != NULL)
11350 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11351 p != seen->end();
11352 ++p)
11354 if (*p == nt)
11355 return;
11358 seen->push_back(nt);
11360 Type::add_local_methods_for_type(nt, field_indexes, depth,
11361 is_embedded_pointer, needs_stub_method,
11362 methods);
11365 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11366 is_embedded_pointer, needs_stub_method,
11367 seen, methods);
11369 // If we are called with depth > 0, then we are looking at an
11370 // anonymous field of a struct. If such a field has interface type,
11371 // then we need to add the interface methods. We don't want to add
11372 // them when depth == 0, because we will already handle them
11373 // following the usual rules for an interface type.
11374 if (depth > 0)
11375 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11377 if (nt != NULL)
11378 seen->pop_back();
11381 // Add the local methods for the named type NT to *METHODS. The
11382 // parameters are as for add_methods_to_type.
11384 void
11385 Type::add_local_methods_for_type(const Named_type* nt,
11386 const Method::Field_indexes* field_indexes,
11387 unsigned int depth,
11388 bool is_embedded_pointer,
11389 bool needs_stub_method,
11390 Methods* methods)
11392 const Bindings* local_methods = nt->local_methods();
11393 if (local_methods == NULL)
11394 return;
11396 for (Bindings::const_declarations_iterator p =
11397 local_methods->begin_declarations();
11398 p != local_methods->end_declarations();
11399 ++p)
11401 Named_object* no = p->second;
11402 bool is_value_method = (is_embedded_pointer
11403 || !Type::method_expects_pointer(no));
11404 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11405 (needs_stub_method || depth > 0));
11406 if (!methods->insert(no->name(), m))
11407 delete m;
11411 // Add the embedded methods for TYPE to *METHODS. These are the
11412 // methods attached to anonymous fields. The parameters are as for
11413 // add_methods_to_type.
11415 void
11416 Type::add_embedded_methods_for_type(const Type* type,
11417 const Method::Field_indexes* field_indexes,
11418 unsigned int depth,
11419 bool is_embedded_pointer,
11420 bool needs_stub_method,
11421 std::vector<const Named_type*>* seen,
11422 Methods* methods)
11424 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11425 // struct.
11426 const Struct_type* st = type->struct_type();
11427 if (st == NULL)
11428 return;
11430 const Struct_field_list* fields = st->fields();
11431 if (fields == NULL)
11432 return;
11434 unsigned int i = 0;
11435 for (Struct_field_list::const_iterator pf = fields->begin();
11436 pf != fields->end();
11437 ++pf, ++i)
11439 if (!pf->is_anonymous())
11440 continue;
11442 Type* ftype = pf->type();
11443 bool is_pointer = false;
11444 if (ftype->points_to() != NULL)
11446 ftype = ftype->points_to();
11447 is_pointer = true;
11449 Named_type* fnt = ftype->named_type();
11450 if (fnt == NULL)
11452 // This is an error, but it will be diagnosed elsewhere.
11453 continue;
11456 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11457 sub_field_indexes->next = field_indexes;
11458 sub_field_indexes->field_index = i;
11460 Methods tmp_methods;
11461 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11462 (is_embedded_pointer || is_pointer),
11463 (needs_stub_method
11464 || is_pointer
11465 || i > 0),
11466 seen,
11467 &tmp_methods);
11468 // Check if there are promoted methods that conflict with field names and
11469 // don't add them to the method map.
11470 for (Methods::const_iterator p = tmp_methods.begin();
11471 p != tmp_methods.end();
11472 ++p)
11474 bool found = false;
11475 for (Struct_field_list::const_iterator fp = fields->begin();
11476 fp != fields->end();
11477 ++fp)
11479 if (fp->field_name() == p->first)
11481 found = true;
11482 break;
11485 if (!found &&
11486 !methods->insert(p->first, p->second))
11487 delete p->second;
11492 // If TYPE is an interface type, then add its method to *METHODS.
11493 // This is for interface methods attached to an anonymous field. The
11494 // parameters are as for add_methods_for_type.
11496 void
11497 Type::add_interface_methods_for_type(const Type* type,
11498 const Method::Field_indexes* field_indexes,
11499 unsigned int depth,
11500 Methods* methods)
11502 const Interface_type* it = type->interface_type();
11503 if (it == NULL)
11504 return;
11506 const Typed_identifier_list* imethods = it->methods();
11507 if (imethods == NULL)
11508 return;
11510 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11511 pm != imethods->end();
11512 ++pm)
11514 Function_type* fntype = pm->type()->function_type();
11515 if (fntype == NULL)
11517 // This is an error, but it should be reported elsewhere
11518 // when we look at the methods for IT.
11519 continue;
11521 go_assert(!fntype->is_method());
11522 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11523 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11524 field_indexes, depth);
11525 if (!methods->insert(pm->name(), m))
11526 delete m;
11530 // Build stub methods for TYPE as needed. METHODS is the set of
11531 // methods for the type. A stub method may be needed when a type
11532 // inherits a method from an anonymous field. When we need the
11533 // address of the method, as in a type descriptor, we need to build a
11534 // little stub which does the required field dereferences and jumps to
11535 // the real method. LOCATION is the location of the type definition.
11537 void
11538 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11539 Location location)
11541 if (methods == NULL)
11542 return;
11543 for (Methods::const_iterator p = methods->begin();
11544 p != methods->end();
11545 ++p)
11547 Method* m = p->second;
11548 if (m->is_ambiguous() || !m->needs_stub_method())
11549 continue;
11551 const std::string& name(p->first);
11553 // Build a stub method.
11555 const Function_type* fntype = m->type();
11557 static unsigned int counter;
11558 char buf[100];
11559 snprintf(buf, sizeof buf, "$this%u", counter);
11560 ++counter;
11562 Type* receiver_type = const_cast<Type*>(type);
11563 if (!m->is_value_method())
11564 receiver_type = Type::make_pointer_type(receiver_type);
11565 Location receiver_location = m->receiver_location();
11566 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11567 receiver_location);
11569 const Typed_identifier_list* fnparams = fntype->parameters();
11570 Typed_identifier_list* stub_params;
11571 if (fnparams == NULL || fnparams->empty())
11572 stub_params = NULL;
11573 else
11575 // We give each stub parameter a unique name.
11576 stub_params = new Typed_identifier_list();
11577 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11578 pp != fnparams->end();
11579 ++pp)
11581 char pbuf[100];
11582 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11583 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11584 pp->location()));
11585 ++counter;
11589 const Typed_identifier_list* fnresults = fntype->results();
11590 Typed_identifier_list* stub_results;
11591 if (fnresults == NULL || fnresults->empty())
11592 stub_results = NULL;
11593 else
11595 // We create the result parameters without any names, since
11596 // we won't refer to them.
11597 stub_results = new Typed_identifier_list();
11598 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11599 pr != fnresults->end();
11600 ++pr)
11601 stub_results->push_back(Typed_identifier("", pr->type(),
11602 pr->location()));
11605 Function_type* stub_type = Type::make_function_type(receiver,
11606 stub_params,
11607 stub_results,
11608 fntype->location());
11609 if (fntype->is_varargs())
11610 stub_type->set_is_varargs();
11612 // We only create the function in the package which creates the
11613 // type.
11614 const Package* package;
11615 if (type->named_type() == NULL)
11616 package = NULL;
11617 else
11618 package = type->named_type()->named_object()->package();
11619 std::string stub_name = name + "$stub";
11620 Named_object* stub;
11621 if (package != NULL)
11622 stub = Named_object::make_function_declaration(stub_name, package,
11623 stub_type, location);
11624 else
11626 stub = gogo->start_function(stub_name, stub_type, false,
11627 fntype->location());
11628 Type::build_one_stub_method(gogo, m, buf, stub_params,
11629 fntype->is_varargs(), location);
11630 gogo->finish_function(fntype->location());
11632 if (type->named_type() == NULL && stub->is_function())
11633 stub->func_value()->set_is_unnamed_type_stub_method();
11634 if (m->nointerface() && stub->is_function())
11635 stub->func_value()->set_nointerface();
11638 m->set_stub_object(stub);
11642 // Build a stub method which adjusts the receiver as required to call
11643 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11644 // PARAMS is the list of function parameters.
11646 void
11647 Type::build_one_stub_method(Gogo* gogo, Method* method,
11648 const char* receiver_name,
11649 const Typed_identifier_list* params,
11650 bool is_varargs,
11651 Location location)
11653 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11654 go_assert(receiver_object != NULL);
11656 Expression* expr = Expression::make_var_reference(receiver_object, location);
11657 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11658 if (expr->type()->points_to() == NULL)
11659 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11661 Expression_list* arguments;
11662 if (params == NULL || params->empty())
11663 arguments = NULL;
11664 else
11666 arguments = new Expression_list();
11667 for (Typed_identifier_list::const_iterator p = params->begin();
11668 p != params->end();
11669 ++p)
11671 Named_object* param = gogo->lookup(p->name(), NULL);
11672 go_assert(param != NULL);
11673 Expression* param_ref = Expression::make_var_reference(param,
11674 location);
11675 arguments->push_back(param_ref);
11679 Expression* func = method->bind_method(expr, location);
11680 go_assert(func != NULL);
11681 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11682 location);
11684 gogo->add_statement(Statement::make_return_from_call(call, location));
11687 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11688 // in reverse order.
11690 Expression*
11691 Type::apply_field_indexes(Expression* expr,
11692 const Method::Field_indexes* field_indexes,
11693 Location location)
11695 if (field_indexes == NULL)
11696 return expr;
11697 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11698 Struct_type* stype = expr->type()->deref()->struct_type();
11699 go_assert(stype != NULL
11700 && field_indexes->field_index < stype->field_count());
11701 if (expr->type()->struct_type() == NULL)
11703 go_assert(expr->type()->points_to() != NULL);
11704 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
11705 go_assert(expr->type()->struct_type() == stype);
11707 return Expression::make_field_reference(expr, field_indexes->field_index,
11708 location);
11711 // Return whether NO is a method for which the receiver is a pointer.
11713 bool
11714 Type::method_expects_pointer(const Named_object* no)
11716 const Function_type *fntype;
11717 if (no->is_function())
11718 fntype = no->func_value()->type();
11719 else if (no->is_function_declaration())
11720 fntype = no->func_declaration_value()->type();
11721 else
11722 go_unreachable();
11723 return fntype->receiver()->type()->points_to() != NULL;
11726 // Given a set of methods for a type, METHODS, return the method NAME,
11727 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11728 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11729 // but is ambiguous (and return NULL).
11731 Method*
11732 Type::method_function(const Methods* methods, const std::string& name,
11733 bool* is_ambiguous)
11735 if (is_ambiguous != NULL)
11736 *is_ambiguous = false;
11737 if (methods == NULL)
11738 return NULL;
11739 Methods::const_iterator p = methods->find(name);
11740 if (p == methods->end())
11741 return NULL;
11742 Method* m = p->second;
11743 if (m->is_ambiguous())
11745 if (is_ambiguous != NULL)
11746 *is_ambiguous = true;
11747 return NULL;
11749 return m;
11752 // Return a pointer to the interface method table for TYPE for the
11753 // interface INTERFACE.
11755 Expression*
11756 Type::interface_method_table(Type* type,
11757 Interface_type *interface,
11758 bool is_pointer,
11759 Interface_method_tables** method_tables,
11760 Interface_method_tables** pointer_tables)
11762 go_assert(!interface->is_empty());
11764 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11766 if (*pimt == NULL)
11767 *pimt = new Interface_method_tables(5);
11769 std::pair<Interface_type*, Expression*> val(interface, NULL);
11770 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11772 Location loc = Linemap::predeclared_location();
11773 if (ins.second)
11775 // This is a new entry in the hash table.
11776 go_assert(ins.first->second == NULL);
11777 ins.first->second =
11778 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11780 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11783 // Look for field or method NAME for TYPE. Return an Expression for
11784 // the field or method bound to EXPR. If there is no such field or
11785 // method, give an appropriate error and return an error expression.
11787 Expression*
11788 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11789 const std::string& name,
11790 Location location)
11792 if (type->deref()->is_error_type())
11793 return Expression::make_error(location);
11795 const Named_type* nt = type->deref()->named_type();
11796 const Struct_type* st = type->deref()->struct_type();
11797 const Interface_type* it = type->interface_type();
11799 // If this is a pointer to a pointer, then it is possible that the
11800 // pointed-to type has methods.
11801 bool dereferenced = false;
11802 if (nt == NULL
11803 && st == NULL
11804 && it == NULL
11805 && type->points_to() != NULL
11806 && type->points_to()->points_to() != NULL)
11808 expr = Expression::make_unary(OPERATOR_MULT, expr, location);
11809 type = type->points_to();
11810 if (type->deref()->is_error_type())
11811 return Expression::make_error(location);
11812 nt = type->points_to()->named_type();
11813 st = type->points_to()->struct_type();
11814 dereferenced = true;
11817 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11818 || expr->is_addressable());
11819 std::vector<const Named_type*> seen;
11820 bool is_method = false;
11821 bool found_pointer_method = false;
11822 std::string ambig1;
11823 std::string ambig2;
11824 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11825 &seen, NULL, &is_method,
11826 &found_pointer_method, &ambig1, &ambig2))
11828 Expression* ret;
11829 if (!is_method)
11831 go_assert(st != NULL);
11832 if (type->struct_type() == NULL)
11834 if (dereferenced)
11836 go_error_at(location, "pointer type has no field %qs",
11837 Gogo::message_name(name).c_str());
11838 return Expression::make_error(location);
11840 go_assert(type->points_to() != NULL);
11841 expr = Expression::make_unary(OPERATOR_MULT, expr,
11842 location);
11843 go_assert(expr->type()->struct_type() == st);
11845 ret = st->field_reference(expr, name, location);
11847 else if (it != NULL && it->find_method(name) != NULL)
11848 ret = Expression::make_interface_field_reference(expr, name,
11849 location);
11850 else
11852 Method* m;
11853 if (nt != NULL)
11854 m = nt->method_function(name, NULL);
11855 else if (st != NULL)
11856 m = st->method_function(name, NULL);
11857 else
11858 go_unreachable();
11859 go_assert(m != NULL);
11860 if (dereferenced)
11862 go_error_at(location,
11863 "calling method %qs requires explicit dereference",
11864 Gogo::message_name(name).c_str());
11865 return Expression::make_error(location);
11867 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11868 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11869 ret = m->bind_method(expr, location);
11871 go_assert(ret != NULL);
11872 return ret;
11874 else
11876 if (Gogo::is_erroneous_name(name))
11878 // An error was already reported.
11880 else if (!ambig1.empty())
11881 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11882 Gogo::message_name(name).c_str(), ambig1.c_str(),
11883 ambig2.c_str());
11884 else if (found_pointer_method)
11885 go_error_at(location, "method requires a pointer receiver");
11886 else if (nt == NULL && st == NULL && it == NULL)
11887 go_error_at(location,
11888 ("reference to field %qs in object which "
11889 "has no fields or methods"),
11890 Gogo::message_name(name).c_str());
11891 else
11893 bool is_unexported;
11894 // The test for 'a' and 'z' is to handle builtin names,
11895 // which are not hidden.
11896 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11897 is_unexported = false;
11898 else
11900 std::string unpacked = Gogo::unpack_hidden_name(name);
11901 seen.clear();
11902 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11903 unpacked,
11904 &seen);
11906 if (is_unexported)
11907 go_error_at(location, "reference to unexported field or method %qs",
11908 Gogo::message_name(name).c_str());
11909 else
11910 go_error_at(location, "reference to undefined field or method %qs",
11911 Gogo::message_name(name).c_str());
11913 return Expression::make_error(location);
11917 // Look in TYPE for a field or method named NAME, return true if one
11918 // is found. This looks through embedded anonymous fields and handles
11919 // ambiguity. If a method is found, sets *IS_METHOD to true;
11920 // otherwise, if a field is found, set it to false. If
11921 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11922 // whose address can not be taken. SEEN is used to avoid infinite
11923 // recursion on invalid types.
11925 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11926 // method we couldn't use because it requires a pointer. LEVEL is
11927 // used for recursive calls, and can be NULL for a non-recursive call.
11928 // When this function returns false because it finds that the name is
11929 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11930 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11931 // will be unchanged.
11933 // This function just returns whether or not there is a field or
11934 // method, and whether it is a field or method. It doesn't build an
11935 // expression to refer to it. If it is a method, we then look in the
11936 // list of all methods for the type. If it is a field, the search has
11937 // to be done again, looking only for fields, and building up the
11938 // expression as we go.
11940 bool
11941 Type::find_field_or_method(const Type* type,
11942 const std::string& name,
11943 bool receiver_can_be_pointer,
11944 std::vector<const Named_type*>* seen,
11945 int* level,
11946 bool* is_method,
11947 bool* found_pointer_method,
11948 std::string* ambig1,
11949 std::string* ambig2)
11951 // Named types can have locally defined methods.
11952 const Named_type* nt = type->named_type();
11953 if (nt == NULL && type->points_to() != NULL)
11954 nt = type->points_to()->named_type();
11955 if (nt != NULL)
11957 Named_object* no = nt->find_local_method(name);
11958 if (no != NULL)
11960 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11962 *is_method = true;
11963 return true;
11966 // Record that we have found a pointer method in order to
11967 // give a better error message if we don't find anything
11968 // else.
11969 *found_pointer_method = true;
11972 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11973 p != seen->end();
11974 ++p)
11976 if (*p == nt)
11978 // We've already seen this type when searching for methods.
11979 return false;
11984 // Interface types can have methods.
11985 const Interface_type* it = type->interface_type();
11986 if (it != NULL && it->find_method(name) != NULL)
11988 *is_method = true;
11989 return true;
11992 // Struct types can have fields. They can also inherit fields and
11993 // methods from anonymous fields.
11994 const Struct_type* st = type->deref()->struct_type();
11995 if (st == NULL)
11996 return false;
11997 const Struct_field_list* fields = st->fields();
11998 if (fields == NULL)
11999 return false;
12001 if (nt != NULL)
12002 seen->push_back(nt);
12004 int found_level = 0;
12005 bool found_is_method = false;
12006 std::string found_ambig1;
12007 std::string found_ambig2;
12008 const Struct_field* found_parent = NULL;
12009 for (Struct_field_list::const_iterator pf = fields->begin();
12010 pf != fields->end();
12011 ++pf)
12013 if (pf->is_field_name(name))
12015 *is_method = false;
12016 if (nt != NULL)
12017 seen->pop_back();
12018 return true;
12021 if (!pf->is_anonymous())
12022 continue;
12024 if (pf->type()->deref()->is_error_type()
12025 || pf->type()->deref()->is_undefined())
12026 continue;
12028 Named_type* fnt = pf->type()->named_type();
12029 if (fnt == NULL)
12030 fnt = pf->type()->deref()->named_type();
12031 go_assert(fnt != NULL);
12033 // Methods with pointer receivers on embedded field are
12034 // inherited by the pointer to struct, and also by the struct
12035 // type if the field itself is a pointer.
12036 bool can_be_pointer = (receiver_can_be_pointer
12037 || pf->type()->points_to() != NULL);
12038 int sublevel = level == NULL ? 1 : *level + 1;
12039 bool sub_is_method;
12040 std::string subambig1;
12041 std::string subambig2;
12042 bool subfound = Type::find_field_or_method(fnt,
12043 name,
12044 can_be_pointer,
12045 seen,
12046 &sublevel,
12047 &sub_is_method,
12048 found_pointer_method,
12049 &subambig1,
12050 &subambig2);
12051 if (!subfound)
12053 if (!subambig1.empty())
12055 // The name was found via this field, but is ambiguous.
12056 // if the ambiguity is lower or at the same level as
12057 // anything else we have already found, then we want to
12058 // pass the ambiguity back to the caller.
12059 if (found_level == 0 || sublevel <= found_level)
12061 found_ambig1 = (Gogo::message_name(pf->field_name())
12062 + '.' + subambig1);
12063 found_ambig2 = (Gogo::message_name(pf->field_name())
12064 + '.' + subambig2);
12065 found_level = sublevel;
12069 else
12071 // The name was found via this field. Use the level to see
12072 // if we want to use this one, or whether it introduces an
12073 // ambiguity.
12074 if (found_level == 0 || sublevel < found_level)
12076 found_level = sublevel;
12077 found_is_method = sub_is_method;
12078 found_ambig1.clear();
12079 found_ambig2.clear();
12080 found_parent = &*pf;
12082 else if (sublevel > found_level)
12084 else if (found_ambig1.empty())
12086 // We found an ambiguity.
12087 go_assert(found_parent != NULL);
12088 found_ambig1 = Gogo::message_name(found_parent->field_name());
12089 found_ambig2 = Gogo::message_name(pf->field_name());
12091 else
12093 // We found an ambiguity, but we already know of one.
12094 // Just report the earlier one.
12099 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
12100 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
12101 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
12102 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
12104 if (nt != NULL)
12105 seen->pop_back();
12107 if (found_level == 0)
12108 return false;
12109 else if (found_is_method
12110 && type->named_type() != NULL
12111 && type->points_to() != NULL)
12113 // If this is a method inherited from a struct field in a named pointer
12114 // type, it is invalid to automatically dereference the pointer to the
12115 // struct to find this method.
12116 if (level != NULL)
12117 *level = found_level;
12118 *is_method = true;
12119 return false;
12121 else if (!found_ambig1.empty())
12123 go_assert(!found_ambig1.empty());
12124 ambig1->assign(found_ambig1);
12125 ambig2->assign(found_ambig2);
12126 if (level != NULL)
12127 *level = found_level;
12128 return false;
12130 else
12132 if (level != NULL)
12133 *level = found_level;
12134 *is_method = found_is_method;
12135 return true;
12139 // Return whether NAME is an unexported field or method for TYPE.
12141 bool
12142 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
12143 const std::string& name,
12144 std::vector<const Named_type*>* seen)
12146 const Named_type* nt = type->named_type();
12147 if (nt == NULL)
12148 nt = type->deref()->named_type();
12149 if (nt != NULL)
12151 if (nt->is_unexported_local_method(gogo, name))
12152 return true;
12154 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12155 p != seen->end();
12156 ++p)
12158 if (*p == nt)
12160 // We've already seen this type.
12161 return false;
12166 const Interface_type* it = type->interface_type();
12167 if (it != NULL && it->is_unexported_method(gogo, name))
12168 return true;
12170 type = type->deref();
12172 const Struct_type* st = type->struct_type();
12173 if (st != NULL && st->is_unexported_local_field(gogo, name))
12174 return true;
12176 if (st == NULL)
12177 return false;
12179 const Struct_field_list* fields = st->fields();
12180 if (fields == NULL)
12181 return false;
12183 if (nt != NULL)
12184 seen->push_back(nt);
12186 for (Struct_field_list::const_iterator pf = fields->begin();
12187 pf != fields->end();
12188 ++pf)
12190 if (pf->is_anonymous()
12191 && !pf->type()->deref()->is_error_type()
12192 && !pf->type()->deref()->is_undefined())
12194 Named_type* subtype = pf->type()->named_type();
12195 if (subtype == NULL)
12196 subtype = pf->type()->deref()->named_type();
12197 if (subtype == NULL)
12199 // This is an error, but it will be diagnosed elsewhere.
12200 continue;
12202 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
12204 if (nt != NULL)
12205 seen->pop_back();
12206 return true;
12211 if (nt != NULL)
12212 seen->pop_back();
12214 return false;
12217 // Class Forward_declaration.
12219 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
12220 : Type(TYPE_FORWARD),
12221 named_object_(named_object->resolve()), warned_(false)
12223 go_assert(this->named_object_->is_unknown()
12224 || this->named_object_->is_type_declaration());
12227 // Return the named object.
12229 Named_object*
12230 Forward_declaration_type::named_object()
12232 return this->named_object_->resolve();
12235 const Named_object*
12236 Forward_declaration_type::named_object() const
12238 return this->named_object_->resolve();
12241 // Return the name of the forward declared type.
12243 const std::string&
12244 Forward_declaration_type::name() const
12246 return this->named_object()->name();
12249 // Warn about a use of a type which has been declared but not defined.
12251 void
12252 Forward_declaration_type::warn() const
12254 Named_object* no = this->named_object_->resolve();
12255 if (no->is_unknown())
12257 // The name was not defined anywhere.
12258 if (!this->warned_)
12260 go_error_at(this->named_object_->location(),
12261 "use of undefined type %qs",
12262 no->message_name().c_str());
12263 this->warned_ = true;
12266 else if (no->is_type_declaration())
12268 // The name was seen as a type, but the type was never defined.
12269 if (no->type_declaration_value()->using_type())
12271 go_error_at(this->named_object_->location(),
12272 "use of undefined type %qs",
12273 no->message_name().c_str());
12274 this->warned_ = true;
12277 else
12279 // The name was defined, but not as a type.
12280 if (!this->warned_)
12282 go_error_at(this->named_object_->location(), "expected type");
12283 this->warned_ = true;
12288 // Get the base type of a declaration. This gives an error if the
12289 // type has not yet been defined.
12291 Type*
12292 Forward_declaration_type::real_type()
12294 if (this->is_defined())
12296 Named_type* nt = this->named_object()->type_value();
12297 if (!nt->is_valid())
12298 return Type::make_error_type();
12299 return this->named_object()->type_value();
12301 else
12303 this->warn();
12304 return Type::make_error_type();
12308 const Type*
12309 Forward_declaration_type::real_type() const
12311 if (this->is_defined())
12313 const Named_type* nt = this->named_object()->type_value();
12314 if (!nt->is_valid())
12315 return Type::make_error_type();
12316 return this->named_object()->type_value();
12318 else
12320 this->warn();
12321 return Type::make_error_type();
12325 // Return whether the base type is defined.
12327 bool
12328 Forward_declaration_type::is_defined() const
12330 return this->named_object()->is_type();
12333 // Add a method. This is used when methods are defined before the
12334 // type.
12336 Named_object*
12337 Forward_declaration_type::add_method(const std::string& name,
12338 Function* function)
12340 Named_object* no = this->named_object();
12341 if (no->is_unknown())
12342 no->declare_as_type();
12343 return no->type_declaration_value()->add_method(name, function);
12346 // Add a method declaration. This is used when methods are declared
12347 // before the type.
12349 Named_object*
12350 Forward_declaration_type::add_method_declaration(const std::string& name,
12351 Package* package,
12352 Function_type* type,
12353 Location location)
12355 Named_object* no = this->named_object();
12356 if (no->is_unknown())
12357 no->declare_as_type();
12358 Type_declaration* td = no->type_declaration_value();
12359 return td->add_method_declaration(name, package, type, location);
12362 // Add an already created object as a method.
12364 void
12365 Forward_declaration_type::add_existing_method(Named_object* nom)
12367 Named_object* no = this->named_object();
12368 if (no->is_unknown())
12369 no->declare_as_type();
12370 no->type_declaration_value()->add_existing_method(nom);
12373 // Traversal.
12376 Forward_declaration_type::do_traverse(Traverse* traverse)
12378 if (this->is_defined()
12379 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12380 return TRAVERSE_EXIT;
12381 return TRAVERSE_CONTINUE;
12384 // Verify the type.
12386 bool
12387 Forward_declaration_type::do_verify()
12389 if (!this->is_defined() && !this->is_nil_constant_as_type())
12391 this->warn();
12392 return false;
12394 return true;
12397 // Get the backend representation for the type.
12399 Btype*
12400 Forward_declaration_type::do_get_backend(Gogo* gogo)
12402 if (this->is_defined())
12403 return Type::get_named_base_btype(gogo, this->real_type());
12405 if (this->warned_)
12406 return gogo->backend()->error_type();
12408 // We represent an undefined type as a struct with no fields. That
12409 // should work fine for the backend, since the same case can arise
12410 // in C.
12411 std::vector<Backend::Btyped_identifier> fields;
12412 Btype* bt = gogo->backend()->struct_type(fields);
12413 return gogo->backend()->named_type(this->name(), bt,
12414 this->named_object()->location());
12417 // Build a type descriptor for a forwarded type.
12419 Expression*
12420 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12422 Location ploc = Linemap::predeclared_location();
12423 if (!this->is_defined())
12424 return Expression::make_error(ploc);
12425 else
12427 Type* t = this->real_type();
12428 if (name != NULL)
12429 return this->named_type_descriptor(gogo, t, name);
12430 else
12431 return Expression::make_error(this->named_object_->location());
12435 // The reflection string.
12437 void
12438 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12440 this->append_reflection(this->real_type(), gogo, ret);
12443 // The mangled name.
12445 void
12446 Forward_declaration_type::do_mangled_name(Gogo* gogo, std::string* ret) const
12448 if (this->is_defined())
12449 this->append_mangled_name(this->real_type(), gogo, ret);
12450 else
12452 const Named_object* no = this->named_object();
12453 std::string name;
12454 if (no->package() == NULL)
12455 name = gogo->pkgpath_symbol();
12456 else
12457 name = no->package()->pkgpath_symbol();
12458 name += '.';
12459 name += Gogo::unpack_hidden_name(no->name());
12460 char buf[20];
12461 snprintf(buf, sizeof buf, "N%u_",
12462 static_cast<unsigned int>(name.length()));
12463 ret->append(buf);
12464 ret->append(name);
12468 // Export a forward declaration. This can happen when a defined type
12469 // refers to a type which is only declared (and is presumably defined
12470 // in some other file in the same package).
12472 void
12473 Forward_declaration_type::do_export(Export*) const
12475 // If there is a base type, that should be exported instead of this.
12476 go_assert(!this->is_defined());
12478 // We don't output anything.
12481 // Make a forward declaration.
12483 Type*
12484 Type::make_forward_declaration(Named_object* named_object)
12486 return new Forward_declaration_type(named_object);
12489 // Class Typed_identifier_list.
12491 // Sort the entries by name.
12493 struct Typed_identifier_list_sort
12495 public:
12496 bool
12497 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12499 return (Gogo::unpack_hidden_name(t1.name())
12500 < Gogo::unpack_hidden_name(t2.name()));
12504 void
12505 Typed_identifier_list::sort_by_name()
12507 std::sort(this->entries_.begin(), this->entries_.end(),
12508 Typed_identifier_list_sort());
12511 // Traverse types.
12514 Typed_identifier_list::traverse(Traverse* traverse)
12516 for (Typed_identifier_list::const_iterator p = this->begin();
12517 p != this->end();
12518 ++p)
12520 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12521 return TRAVERSE_EXIT;
12523 return TRAVERSE_CONTINUE;
12526 // Copy the list.
12528 Typed_identifier_list*
12529 Typed_identifier_list::copy() const
12531 Typed_identifier_list* ret = new Typed_identifier_list();
12532 for (Typed_identifier_list::const_iterator p = this->begin();
12533 p != this->end();
12534 ++p)
12535 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12536 return ret;