Improve fstack_protector effective target
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob2274c3134678d0c6112795fbd21b2374e8a4f0ec
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_, location);
1210 Bexpression* var_addr =
1211 gogo->backend()->address_expression(var_expr, location);
1212 Type* td_type = Type::make_type_descriptor_type();
1213 Btype* td_btype = td_type->get_backend(gogo);
1214 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1215 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1218 // A mapping from unnamed types to type descriptor variables.
1220 Type::Type_descriptor_vars Type::type_descriptor_vars;
1222 // Build the type descriptor for this type.
1224 void
1225 Type::make_type_descriptor_var(Gogo* gogo)
1227 go_assert(this->type_descriptor_var_ == NULL);
1229 Named_type* nt = this->named_type();
1231 // We can have multiple instances of unnamed types, but we only want
1232 // to emit the type descriptor once. We use a hash table. This is
1233 // not necessary for named types, as they are unique, and we store
1234 // the type descriptor in the type itself.
1235 Bvariable** phash = NULL;
1236 if (nt == NULL)
1238 Bvariable* bvnull = NULL;
1239 std::pair<Type_descriptor_vars::iterator, bool> ins =
1240 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1241 if (!ins.second)
1243 // We've already built a type descriptor for this type.
1244 this->type_descriptor_var_ = ins.first->second;
1245 return;
1247 phash = &ins.first->second;
1250 // The type descriptor symbol for the unsafe.Pointer type is defined in
1251 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1252 // symbol if necessary.
1253 if (this->is_unsafe_pointer_type())
1255 Location bloc = Linemap::predeclared_location();
1257 Type* td_type = Type::make_type_descriptor_type();
1258 Btype* td_btype = td_type->get_backend(gogo);
1259 std::string name = gogo->type_descriptor_name(this, nt);
1260 std::string asm_name(go_selectively_encode_id(name));
1261 this->type_descriptor_var_ =
1262 gogo->backend()->immutable_struct_reference(name, asm_name,
1263 td_btype,
1264 bloc);
1266 if (phash != NULL)
1267 *phash = this->type_descriptor_var_;
1268 return;
1271 std::string var_name = gogo->type_descriptor_name(this, nt);
1273 // Build the contents of the type descriptor.
1274 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1276 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1278 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1280 const Package* dummy;
1281 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1283 std::string asm_name(go_selectively_encode_id(var_name));
1284 this->type_descriptor_var_ =
1285 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1286 initializer_btype,
1287 loc);
1288 if (phash != NULL)
1289 *phash = this->type_descriptor_var_;
1290 return;
1293 // See if this type descriptor can appear in multiple packages.
1294 bool is_common = false;
1295 if (nt != NULL)
1297 // We create the descriptor for a builtin type whenever we need
1298 // it.
1299 is_common = nt->is_builtin();
1301 else
1303 // This is an unnamed type. The descriptor could be defined in
1304 // any package where it is needed, and the linker will pick one
1305 // descriptor to keep.
1306 is_common = true;
1309 // We are going to build the type descriptor in this package. We
1310 // must create the variable before we convert the initializer to the
1311 // backend representation, because the initializer may refer to the
1312 // type descriptor of this type. By setting type_descriptor_var_ we
1313 // ensure that type_descriptor_pointer will work if called while
1314 // converting INITIALIZER.
1316 std::string asm_name(go_selectively_encode_id(var_name));
1317 this->type_descriptor_var_ =
1318 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1319 initializer_btype, loc);
1320 if (phash != NULL)
1321 *phash = this->type_descriptor_var_;
1323 Translate_context context(gogo, NULL, NULL, NULL);
1324 context.set_is_const();
1325 Bexpression* binitializer = initializer->get_backend(&context);
1327 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1328 var_name, false, is_common,
1329 initializer_btype, loc,
1330 binitializer);
1333 // Return true if this type descriptor is defined in a different
1334 // package. If this returns true it sets *PACKAGE to the package.
1336 bool
1337 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1338 const Package** package)
1340 if (nt != NULL)
1342 if (nt->named_object()->package() != NULL)
1344 // This is a named type defined in a different package. The
1345 // type descriptor should be defined in that package.
1346 *package = nt->named_object()->package();
1347 return true;
1350 else
1352 if (this->points_to() != NULL
1353 && this->points_to()->named_type() != NULL
1354 && this->points_to()->named_type()->named_object()->package() != NULL)
1356 // This is an unnamed pointer to a named type defined in a
1357 // different package. The descriptor should be defined in
1358 // that package.
1359 *package = this->points_to()->named_type()->named_object()->package();
1360 return true;
1363 return false;
1366 // Return a composite literal for a type descriptor.
1368 Expression*
1369 Type::type_descriptor(Gogo* gogo, Type* type)
1371 return type->do_type_descriptor(gogo, NULL);
1374 // Return a composite literal for a type descriptor with a name.
1376 Expression*
1377 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1379 go_assert(name != NULL && type->named_type() != name);
1380 return type->do_type_descriptor(gogo, name);
1383 // Make a builtin struct type from a list of fields. The fields are
1384 // pairs of a name and a type.
1386 Struct_type*
1387 Type::make_builtin_struct_type(int nfields, ...)
1389 va_list ap;
1390 va_start(ap, nfields);
1392 Location bloc = Linemap::predeclared_location();
1393 Struct_field_list* sfl = new Struct_field_list();
1394 for (int i = 0; i < nfields; i++)
1396 const char* field_name = va_arg(ap, const char *);
1397 Type* type = va_arg(ap, Type*);
1398 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1401 va_end(ap);
1403 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1404 ret->set_is_struct_incomparable();
1405 return ret;
1408 // A list of builtin named types.
1410 std::vector<Named_type*> Type::named_builtin_types;
1412 // Make a builtin named type.
1414 Named_type*
1415 Type::make_builtin_named_type(const char* name, Type* type)
1417 Location bloc = Linemap::predeclared_location();
1418 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1419 Named_type* ret = no->type_value();
1420 Type::named_builtin_types.push_back(ret);
1421 return ret;
1424 // Convert the named builtin types.
1426 void
1427 Type::convert_builtin_named_types(Gogo* gogo)
1429 for (std::vector<Named_type*>::const_iterator p =
1430 Type::named_builtin_types.begin();
1431 p != Type::named_builtin_types.end();
1432 ++p)
1434 bool r = (*p)->verify();
1435 go_assert(r);
1436 (*p)->convert(gogo);
1440 // Return the type of a type descriptor. We should really tie this to
1441 // runtime.Type rather than copying it. This must match the struct "_type"
1442 // declared in libgo/go/runtime/type.go.
1444 Type*
1445 Type::make_type_descriptor_type()
1447 static Type* ret;
1448 if (ret == NULL)
1450 Location bloc = Linemap::predeclared_location();
1452 Type* uint8_type = Type::lookup_integer_type("uint8");
1453 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1454 Type* uint32_type = Type::lookup_integer_type("uint32");
1455 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1456 Type* string_type = Type::lookup_string_type();
1457 Type* pointer_string_type = Type::make_pointer_type(string_type);
1459 // This is an unnamed version of unsafe.Pointer. Perhaps we
1460 // should use the named version instead, although that would
1461 // require us to create the unsafe package if it has not been
1462 // imported. It probably doesn't matter.
1463 Type* void_type = Type::make_void_type();
1464 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1466 Typed_identifier_list *params = new Typed_identifier_list();
1467 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1468 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1470 Typed_identifier_list* results = new Typed_identifier_list();
1471 results->push_back(Typed_identifier("", uintptr_type, bloc));
1473 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1474 bloc);
1476 params = new Typed_identifier_list();
1477 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1478 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1480 results = new Typed_identifier_list();
1481 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1483 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1484 bloc);
1486 // Forward declaration for the type descriptor type.
1487 Named_object* named_type_descriptor_type =
1488 Named_object::make_type_declaration("_type", NULL, bloc);
1489 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1490 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1492 // The type of a method on a concrete type.
1493 Struct_type* method_type =
1494 Type::make_builtin_struct_type(5,
1495 "name", pointer_string_type,
1496 "pkgPath", pointer_string_type,
1497 "mtyp", pointer_type_descriptor_type,
1498 "typ", pointer_type_descriptor_type,
1499 "tfn", unsafe_pointer_type);
1500 Named_type* named_method_type =
1501 Type::make_builtin_named_type("method", method_type);
1503 // Information for types with a name or methods.
1504 Type* slice_named_method_type =
1505 Type::make_array_type(named_method_type, NULL);
1506 Struct_type* uncommon_type =
1507 Type::make_builtin_struct_type(3,
1508 "name", pointer_string_type,
1509 "pkgPath", pointer_string_type,
1510 "methods", slice_named_method_type);
1511 Named_type* named_uncommon_type =
1512 Type::make_builtin_named_type("uncommonType", uncommon_type);
1514 Type* pointer_uncommon_type =
1515 Type::make_pointer_type(named_uncommon_type);
1517 // The type descriptor type.
1519 Struct_type* type_descriptor_type =
1520 Type::make_builtin_struct_type(12,
1521 "size", uintptr_type,
1522 "ptrdata", uintptr_type,
1523 "hash", uint32_type,
1524 "kind", uint8_type,
1525 "align", uint8_type,
1526 "fieldAlign", uint8_type,
1527 "hashfn", hash_fntype,
1528 "equalfn", equal_fntype,
1529 "gcdata", pointer_uint8_type,
1530 "string", pointer_string_type,
1531 "", pointer_uncommon_type,
1532 "ptrToThis",
1533 pointer_type_descriptor_type);
1535 Named_type* named = Type::make_builtin_named_type("_type",
1536 type_descriptor_type);
1538 named_type_descriptor_type->set_type_value(named);
1540 ret = named;
1543 return ret;
1546 // Make the type of a pointer to a type descriptor as represented in
1547 // Go.
1549 Type*
1550 Type::make_type_descriptor_ptr_type()
1552 static Type* ret;
1553 if (ret == NULL)
1554 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1555 return ret;
1558 // Return the alignment required by the memequalN function. N is a
1559 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1560 // in libgo/go/runtime/alg.go.
1562 int64_t
1563 Type::memequal_align(Gogo* gogo, int size)
1565 const char* tn;
1566 switch (size)
1568 case 16:
1569 tn = "int16";
1570 break;
1571 case 32:
1572 tn = "int32";
1573 break;
1574 case 64:
1575 tn = "int64";
1576 break;
1577 case 128:
1578 // The code uses [2]int64, which must have the same alignment as
1579 // int64.
1580 tn = "int64";
1581 break;
1582 default:
1583 go_unreachable();
1586 Type* t = Type::lookup_integer_type(tn);
1588 int64_t ret;
1589 if (!t->backend_type_align(gogo, &ret))
1590 go_unreachable();
1591 return ret;
1594 // Return whether this type needs specially built type functions.
1595 // This returns true for types that are comparable and either can not
1596 // use an identity comparison, or are a non-standard size.
1598 bool
1599 Type::needs_specific_type_functions(Gogo* gogo)
1601 Named_type* nt = this->named_type();
1602 if (nt != NULL && nt->is_alias())
1603 return false;
1604 if (!this->is_comparable())
1605 return false;
1606 if (!this->compare_is_identity(gogo))
1607 return true;
1609 // We create a few predeclared types for type descriptors; they are
1610 // really just for the backend and don't need hash or equality
1611 // functions.
1612 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1613 return false;
1615 int64_t size, align;
1616 if (!this->backend_type_size(gogo, &size)
1617 || !this->backend_type_align(gogo, &align))
1619 go_assert(saw_errors());
1620 return false;
1622 // This switch matches the one in Type::type_functions.
1623 switch (size)
1625 case 0:
1626 case 1:
1627 case 2:
1628 return align < Type::memequal_align(gogo, 16);
1629 case 4:
1630 return align < Type::memequal_align(gogo, 32);
1631 case 8:
1632 return align < Type::memequal_align(gogo, 64);
1633 case 16:
1634 return align < Type::memequal_align(gogo, 128);
1635 default:
1636 return true;
1640 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1641 // hash code for this type and which compare whether two values of
1642 // this type are equal. If NAME is not NULL it is the name of this
1643 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1644 // functions, for convenience; they may be NULL.
1646 void
1647 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1648 Function_type* equal_fntype, Named_object** hash_fn,
1649 Named_object** equal_fn)
1651 // If this loop leaves NAME as NULL, then the type does not have a
1652 // name after all.
1653 while (name != NULL && name->is_alias())
1654 name = name->real_type()->named_type();
1656 if (!this->is_comparable())
1658 *hash_fn = NULL;
1659 *equal_fn = NULL;
1660 return;
1663 if (hash_fntype == NULL || equal_fntype == NULL)
1665 Location bloc = Linemap::predeclared_location();
1667 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1668 Type* void_type = Type::make_void_type();
1669 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1671 if (hash_fntype == NULL)
1673 Typed_identifier_list* params = new Typed_identifier_list();
1674 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1675 bloc));
1676 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1678 Typed_identifier_list* results = new Typed_identifier_list();
1679 results->push_back(Typed_identifier("", uintptr_type, bloc));
1681 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1683 if (equal_fntype == NULL)
1685 Typed_identifier_list* params = new Typed_identifier_list();
1686 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1687 bloc));
1688 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1689 bloc));
1691 Typed_identifier_list* results = new Typed_identifier_list();
1692 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1693 bloc));
1695 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1699 const char* hash_fnname;
1700 const char* equal_fnname;
1701 if (this->compare_is_identity(gogo))
1703 int64_t size, align;
1704 if (!this->backend_type_size(gogo, &size)
1705 || !this->backend_type_align(gogo, &align))
1707 go_assert(saw_errors());
1708 return;
1710 bool build_functions = false;
1711 // This switch matches the one in Type::needs_specific_type_functions.
1712 // The alignment tests are because of the memequal functions,
1713 // which assume that the values are aligned as required for an
1714 // integer of that size.
1715 switch (size)
1717 case 0:
1718 hash_fnname = "runtime.memhash0";
1719 equal_fnname = "runtime.memequal0";
1720 break;
1721 case 1:
1722 hash_fnname = "runtime.memhash8";
1723 equal_fnname = "runtime.memequal8";
1724 break;
1725 case 2:
1726 if (align < Type::memequal_align(gogo, 16))
1727 build_functions = true;
1728 else
1730 hash_fnname = "runtime.memhash16";
1731 equal_fnname = "runtime.memequal16";
1733 break;
1734 case 4:
1735 if (align < Type::memequal_align(gogo, 32))
1736 build_functions = true;
1737 else
1739 hash_fnname = "runtime.memhash32";
1740 equal_fnname = "runtime.memequal32";
1742 break;
1743 case 8:
1744 if (align < Type::memequal_align(gogo, 64))
1745 build_functions = true;
1746 else
1748 hash_fnname = "runtime.memhash64";
1749 equal_fnname = "runtime.memequal64";
1751 break;
1752 case 16:
1753 if (align < Type::memequal_align(gogo, 128))
1754 build_functions = true;
1755 else
1757 hash_fnname = "runtime.memhash128";
1758 equal_fnname = "runtime.memequal128";
1760 break;
1761 default:
1762 build_functions = true;
1763 break;
1765 if (build_functions)
1767 // We don't have a built-in function for a type of this size
1768 // and alignment. Build a function to use that calls the
1769 // generic hash/equality functions for identity, passing the size.
1770 this->specific_type_functions(gogo, name, size, hash_fntype,
1771 equal_fntype, hash_fn, equal_fn);
1772 return;
1775 else
1777 switch (this->base()->classification())
1779 case Type::TYPE_ERROR:
1780 case Type::TYPE_VOID:
1781 case Type::TYPE_NIL:
1782 case Type::TYPE_FUNCTION:
1783 case Type::TYPE_MAP:
1784 // For these types is_comparable should have returned false.
1785 go_unreachable();
1787 case Type::TYPE_BOOLEAN:
1788 case Type::TYPE_INTEGER:
1789 case Type::TYPE_POINTER:
1790 case Type::TYPE_CHANNEL:
1791 // For these types compare_is_identity should have returned true.
1792 go_unreachable();
1794 case Type::TYPE_FLOAT:
1795 switch (this->float_type()->bits())
1797 case 32:
1798 hash_fnname = "runtime.f32hash";
1799 equal_fnname = "runtime.f32equal";
1800 break;
1801 case 64:
1802 hash_fnname = "runtime.f64hash";
1803 equal_fnname = "runtime.f64equal";
1804 break;
1805 default:
1806 go_unreachable();
1808 break;
1810 case Type::TYPE_COMPLEX:
1811 switch (this->complex_type()->bits())
1813 case 64:
1814 hash_fnname = "runtime.c64hash";
1815 equal_fnname = "runtime.c64equal";
1816 break;
1817 case 128:
1818 hash_fnname = "runtime.c128hash";
1819 equal_fnname = "runtime.c128equal";
1820 break;
1821 default:
1822 go_unreachable();
1824 break;
1826 case Type::TYPE_STRING:
1827 hash_fnname = "runtime.strhash";
1828 equal_fnname = "runtime.strequal";
1829 break;
1831 case Type::TYPE_STRUCT:
1833 // This is a struct which can not be compared using a
1834 // simple identity function. We need to build a function
1835 // for comparison.
1836 this->specific_type_functions(gogo, name, -1, hash_fntype,
1837 equal_fntype, hash_fn, equal_fn);
1838 return;
1841 case Type::TYPE_ARRAY:
1842 if (this->is_slice_type())
1844 // Type::is_compatible_for_comparison should have
1845 // returned false.
1846 go_unreachable();
1848 else
1850 // This is an array which can not be compared using a
1851 // simple identity function. We need to build a
1852 // function for comparison.
1853 this->specific_type_functions(gogo, name, -1, hash_fntype,
1854 equal_fntype, hash_fn, equal_fn);
1855 return;
1857 break;
1859 case Type::TYPE_INTERFACE:
1860 if (this->interface_type()->is_empty())
1862 hash_fnname = "runtime.nilinterhash";
1863 equal_fnname = "runtime.nilinterequal";
1865 else
1867 hash_fnname = "runtime.interhash";
1868 equal_fnname = "runtime.interequal";
1870 break;
1872 case Type::TYPE_NAMED:
1873 case Type::TYPE_FORWARD:
1874 go_unreachable();
1876 default:
1877 go_unreachable();
1882 Location bloc = Linemap::predeclared_location();
1883 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1884 hash_fntype, bloc);
1885 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1886 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1887 equal_fntype, bloc);
1888 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1891 // A hash table mapping types to the specific hash functions.
1893 Type::Type_functions Type::type_functions_table;
1895 // Handle a type function which is specific to a type: if SIZE == -1,
1896 // this is a struct or array that can not use an identity comparison.
1897 // Otherwise, it is a type that uses an identity comparison but is not
1898 // one of the standard supported sizes.
1900 void
1901 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1902 Function_type* hash_fntype,
1903 Function_type* equal_fntype,
1904 Named_object** hash_fn,
1905 Named_object** equal_fn)
1907 Hash_equal_fn fnull(NULL, NULL);
1908 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1909 std::pair<Type_functions::iterator, bool> ins =
1910 Type::type_functions_table.insert(val);
1911 if (!ins.second)
1913 // We already have functions for this type
1914 *hash_fn = ins.first->second.first;
1915 *equal_fn = ins.first->second.second;
1916 return;
1919 std::string hash_name;
1920 std::string equal_name;
1921 gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
1923 Location bloc = Linemap::predeclared_location();
1925 const Package* package = NULL;
1926 bool is_defined_elsewhere =
1927 this->type_descriptor_defined_elsewhere(name, &package);
1928 if (is_defined_elsewhere)
1930 *hash_fn = Named_object::make_function_declaration(hash_name, package,
1931 hash_fntype, bloc);
1932 *equal_fn = Named_object::make_function_declaration(equal_name, package,
1933 equal_fntype, bloc);
1935 else
1937 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
1938 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
1939 bloc);
1942 ins.first->second.first = *hash_fn;
1943 ins.first->second.second = *equal_fn;
1945 if (!is_defined_elsewhere)
1947 if (gogo->in_global_scope())
1948 this->write_specific_type_functions(gogo, name, size, hash_name,
1949 hash_fntype, equal_name,
1950 equal_fntype);
1951 else
1952 gogo->queue_specific_type_function(this, name, size, hash_name,
1953 hash_fntype, equal_name,
1954 equal_fntype);
1958 // Write the hash and equality functions for a type which needs to be
1959 // written specially.
1961 void
1962 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1963 const std::string& hash_name,
1964 Function_type* hash_fntype,
1965 const std::string& equal_name,
1966 Function_type* equal_fntype)
1968 Location bloc = Linemap::predeclared_location();
1970 if (gogo->specific_type_functions_are_written())
1972 go_assert(saw_errors());
1973 return;
1976 go_assert(this->is_comparable());
1978 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
1979 bloc);
1980 hash_fn->func_value()->set_is_type_specific_function();
1981 gogo->start_block(bloc);
1983 if (size != -1)
1984 this->write_identity_hash(gogo, size);
1985 else if (name != NULL && name->real_type()->named_type() != NULL)
1986 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
1987 else if (this->struct_type() != NULL)
1988 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
1989 equal_fntype);
1990 else if (this->array_type() != NULL)
1991 this->array_type()->write_hash_function(gogo, name, hash_fntype,
1992 equal_fntype);
1993 else
1994 go_unreachable();
1996 Block* b = gogo->finish_block(bloc);
1997 gogo->add_block(b, bloc);
1998 gogo->lower_block(hash_fn, b);
1999 gogo->finish_function(bloc);
2001 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2002 false, bloc);
2003 equal_fn->func_value()->set_is_type_specific_function();
2004 gogo->start_block(bloc);
2006 if (size != -1)
2007 this->write_identity_equal(gogo, size);
2008 else if (name != NULL && name->real_type()->named_type() != NULL)
2009 this->write_named_equal(gogo, name);
2010 else if (this->struct_type() != NULL)
2011 this->struct_type()->write_equal_function(gogo, name);
2012 else if (this->array_type() != NULL)
2013 this->array_type()->write_equal_function(gogo, name);
2014 else
2015 go_unreachable();
2017 b = gogo->finish_block(bloc);
2018 gogo->add_block(b, bloc);
2019 gogo->lower_block(equal_fn, b);
2020 gogo->finish_function(bloc);
2022 // Build the function descriptors for the type descriptor to refer to.
2023 hash_fn->func_value()->descriptor(gogo, hash_fn);
2024 equal_fn->func_value()->descriptor(gogo, equal_fn);
2027 // Write a hash function for a type that can use an identity hash but
2028 // is not one of the standard supported sizes. For example, this
2029 // would be used for the type [3]byte. This builds a return statement
2030 // that returns a call to the memhash function, passing the key and
2031 // seed from the function arguments (already constructed before this
2032 // is called), and the constant size.
2034 void
2035 Type::write_identity_hash(Gogo* gogo, int64_t size)
2037 Location bloc = Linemap::predeclared_location();
2039 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2040 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2042 Typed_identifier_list* params = new Typed_identifier_list();
2043 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2044 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2045 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2047 Typed_identifier_list* results = new Typed_identifier_list();
2048 results->push_back(Typed_identifier("", uintptr_type, bloc));
2050 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2051 results, bloc);
2053 Named_object* memhash =
2054 Named_object::make_function_declaration("runtime.memhash", NULL,
2055 memhash_fntype, bloc);
2056 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2058 Named_object* key_arg = gogo->lookup("key", NULL);
2059 go_assert(key_arg != NULL);
2060 Named_object* seed_arg = gogo->lookup("seed", NULL);
2061 go_assert(seed_arg != NULL);
2063 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2064 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2065 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2066 bloc);
2067 Expression_list* args = new Expression_list();
2068 args->push_back(key_ref);
2069 args->push_back(seed_ref);
2070 args->push_back(size_arg);
2071 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2072 Expression* call = Expression::make_call(func, args, false, bloc);
2074 Expression_list* vals = new Expression_list();
2075 vals->push_back(call);
2076 Statement* s = Statement::make_return_statement(vals, bloc);
2077 gogo->add_statement(s);
2080 // Write an equality function for a type that can use an identity
2081 // equality comparison but is not one of the standard supported sizes.
2082 // For example, this would be used for the type [3]byte. This builds
2083 // a return statement that returns a call to the memequal function,
2084 // passing the two keys from the function arguments (already
2085 // constructed before this is called), and the constant size.
2087 void
2088 Type::write_identity_equal(Gogo* gogo, int64_t size)
2090 Location bloc = Linemap::predeclared_location();
2092 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2093 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2095 Typed_identifier_list* params = new Typed_identifier_list();
2096 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2097 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2098 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2100 Typed_identifier_list* results = new Typed_identifier_list();
2101 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2103 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2104 results, bloc);
2106 Named_object* memequal =
2107 Named_object::make_function_declaration("runtime.memequal", NULL,
2108 memequal_fntype, bloc);
2109 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2111 Named_object* key1_arg = gogo->lookup("key1", NULL);
2112 go_assert(key1_arg != NULL);
2113 Named_object* key2_arg = gogo->lookup("key2", NULL);
2114 go_assert(key2_arg != NULL);
2116 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2117 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2118 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2119 bloc);
2120 Expression_list* args = new Expression_list();
2121 args->push_back(key1_ref);
2122 args->push_back(key2_ref);
2123 args->push_back(size_arg);
2124 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2125 Expression* call = Expression::make_call(func, args, false, bloc);
2127 Expression_list* vals = new Expression_list();
2128 vals->push_back(call);
2129 Statement* s = Statement::make_return_statement(vals, bloc);
2130 gogo->add_statement(s);
2133 // Write a hash function that simply calls the hash function for a
2134 // named type. This is used when one named type is defined as
2135 // another. This ensures that this case works when the other named
2136 // type is defined in another package and relies on calling hash
2137 // functions defined only in that package.
2139 void
2140 Type::write_named_hash(Gogo* gogo, Named_type* name,
2141 Function_type* hash_fntype, Function_type* equal_fntype)
2143 Location bloc = Linemap::predeclared_location();
2145 Named_type* base_type = name->real_type()->named_type();
2146 while (base_type->is_alias())
2148 base_type = base_type->real_type()->named_type();
2149 go_assert(base_type != NULL);
2151 go_assert(base_type != NULL);
2153 // The pointer to the type we are going to hash. This is an
2154 // unsafe.Pointer.
2155 Named_object* key_arg = gogo->lookup("key", NULL);
2156 go_assert(key_arg != NULL);
2158 // The seed argument to the hash function.
2159 Named_object* seed_arg = gogo->lookup("seed", NULL);
2160 go_assert(seed_arg != NULL);
2162 Named_object* hash_fn;
2163 Named_object* equal_fn;
2164 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2165 &hash_fn, &equal_fn);
2167 // Call the hash function for the base type.
2168 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2169 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2170 Expression_list* args = new Expression_list();
2171 args->push_back(key_ref);
2172 args->push_back(seed_ref);
2173 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2174 Expression* call = Expression::make_call(func, args, false, bloc);
2176 // Return the hash of the base type.
2177 Expression_list* vals = new Expression_list();
2178 vals->push_back(call);
2179 Statement* s = Statement::make_return_statement(vals, bloc);
2180 gogo->add_statement(s);
2183 // Write an equality function that simply calls the equality function
2184 // for a named type. This is used when one named type is defined as
2185 // another. This ensures that this case works when the other named
2186 // type is defined in another package and relies on calling equality
2187 // functions defined only in that package.
2189 void
2190 Type::write_named_equal(Gogo* gogo, Named_type* name)
2192 Location bloc = Linemap::predeclared_location();
2194 // The pointers to the types we are going to compare. These have
2195 // type unsafe.Pointer.
2196 Named_object* key1_arg = gogo->lookup("key1", NULL);
2197 Named_object* key2_arg = gogo->lookup("key2", NULL);
2198 go_assert(key1_arg != NULL && key2_arg != NULL);
2200 Named_type* base_type = name->real_type()->named_type();
2201 go_assert(base_type != NULL);
2203 // Build temporaries with the base type.
2204 Type* pt = Type::make_pointer_type(base_type);
2206 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2207 ref = Expression::make_cast(pt, ref, bloc);
2208 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2209 gogo->add_statement(p1);
2211 ref = Expression::make_var_reference(key2_arg, bloc);
2212 ref = Expression::make_cast(pt, ref, bloc);
2213 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2214 gogo->add_statement(p2);
2216 // Compare the values for equality.
2217 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2218 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2220 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2221 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2223 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2225 // Return the equality comparison.
2226 Expression_list* vals = new Expression_list();
2227 vals->push_back(cond);
2228 Statement* s = Statement::make_return_statement(vals, bloc);
2229 gogo->add_statement(s);
2232 // Return a composite literal for the type descriptor for a plain type
2233 // of kind RUNTIME_TYPE_KIND named NAME.
2235 Expression*
2236 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2237 Named_type* name, const Methods* methods,
2238 bool only_value_methods)
2240 Location bloc = Linemap::predeclared_location();
2242 Type* td_type = Type::make_type_descriptor_type();
2243 const Struct_field_list* fields = td_type->struct_type()->fields();
2245 Expression_list* vals = new Expression_list();
2246 vals->reserve(12);
2248 if (!this->has_pointer())
2249 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2250 if (this->points_to() != NULL)
2251 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2252 int64_t ptrsize;
2253 int64_t ptrdata;
2254 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2255 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2257 Struct_field_list::const_iterator p = fields->begin();
2258 go_assert(p->is_field_name("size"));
2259 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2260 vals->push_back(Expression::make_type_info(this, type_info));
2262 ++p;
2263 go_assert(p->is_field_name("ptrdata"));
2264 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2265 vals->push_back(Expression::make_type_info(this, type_info));
2267 ++p;
2268 go_assert(p->is_field_name("hash"));
2269 unsigned int h;
2270 if (name != NULL)
2271 h = name->hash_for_method(gogo);
2272 else
2273 h = this->hash_for_method(gogo);
2274 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2276 ++p;
2277 go_assert(p->is_field_name("kind"));
2278 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2279 bloc));
2281 ++p;
2282 go_assert(p->is_field_name("align"));
2283 type_info = Expression::TYPE_INFO_ALIGNMENT;
2284 vals->push_back(Expression::make_type_info(this, type_info));
2286 ++p;
2287 go_assert(p->is_field_name("fieldAlign"));
2288 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2289 vals->push_back(Expression::make_type_info(this, type_info));
2291 ++p;
2292 go_assert(p->is_field_name("hashfn"));
2293 Function_type* hash_fntype = p->type()->function_type();
2295 ++p;
2296 go_assert(p->is_field_name("equalfn"));
2297 Function_type* equal_fntype = p->type()->function_type();
2299 Named_object* hash_fn;
2300 Named_object* equal_fn;
2301 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2302 &equal_fn);
2303 if (hash_fn == NULL)
2304 vals->push_back(Expression::make_cast(hash_fntype,
2305 Expression::make_nil(bloc),
2306 bloc));
2307 else
2308 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2309 if (equal_fn == NULL)
2310 vals->push_back(Expression::make_cast(equal_fntype,
2311 Expression::make_nil(bloc),
2312 bloc));
2313 else
2314 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2316 ++p;
2317 go_assert(p->is_field_name("gcdata"));
2318 vals->push_back(Expression::make_gc_symbol(this));
2320 ++p;
2321 go_assert(p->is_field_name("string"));
2322 Expression* s = Expression::make_string((name != NULL
2323 ? name->reflection(gogo)
2324 : this->reflection(gogo)),
2325 bloc);
2326 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2328 ++p;
2329 go_assert(p->is_field_name("uncommonType"));
2330 if (name == NULL && methods == NULL)
2331 vals->push_back(Expression::make_nil(bloc));
2332 else
2334 if (methods == NULL)
2335 methods = name->methods();
2336 vals->push_back(this->uncommon_type_constructor(gogo,
2337 p->type()->deref(),
2338 name, methods,
2339 only_value_methods));
2342 ++p;
2343 go_assert(p->is_field_name("ptrToThis"));
2344 if (name == NULL && methods == NULL)
2345 vals->push_back(Expression::make_nil(bloc));
2346 else
2348 Type* pt;
2349 if (name != NULL)
2350 pt = Type::make_pointer_type(name);
2351 else
2352 pt = Type::make_pointer_type(this);
2353 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2356 ++p;
2357 go_assert(p == fields->end());
2359 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2362 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2363 // length used by the gc toolchain, and also appears in
2364 // libgo/go/reflect/type.go.
2366 static const int64_t max_ptrmask_bytes = 2048;
2368 // Return a pointer to the Garbage Collection information for this type.
2370 Bexpression*
2371 Type::gc_symbol_pointer(Gogo* gogo)
2373 Type* t = this->forwarded();
2374 while (t->named_type() != NULL && t->named_type()->is_alias())
2375 t = t->named_type()->real_type()->forwarded();
2377 if (!t->has_pointer())
2378 return gogo->backend()->nil_pointer_expression();
2380 if (t->gc_symbol_var_ == NULL)
2382 t->make_gc_symbol_var(gogo);
2383 go_assert(t->gc_symbol_var_ != NULL);
2385 Location bloc = Linemap::predeclared_location();
2386 Bexpression* var_expr =
2387 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2388 Bexpression* addr_expr =
2389 gogo->backend()->address_expression(var_expr, bloc);
2391 Type* uint8_type = Type::lookup_integer_type("uint8");
2392 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2393 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2394 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2397 // A mapping from unnamed types to GC symbol variables.
2399 Type::GC_symbol_vars Type::gc_symbol_vars;
2401 // Build the GC symbol for this type.
2403 void
2404 Type::make_gc_symbol_var(Gogo* gogo)
2406 go_assert(this->gc_symbol_var_ == NULL);
2408 Named_type* nt = this->named_type();
2410 // We can have multiple instances of unnamed types and similar to type
2411 // descriptors, we only want to the emit the GC data once, so we use a
2412 // hash table.
2413 Bvariable** phash = NULL;
2414 if (nt == NULL)
2416 Bvariable* bvnull = NULL;
2417 std::pair<GC_symbol_vars::iterator, bool> ins =
2418 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2419 if (!ins.second)
2421 // We've already built a gc symbol for this type.
2422 this->gc_symbol_var_ = ins.first->second;
2423 return;
2425 phash = &ins.first->second;
2428 int64_t ptrsize;
2429 int64_t ptrdata;
2430 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2432 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2433 if (phash != NULL)
2434 *phash = this->gc_symbol_var_;
2435 return;
2438 std::string sym_name = gogo->gc_symbol_name(this);
2440 // Build the contents of the gc symbol.
2441 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2442 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2444 // If the type descriptor for this type is defined somewhere else, so is the
2445 // GC symbol.
2446 const Package* dummy;
2447 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2449 std::string asm_name(go_selectively_encode_id(sym_name));
2450 this->gc_symbol_var_ =
2451 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2452 sym_btype);
2453 if (phash != NULL)
2454 *phash = this->gc_symbol_var_;
2455 return;
2458 // See if this gc symbol can appear in multiple packages.
2459 bool is_common = false;
2460 if (nt != NULL)
2462 // We create the symbol for a builtin type whenever we need
2463 // it.
2464 is_common = nt->is_builtin();
2466 else
2468 // This is an unnamed type. The descriptor could be defined in
2469 // any package where it is needed, and the linker will pick one
2470 // descriptor to keep.
2471 is_common = true;
2474 // Since we are building the GC symbol in this package, we must create the
2475 // variable before converting the initializer to its backend representation
2476 // because the initializer may refer to the GC symbol for this type.
2477 std::string asm_name(go_selectively_encode_id(sym_name));
2478 this->gc_symbol_var_ =
2479 gogo->backend()->implicit_variable(sym_name, asm_name,
2480 sym_btype, false, true, is_common, 0);
2481 if (phash != NULL)
2482 *phash = this->gc_symbol_var_;
2484 Translate_context context(gogo, NULL, NULL, NULL);
2485 context.set_is_const();
2486 Bexpression* sym_binit = sym_init->get_backend(&context);
2487 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2488 sym_btype, false, true, is_common,
2489 sym_binit);
2492 // Return whether this type needs a GC program, and set *PTRDATA to
2493 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2494 // pointer.
2496 bool
2497 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2499 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2500 if (!voidptr->backend_type_size(gogo, ptrsize))
2501 go_unreachable();
2503 if (!this->backend_type_ptrdata(gogo, ptrdata))
2505 go_assert(saw_errors());
2506 return false;
2509 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2512 // A simple class used to build a GC ptrmask for a type.
2514 class Ptrmask
2516 public:
2517 Ptrmask(size_t count)
2518 : bits_((count + 7) / 8, 0)
2521 void
2522 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2524 std::string
2525 symname() const;
2527 Expression*
2528 constructor(Gogo* gogo) const;
2530 private:
2531 void
2532 set(size_t index)
2533 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2535 // The actual bits.
2536 std::vector<unsigned char> bits_;
2539 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2540 // counts in bytes. PTRSIZE is the size of a pointer on the target
2541 // system.
2543 void
2544 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2546 switch (type->base()->classification())
2548 default:
2549 case Type::TYPE_NIL:
2550 case Type::TYPE_CALL_MULTIPLE_RESULT:
2551 case Type::TYPE_NAMED:
2552 case Type::TYPE_FORWARD:
2553 go_unreachable();
2555 case Type::TYPE_ERROR:
2556 case Type::TYPE_VOID:
2557 case Type::TYPE_BOOLEAN:
2558 case Type::TYPE_INTEGER:
2559 case Type::TYPE_FLOAT:
2560 case Type::TYPE_COMPLEX:
2561 case Type::TYPE_SINK:
2562 break;
2564 case Type::TYPE_FUNCTION:
2565 case Type::TYPE_POINTER:
2566 case Type::TYPE_MAP:
2567 case Type::TYPE_CHANNEL:
2568 // These types are all a single pointer.
2569 go_assert((offset % ptrsize) == 0);
2570 this->set(offset / ptrsize);
2571 break;
2573 case Type::TYPE_STRING:
2574 // A string starts with a single pointer.
2575 go_assert((offset % ptrsize) == 0);
2576 this->set(offset / ptrsize);
2577 break;
2579 case Type::TYPE_INTERFACE:
2580 // An interface is two pointers.
2581 go_assert((offset % ptrsize) == 0);
2582 this->set(offset / ptrsize);
2583 this->set((offset / ptrsize) + 1);
2584 break;
2586 case Type::TYPE_STRUCT:
2588 if (!type->has_pointer())
2589 return;
2591 const Struct_field_list* fields = type->struct_type()->fields();
2592 int64_t soffset = 0;
2593 for (Struct_field_list::const_iterator pf = fields->begin();
2594 pf != fields->end();
2595 ++pf)
2597 int64_t field_align;
2598 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2600 go_assert(saw_errors());
2601 return;
2603 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2605 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2607 int64_t field_size;
2608 if (!pf->type()->backend_type_size(gogo, &field_size))
2610 go_assert(saw_errors());
2611 return;
2613 soffset += field_size;
2616 break;
2618 case Type::TYPE_ARRAY:
2619 if (type->is_slice_type())
2621 // A slice starts with a single pointer.
2622 go_assert((offset % ptrsize) == 0);
2623 this->set(offset / ptrsize);
2624 break;
2626 else
2628 if (!type->has_pointer())
2629 return;
2631 int64_t len;
2632 if (!type->array_type()->int_length(&len))
2634 go_assert(saw_errors());
2635 return;
2638 Type* element_type = type->array_type()->element_type();
2639 int64_t ele_size;
2640 if (!element_type->backend_type_size(gogo, &ele_size))
2642 go_assert(saw_errors());
2643 return;
2646 int64_t eoffset = 0;
2647 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2648 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2649 break;
2654 // Return a symbol name for this ptrmask. This is used to coalesce
2655 // identical ptrmasks, which are common. The symbol name must use
2656 // only characters that are valid in symbols. It's nice if it's
2657 // short. We convert it to a base64 string.
2659 std::string
2660 Ptrmask::symname() const
2662 const char chars[65] =
2663 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";
2664 go_assert(chars[64] == '\0');
2665 std::string ret;
2666 unsigned int b = 0;
2667 int remaining = 0;
2668 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2669 p != this->bits_.end();
2670 ++p)
2672 b |= *p << remaining;
2673 remaining += 8;
2674 while (remaining >= 6)
2676 ret += chars[b & 0x3f];
2677 b >>= 6;
2678 remaining -= 6;
2681 while (remaining > 0)
2683 ret += chars[b & 0x3f];
2684 b >>= 6;
2685 remaining -= 6;
2687 return ret;
2690 // Return a constructor for this ptrmask. This will be used to
2691 // initialize the runtime ptrmask value.
2693 Expression*
2694 Ptrmask::constructor(Gogo* gogo) const
2696 Location bloc = Linemap::predeclared_location();
2697 Type* byte_type = gogo->lookup_global("byte")->type_value();
2698 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2699 bloc);
2700 Array_type* at = Type::make_array_type(byte_type, len);
2701 Expression_list* vals = new Expression_list();
2702 vals->reserve(this->bits_.size());
2703 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2704 p != this->bits_.end();
2705 ++p)
2706 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2707 return Expression::make_array_composite_literal(at, vals, bloc);
2710 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2711 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2713 // Return a ptrmask variable for a type. For a type descriptor this
2714 // is only used for variables that are small enough to not need a
2715 // gcprog, but for a global variable this is used for a variable of
2716 // any size. PTRDATA is the number of bytes of the type that contain
2717 // pointer data. PTRSIZE is the size of a pointer on the target
2718 // system.
2720 Bvariable*
2721 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2723 Ptrmask ptrmask(ptrdata / ptrsize);
2724 if (ptrdata >= ptrsize)
2725 ptrmask.set_from(gogo, this, ptrsize, 0);
2726 else
2728 // This can happen in error cases. Just build an empty gcbits.
2729 go_assert(saw_errors());
2732 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2733 Bvariable* bvnull = NULL;
2734 std::pair<GC_gcbits_vars::iterator, bool> ins =
2735 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2736 if (!ins.second)
2738 // We've already built a GC symbol for this set of gcbits.
2739 return ins.first->second;
2742 Expression* val = ptrmask.constructor(gogo);
2743 Translate_context context(gogo, NULL, NULL, NULL);
2744 context.set_is_const();
2745 Bexpression* bval = val->get_backend(&context);
2747 std::string asm_name(go_selectively_encode_id(sym_name));
2748 Btype *btype = val->type()->get_backend(gogo);
2749 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2750 btype, false, true,
2751 true, 0);
2752 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2753 true, true, bval);
2754 ins.first->second = ret;
2755 return ret;
2758 // A GCProg is used to build a program for the garbage collector.
2759 // This is used for types with a lot of pointer data, to reduce the
2760 // size of the data in the compiled program. The program is expanded
2761 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2763 class GCProg
2765 public:
2766 GCProg()
2767 : bytes_(), index_(0), nb_(0)
2770 // The number of bits described so far.
2771 int64_t
2772 bit_index() const
2773 { return this->index_; }
2775 void
2776 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2778 void
2779 end();
2781 Expression*
2782 constructor(Gogo* gogo) const;
2784 private:
2785 void
2786 ptr(int64_t);
2788 bool
2789 should_repeat(int64_t, int64_t);
2791 void
2792 repeat(int64_t, int64_t);
2794 void
2795 zero_until(int64_t);
2797 void
2798 lit(unsigned char);
2800 void
2801 varint(int64_t);
2803 void
2804 flushlit();
2806 // Add a byte to the program.
2807 void
2808 byte(unsigned char x)
2809 { this->bytes_.push_back(x); }
2811 // The maximum number of bytes of literal bits.
2812 static const int max_literal = 127;
2814 // The program.
2815 std::vector<unsigned char> bytes_;
2816 // The index of the last bit described.
2817 int64_t index_;
2818 // The current set of literal bits.
2819 unsigned char b_[max_literal];
2820 // The current number of literal bits.
2821 int nb_;
2824 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2825 // counts in bytes. PTRSIZE is the size of a pointer on the target
2826 // system.
2828 void
2829 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2831 switch (type->base()->classification())
2833 default:
2834 case Type::TYPE_NIL:
2835 case Type::TYPE_CALL_MULTIPLE_RESULT:
2836 case Type::TYPE_NAMED:
2837 case Type::TYPE_FORWARD:
2838 go_unreachable();
2840 case Type::TYPE_ERROR:
2841 case Type::TYPE_VOID:
2842 case Type::TYPE_BOOLEAN:
2843 case Type::TYPE_INTEGER:
2844 case Type::TYPE_FLOAT:
2845 case Type::TYPE_COMPLEX:
2846 case Type::TYPE_SINK:
2847 break;
2849 case Type::TYPE_FUNCTION:
2850 case Type::TYPE_POINTER:
2851 case Type::TYPE_MAP:
2852 case Type::TYPE_CHANNEL:
2853 // These types are all a single pointer.
2854 go_assert((offset % ptrsize) == 0);
2855 this->ptr(offset / ptrsize);
2856 break;
2858 case Type::TYPE_STRING:
2859 // A string starts with a single pointer.
2860 go_assert((offset % ptrsize) == 0);
2861 this->ptr(offset / ptrsize);
2862 break;
2864 case Type::TYPE_INTERFACE:
2865 // An interface is two pointers.
2866 go_assert((offset % ptrsize) == 0);
2867 this->ptr(offset / ptrsize);
2868 this->ptr((offset / ptrsize) + 1);
2869 break;
2871 case Type::TYPE_STRUCT:
2873 if (!type->has_pointer())
2874 return;
2876 const Struct_field_list* fields = type->struct_type()->fields();
2877 int64_t soffset = 0;
2878 for (Struct_field_list::const_iterator pf = fields->begin();
2879 pf != fields->end();
2880 ++pf)
2882 int64_t field_align;
2883 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2885 go_assert(saw_errors());
2886 return;
2888 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2890 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2892 int64_t field_size;
2893 if (!pf->type()->backend_type_size(gogo, &field_size))
2895 go_assert(saw_errors());
2896 return;
2898 soffset += field_size;
2901 break;
2903 case Type::TYPE_ARRAY:
2904 if (type->is_slice_type())
2906 // A slice starts with a single pointer.
2907 go_assert((offset % ptrsize) == 0);
2908 this->ptr(offset / ptrsize);
2909 break;
2911 else
2913 if (!type->has_pointer())
2914 return;
2916 int64_t len;
2917 if (!type->array_type()->int_length(&len))
2919 go_assert(saw_errors());
2920 return;
2923 Type* element_type = type->array_type()->element_type();
2925 // Flatten array of array to a big array by multiplying counts.
2926 while (element_type->array_type() != NULL
2927 && !element_type->is_slice_type())
2929 int64_t ele_len;
2930 if (!element_type->array_type()->int_length(&ele_len))
2932 go_assert(saw_errors());
2933 return;
2936 len *= ele_len;
2937 element_type = element_type->array_type()->element_type();
2940 int64_t ele_size;
2941 if (!element_type->backend_type_size(gogo, &ele_size))
2943 go_assert(saw_errors());
2944 return;
2947 go_assert(len > 0 && ele_size > 0);
2949 if (!this->should_repeat(ele_size / ptrsize, len))
2951 // Cheaper to just emit the bits.
2952 int64_t eoffset = 0;
2953 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2954 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2956 else
2958 go_assert((offset % ptrsize) == 0);
2959 go_assert((ele_size % ptrsize) == 0);
2960 this->set_from(gogo, element_type, ptrsize, offset);
2961 this->zero_until((offset + ele_size) / ptrsize);
2962 this->repeat(ele_size / ptrsize, len - 1);
2965 break;
2970 // Emit a 1 into the bit stream of a GC program at the given bit index.
2972 void
2973 GCProg::ptr(int64_t index)
2975 go_assert(index >= this->index_);
2976 this->zero_until(index);
2977 this->lit(1);
2980 // Return whether it is worthwhile to use a repeat to describe c
2981 // elements of n bits each, compared to just emitting c copies of the
2982 // n-bit description.
2984 bool
2985 GCProg::should_repeat(int64_t n, int64_t c)
2987 // Repeat if there is more than 1 item and if the total data doesn't
2988 // fit into four bytes.
2989 return c > 1 && c * n > 4 * 8;
2992 // Emit an instruction to repeat the description of the last n words c
2993 // times (including the initial description, so c + 1 times in total).
2995 void
2996 GCProg::repeat(int64_t n, int64_t c)
2998 if (n == 0 || c == 0)
2999 return;
3000 this->flushlit();
3001 if (n < 128)
3002 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3003 else
3005 this->byte(0x80);
3006 this->varint(n);
3008 this->varint(c);
3009 this->index_ += n * c;
3012 // Add zeros to the bit stream up to the given index.
3014 void
3015 GCProg::zero_until(int64_t index)
3017 go_assert(index >= this->index_);
3018 int64_t skip = index - this->index_;
3019 if (skip == 0)
3020 return;
3021 if (skip < 4 * 8)
3023 for (int64_t i = 0; i < skip; ++i)
3024 this->lit(0);
3025 return;
3027 this->lit(0);
3028 this->flushlit();
3029 this->repeat(1, skip - 1);
3032 // Add a single literal bit to the program.
3034 void
3035 GCProg::lit(unsigned char x)
3037 if (this->nb_ == GCProg::max_literal)
3038 this->flushlit();
3039 this->b_[this->nb_] = x;
3040 ++this->nb_;
3041 ++this->index_;
3044 // Emit the varint encoding of x.
3046 void
3047 GCProg::varint(int64_t x)
3049 go_assert(x >= 0);
3050 while (x >= 0x80)
3052 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3053 x >>= 7;
3055 this->byte(static_cast<unsigned char>(x & 0x7f));
3058 // Flush any pending literal bits.
3060 void
3061 GCProg::flushlit()
3063 if (this->nb_ == 0)
3064 return;
3065 this->byte(static_cast<unsigned char>(this->nb_));
3066 unsigned char bits = 0;
3067 for (int i = 0; i < this->nb_; ++i)
3069 bits |= this->b_[i] << (i % 8);
3070 if ((i + 1) % 8 == 0)
3072 this->byte(bits);
3073 bits = 0;
3076 if (this->nb_ % 8 != 0)
3077 this->byte(bits);
3078 this->nb_ = 0;
3081 // Mark the end of a GC program.
3083 void
3084 GCProg::end()
3086 this->flushlit();
3087 this->byte(0);
3090 // Return an Expression for the bytes in a GC program.
3092 Expression*
3093 GCProg::constructor(Gogo* gogo) const
3095 Location bloc = Linemap::predeclared_location();
3097 // The first four bytes are the length of the program in target byte
3098 // order. Build a struct whose first type is uint32 to make this
3099 // work.
3101 Type* uint32_type = Type::lookup_integer_type("uint32");
3103 Type* byte_type = gogo->lookup_global("byte")->type_value();
3104 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3105 bloc);
3106 Array_type* at = Type::make_array_type(byte_type, len);
3108 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3109 "bytes", at);
3111 Expression_list* vals = new Expression_list();
3112 vals->reserve(this->bytes_.size());
3113 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3114 p != this->bytes_.end();
3115 ++p)
3116 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3117 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3119 vals = new Expression_list();
3120 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3121 bloc));
3122 vals->push_back(bytes);
3124 return Expression::make_struct_composite_literal(st, vals, bloc);
3127 // Return a composite literal for the garbage collection program for
3128 // this type. This is only used for types that are too large to use a
3129 // ptrmask.
3131 Expression*
3132 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3134 Location bloc = Linemap::predeclared_location();
3136 GCProg prog;
3137 prog.set_from(gogo, this, ptrsize, 0);
3138 int64_t offset = prog.bit_index() * ptrsize;
3139 prog.end();
3141 int64_t type_size;
3142 if (!this->backend_type_size(gogo, &type_size))
3144 go_assert(saw_errors());
3145 return Expression::make_error(bloc);
3148 go_assert(offset >= ptrdata && offset <= type_size);
3150 return prog.constructor(gogo);
3153 // Return a composite literal for the uncommon type information for
3154 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3155 // struct. If name is not NULL, it is the name of the type. If
3156 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3157 // is true if only value methods should be included. At least one of
3158 // NAME and METHODS must not be NULL.
3160 Expression*
3161 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3162 Named_type* name, const Methods* methods,
3163 bool only_value_methods) const
3165 Location bloc = Linemap::predeclared_location();
3167 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3169 Expression_list* vals = new Expression_list();
3170 vals->reserve(3);
3172 Struct_field_list::const_iterator p = fields->begin();
3173 go_assert(p->is_field_name("name"));
3175 ++p;
3176 go_assert(p->is_field_name("pkgPath"));
3178 if (name == NULL)
3180 vals->push_back(Expression::make_nil(bloc));
3181 vals->push_back(Expression::make_nil(bloc));
3183 else
3185 Named_object* no = name->named_object();
3186 std::string n = Gogo::unpack_hidden_name(no->name());
3187 Expression* s = Expression::make_string(n, bloc);
3188 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3190 if (name->is_builtin())
3191 vals->push_back(Expression::make_nil(bloc));
3192 else
3194 const Package* package = no->package();
3195 const std::string& pkgpath(package == NULL
3196 ? gogo->pkgpath()
3197 : package->pkgpath());
3198 s = Expression::make_string(pkgpath, bloc);
3199 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3203 ++p;
3204 go_assert(p->is_field_name("methods"));
3205 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3206 only_value_methods));
3208 ++p;
3209 go_assert(p == fields->end());
3211 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3212 vals, bloc);
3213 return Expression::make_unary(OPERATOR_AND, r, bloc);
3216 // Sort methods by name.
3218 class Sort_methods
3220 public:
3221 bool
3222 operator()(const std::pair<std::string, const Method*>& m1,
3223 const std::pair<std::string, const Method*>& m2) const
3225 return (Gogo::unpack_hidden_name(m1.first)
3226 < Gogo::unpack_hidden_name(m2.first));
3230 // Return a composite literal for the type method table for this type.
3231 // METHODS_TYPE is the type of the table, and is a slice type.
3232 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3233 // then only value methods are used.
3235 Expression*
3236 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3237 const Methods* methods,
3238 bool only_value_methods) const
3240 Location bloc = Linemap::predeclared_location();
3242 std::vector<std::pair<std::string, const Method*> > smethods;
3243 if (methods != NULL)
3245 smethods.reserve(methods->count());
3246 for (Methods::const_iterator p = methods->begin();
3247 p != methods->end();
3248 ++p)
3250 if (p->second->is_ambiguous())
3251 continue;
3252 if (only_value_methods && !p->second->is_value_method())
3253 continue;
3255 // This is where we implement the magic //go:nointerface
3256 // comment. If we saw that comment, we don't add this
3257 // method to the type descriptor.
3258 if (p->second->nointerface())
3259 continue;
3261 smethods.push_back(std::make_pair(p->first, p->second));
3265 if (smethods.empty())
3266 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3268 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3270 Type* method_type = methods_type->array_type()->element_type();
3272 Expression_list* vals = new Expression_list();
3273 vals->reserve(smethods.size());
3274 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3275 = smethods.begin();
3276 p != smethods.end();
3277 ++p)
3278 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3279 p->second, only_value_methods));
3281 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3284 // Return a composite literal for a single method. METHOD_TYPE is the
3285 // type of the entry. METHOD_NAME is the name of the method and M is
3286 // the method information.
3288 Expression*
3289 Type::method_constructor(Gogo*, Type* method_type,
3290 const std::string& method_name,
3291 const Method* m,
3292 bool only_value_methods) const
3294 Location bloc = Linemap::predeclared_location();
3296 const Struct_field_list* fields = method_type->struct_type()->fields();
3298 Expression_list* vals = new Expression_list();
3299 vals->reserve(5);
3301 Struct_field_list::const_iterator p = fields->begin();
3302 go_assert(p->is_field_name("name"));
3303 const std::string n = Gogo::unpack_hidden_name(method_name);
3304 Expression* s = Expression::make_string(n, bloc);
3305 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3307 ++p;
3308 go_assert(p->is_field_name("pkgPath"));
3309 if (!Gogo::is_hidden_name(method_name))
3310 vals->push_back(Expression::make_nil(bloc));
3311 else
3313 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3314 bloc);
3315 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3318 Named_object* no = (m->needs_stub_method()
3319 ? m->stub_object()
3320 : m->named_object());
3322 Function_type* mtype;
3323 if (no->is_function())
3324 mtype = no->func_value()->type();
3325 else
3326 mtype = no->func_declaration_value()->type();
3327 go_assert(mtype->is_method());
3328 Type* nonmethod_type = mtype->copy_without_receiver();
3330 ++p;
3331 go_assert(p->is_field_name("mtyp"));
3332 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3334 ++p;
3335 go_assert(p->is_field_name("typ"));
3336 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3337 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3338 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3340 ++p;
3341 go_assert(p->is_field_name("tfn"));
3342 vals->push_back(Expression::make_func_code_reference(no, bloc));
3344 ++p;
3345 go_assert(p == fields->end());
3347 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3350 // Return a composite literal for the type descriptor of a plain type.
3351 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3352 // NULL, it is the name to use as well as the list of methods.
3354 Expression*
3355 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3356 Named_type* name)
3358 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3359 name, NULL, true);
3362 // Return the type reflection string for this type.
3364 std::string
3365 Type::reflection(Gogo* gogo) const
3367 std::string ret;
3369 // The do_reflection virtual function should set RET to the
3370 // reflection string.
3371 this->do_reflection(gogo, &ret);
3373 return ret;
3376 // Return whether the backend size of the type is known.
3378 bool
3379 Type::is_backend_type_size_known(Gogo* gogo)
3381 switch (this->classification_)
3383 case TYPE_ERROR:
3384 case TYPE_VOID:
3385 case TYPE_BOOLEAN:
3386 case TYPE_INTEGER:
3387 case TYPE_FLOAT:
3388 case TYPE_COMPLEX:
3389 case TYPE_STRING:
3390 case TYPE_FUNCTION:
3391 case TYPE_POINTER:
3392 case TYPE_NIL:
3393 case TYPE_MAP:
3394 case TYPE_CHANNEL:
3395 case TYPE_INTERFACE:
3396 return true;
3398 case TYPE_STRUCT:
3400 const Struct_field_list* fields = this->struct_type()->fields();
3401 for (Struct_field_list::const_iterator pf = fields->begin();
3402 pf != fields->end();
3403 ++pf)
3404 if (!pf->type()->is_backend_type_size_known(gogo))
3405 return false;
3406 return true;
3409 case TYPE_ARRAY:
3411 const Array_type* at = this->array_type();
3412 if (at->length() == NULL)
3413 return true;
3414 else
3416 Numeric_constant nc;
3417 if (!at->length()->numeric_constant_value(&nc))
3418 return false;
3419 mpz_t ival;
3420 if (!nc.to_int(&ival))
3421 return false;
3422 mpz_clear(ival);
3423 return at->element_type()->is_backend_type_size_known(gogo);
3427 case TYPE_NAMED:
3428 this->named_type()->convert(gogo);
3429 return this->named_type()->is_named_backend_type_size_known();
3431 case TYPE_FORWARD:
3433 Forward_declaration_type* fdt = this->forward_declaration_type();
3434 return fdt->real_type()->is_backend_type_size_known(gogo);
3437 case TYPE_SINK:
3438 case TYPE_CALL_MULTIPLE_RESULT:
3439 go_unreachable();
3441 default:
3442 go_unreachable();
3446 // If the size of the type can be determined, set *PSIZE to the size
3447 // in bytes and return true. Otherwise, return false. This queries
3448 // the backend.
3450 bool
3451 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3453 if (!this->is_backend_type_size_known(gogo))
3454 return false;
3455 if (this->is_error_type())
3456 return false;
3457 Btype* bt = this->get_backend_placeholder(gogo);
3458 *psize = gogo->backend()->type_size(bt);
3459 if (*psize == -1)
3461 if (this->named_type() != NULL)
3462 go_error_at(this->named_type()->location(),
3463 "type %s larger than address space",
3464 Gogo::message_name(this->named_type()->name()).c_str());
3465 else
3466 go_error_at(Linemap::unknown_location(),
3467 "type %s larger than address space",
3468 this->reflection(gogo).c_str());
3470 // Make this an error type to avoid knock-on errors.
3471 this->classification_ = TYPE_ERROR;
3472 return false;
3474 return true;
3477 // If the alignment of the type can be determined, set *PALIGN to
3478 // the alignment in bytes and return true. Otherwise, return false.
3480 bool
3481 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3483 if (!this->is_backend_type_size_known(gogo))
3484 return false;
3485 Btype* bt = this->get_backend_placeholder(gogo);
3486 *palign = gogo->backend()->type_alignment(bt);
3487 return true;
3490 // Like backend_type_align, but return the alignment when used as a
3491 // field.
3493 bool
3494 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3496 if (!this->is_backend_type_size_known(gogo))
3497 return false;
3498 Btype* bt = this->get_backend_placeholder(gogo);
3499 *palign = gogo->backend()->type_field_alignment(bt);
3500 return true;
3503 // Get the ptrdata value for a type. This is the size of the prefix
3504 // of the type that contains all pointers. Store the ptrdata in
3505 // *PPTRDATA and return whether we found it.
3507 bool
3508 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3510 *pptrdata = 0;
3512 if (!this->has_pointer())
3513 return true;
3515 if (!this->is_backend_type_size_known(gogo))
3516 return false;
3518 switch (this->classification_)
3520 case TYPE_ERROR:
3521 return true;
3523 case TYPE_FUNCTION:
3524 case TYPE_POINTER:
3525 case TYPE_MAP:
3526 case TYPE_CHANNEL:
3527 // These types are nothing but a pointer.
3528 return this->backend_type_size(gogo, pptrdata);
3530 case TYPE_INTERFACE:
3531 // An interface is a struct of two pointers.
3532 return this->backend_type_size(gogo, pptrdata);
3534 case TYPE_STRING:
3536 // A string is a struct whose first field is a pointer, and
3537 // whose second field is not.
3538 Type* uint8_type = Type::lookup_integer_type("uint8");
3539 Type* ptr = Type::make_pointer_type(uint8_type);
3540 return ptr->backend_type_size(gogo, pptrdata);
3543 case TYPE_NAMED:
3544 case TYPE_FORWARD:
3545 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3547 case TYPE_STRUCT:
3549 const Struct_field_list* fields = this->struct_type()->fields();
3550 int64_t offset = 0;
3551 const Struct_field *ptr = NULL;
3552 int64_t ptr_offset = 0;
3553 for (Struct_field_list::const_iterator pf = fields->begin();
3554 pf != fields->end();
3555 ++pf)
3557 int64_t field_align;
3558 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3559 return false;
3560 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3562 if (pf->type()->has_pointer())
3564 ptr = &*pf;
3565 ptr_offset = offset;
3568 int64_t field_size;
3569 if (!pf->type()->backend_type_size(gogo, &field_size))
3570 return false;
3571 offset += field_size;
3574 if (ptr != NULL)
3576 int64_t ptr_ptrdata;
3577 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3578 return false;
3579 *pptrdata = ptr_offset + ptr_ptrdata;
3581 return true;
3584 case TYPE_ARRAY:
3585 if (this->is_slice_type())
3587 // A slice is a struct whose first field is a pointer, and
3588 // whose remaining fields are not.
3589 Type* element_type = this->array_type()->element_type();
3590 Type* ptr = Type::make_pointer_type(element_type);
3591 return ptr->backend_type_size(gogo, pptrdata);
3593 else
3595 Numeric_constant nc;
3596 if (!this->array_type()->length()->numeric_constant_value(&nc))
3597 return false;
3598 int64_t len;
3599 if (!nc.to_memory_size(&len))
3600 return false;
3602 Type* element_type = this->array_type()->element_type();
3603 int64_t ele_size;
3604 int64_t ele_ptrdata;
3605 if (!element_type->backend_type_size(gogo, &ele_size)
3606 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3607 return false;
3608 go_assert(ele_size > 0 && ele_ptrdata > 0);
3610 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3611 return true;
3614 default:
3615 case TYPE_VOID:
3616 case TYPE_BOOLEAN:
3617 case TYPE_INTEGER:
3618 case TYPE_FLOAT:
3619 case TYPE_COMPLEX:
3620 case TYPE_SINK:
3621 case TYPE_NIL:
3622 case TYPE_CALL_MULTIPLE_RESULT:
3623 go_unreachable();
3627 // Get the ptrdata value to store in a type descriptor. This is
3628 // normally the same as backend_type_ptrdata, but for a type that is
3629 // large enough to use a gcprog we may need to store a different value
3630 // if it ends with an array. If the gcprog uses a repeat descriptor
3631 // for the array, and if the array element ends with non-pointer data,
3632 // then the gcprog will produce a value that describes the complete
3633 // array where the backend ptrdata will omit the non-pointer elements
3634 // of the final array element. This is a subtle difference but the
3635 // run time code checks it to verify that it has expanded a gcprog as
3636 // expected.
3638 bool
3639 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3641 int64_t backend_ptrdata;
3642 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3643 return false;
3645 int64_t ptrsize;
3646 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3648 *pptrdata = backend_ptrdata;
3649 return true;
3652 GCProg prog;
3653 prog.set_from(gogo, this, ptrsize, 0);
3654 int64_t offset = prog.bit_index() * ptrsize;
3656 go_assert(offset >= backend_ptrdata);
3657 *pptrdata = offset;
3658 return true;
3661 // Default function to export a type.
3663 void
3664 Type::do_export(Export*) const
3666 go_unreachable();
3669 // Import a type.
3671 Type*
3672 Type::import_type(Import* imp)
3674 if (imp->match_c_string("("))
3675 return Function_type::do_import(imp);
3676 else if (imp->match_c_string("*"))
3677 return Pointer_type::do_import(imp);
3678 else if (imp->match_c_string("struct "))
3679 return Struct_type::do_import(imp);
3680 else if (imp->match_c_string("["))
3681 return Array_type::do_import(imp);
3682 else if (imp->match_c_string("map "))
3683 return Map_type::do_import(imp);
3684 else if (imp->match_c_string("chan "))
3685 return Channel_type::do_import(imp);
3686 else if (imp->match_c_string("interface"))
3687 return Interface_type::do_import(imp);
3688 else
3690 go_error_at(imp->location(), "import error: expected type");
3691 return Type::make_error_type();
3695 // Class Error_type.
3697 // Return the backend representation of an Error type.
3699 Btype*
3700 Error_type::do_get_backend(Gogo* gogo)
3702 return gogo->backend()->error_type();
3705 // Return an expression for the type descriptor for an error type.
3708 Expression*
3709 Error_type::do_type_descriptor(Gogo*, Named_type*)
3711 return Expression::make_error(Linemap::predeclared_location());
3714 // We should not be asked for the reflection string for an error type.
3716 void
3717 Error_type::do_reflection(Gogo*, std::string*) const
3719 go_assert(saw_errors());
3722 Type*
3723 Type::make_error_type()
3725 static Error_type singleton_error_type;
3726 return &singleton_error_type;
3729 // Class Void_type.
3731 // Get the backend representation of a void type.
3733 Btype*
3734 Void_type::do_get_backend(Gogo* gogo)
3736 return gogo->backend()->void_type();
3739 Type*
3740 Type::make_void_type()
3742 static Void_type singleton_void_type;
3743 return &singleton_void_type;
3746 // Class Boolean_type.
3748 // Return the backend representation of the boolean type.
3750 Btype*
3751 Boolean_type::do_get_backend(Gogo* gogo)
3753 return gogo->backend()->bool_type();
3756 // Make the type descriptor.
3758 Expression*
3759 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3761 if (name != NULL)
3762 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3763 else
3765 Named_object* no = gogo->lookup_global("bool");
3766 go_assert(no != NULL);
3767 return Type::type_descriptor(gogo, no->type_value());
3771 Type*
3772 Type::make_boolean_type()
3774 static Boolean_type boolean_type;
3775 return &boolean_type;
3778 // The named type "bool".
3780 static Named_type* named_bool_type;
3782 // Get the named type "bool".
3784 Named_type*
3785 Type::lookup_bool_type()
3787 return named_bool_type;
3790 // Make the named type "bool".
3792 Named_type*
3793 Type::make_named_bool_type()
3795 Type* bool_type = Type::make_boolean_type();
3796 Named_object* named_object =
3797 Named_object::make_type("bool", NULL, bool_type,
3798 Linemap::predeclared_location());
3799 Named_type* named_type = named_object->type_value();
3800 named_bool_type = named_type;
3801 return named_type;
3804 // Class Integer_type.
3806 Integer_type::Named_integer_types Integer_type::named_integer_types;
3808 // Create a new integer type. Non-abstract integer types always have
3809 // names.
3811 Named_type*
3812 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3813 int bits, int runtime_type_kind)
3815 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3816 runtime_type_kind);
3817 std::string sname(name);
3818 Named_object* named_object =
3819 Named_object::make_type(sname, NULL, integer_type,
3820 Linemap::predeclared_location());
3821 Named_type* named_type = named_object->type_value();
3822 std::pair<Named_integer_types::iterator, bool> ins =
3823 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3824 go_assert(ins.second);
3825 return named_type;
3828 // Look up an existing integer type.
3830 Named_type*
3831 Integer_type::lookup_integer_type(const char* name)
3833 Named_integer_types::const_iterator p =
3834 Integer_type::named_integer_types.find(name);
3835 go_assert(p != Integer_type::named_integer_types.end());
3836 return p->second;
3839 // Create a new abstract integer type.
3841 Integer_type*
3842 Integer_type::create_abstract_integer_type()
3844 static Integer_type* abstract_type;
3845 if (abstract_type == NULL)
3847 Type* int_type = Type::lookup_integer_type("int");
3848 abstract_type = new Integer_type(true, false,
3849 int_type->integer_type()->bits(),
3850 RUNTIME_TYPE_KIND_INT);
3852 return abstract_type;
3855 // Create a new abstract character type.
3857 Integer_type*
3858 Integer_type::create_abstract_character_type()
3860 static Integer_type* abstract_type;
3861 if (abstract_type == NULL)
3863 abstract_type = new Integer_type(true, false, 32,
3864 RUNTIME_TYPE_KIND_INT32);
3865 abstract_type->set_is_rune();
3867 return abstract_type;
3870 // Integer type compatibility.
3872 bool
3873 Integer_type::is_identical(const Integer_type* t) const
3875 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3876 return false;
3877 return this->is_abstract_ == t->is_abstract_;
3880 // Hash code.
3882 unsigned int
3883 Integer_type::do_hash_for_method(Gogo*) const
3885 return ((this->bits_ << 4)
3886 + ((this->is_unsigned_ ? 1 : 0) << 8)
3887 + ((this->is_abstract_ ? 1 : 0) << 9));
3890 // Convert an Integer_type to the backend representation.
3892 Btype*
3893 Integer_type::do_get_backend(Gogo* gogo)
3895 if (this->is_abstract_)
3897 go_assert(saw_errors());
3898 return gogo->backend()->error_type();
3900 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
3903 // The type descriptor for an integer type. Integer types are always
3904 // named.
3906 Expression*
3907 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3909 go_assert(name != NULL || saw_errors());
3910 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3913 // We should not be asked for the reflection string of a basic type.
3915 void
3916 Integer_type::do_reflection(Gogo*, std::string*) const
3918 go_assert(saw_errors());
3921 // Make an integer type.
3923 Named_type*
3924 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
3925 int runtime_type_kind)
3927 return Integer_type::create_integer_type(name, is_unsigned, bits,
3928 runtime_type_kind);
3931 // Make an abstract integer type.
3933 Integer_type*
3934 Type::make_abstract_integer_type()
3936 return Integer_type::create_abstract_integer_type();
3939 // Make an abstract character type.
3941 Integer_type*
3942 Type::make_abstract_character_type()
3944 return Integer_type::create_abstract_character_type();
3947 // Look up an integer type.
3949 Named_type*
3950 Type::lookup_integer_type(const char* name)
3952 return Integer_type::lookup_integer_type(name);
3955 // Class Float_type.
3957 Float_type::Named_float_types Float_type::named_float_types;
3959 // Create a new float type. Non-abstract float types always have
3960 // names.
3962 Named_type*
3963 Float_type::create_float_type(const char* name, int bits,
3964 int runtime_type_kind)
3966 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
3967 std::string sname(name);
3968 Named_object* named_object =
3969 Named_object::make_type(sname, NULL, float_type,
3970 Linemap::predeclared_location());
3971 Named_type* named_type = named_object->type_value();
3972 std::pair<Named_float_types::iterator, bool> ins =
3973 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
3974 go_assert(ins.second);
3975 return named_type;
3978 // Look up an existing float type.
3980 Named_type*
3981 Float_type::lookup_float_type(const char* name)
3983 Named_float_types::const_iterator p =
3984 Float_type::named_float_types.find(name);
3985 go_assert(p != Float_type::named_float_types.end());
3986 return p->second;
3989 // Create a new abstract float type.
3991 Float_type*
3992 Float_type::create_abstract_float_type()
3994 static Float_type* abstract_type;
3995 if (abstract_type == NULL)
3996 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
3997 return abstract_type;
4000 // Whether this type is identical with T.
4002 bool
4003 Float_type::is_identical(const Float_type* t) const
4005 if (this->bits_ != t->bits_)
4006 return false;
4007 return this->is_abstract_ == t->is_abstract_;
4010 // Hash code.
4012 unsigned int
4013 Float_type::do_hash_for_method(Gogo*) const
4015 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4018 // Convert to the backend representation.
4020 Btype*
4021 Float_type::do_get_backend(Gogo* gogo)
4023 return gogo->backend()->float_type(this->bits_);
4026 // The type descriptor for a float type. Float types are always named.
4028 Expression*
4029 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4031 go_assert(name != NULL || saw_errors());
4032 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4035 // We should not be asked for the reflection string of a basic type.
4037 void
4038 Float_type::do_reflection(Gogo*, std::string*) const
4040 go_assert(saw_errors());
4043 // Make a floating point type.
4045 Named_type*
4046 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4048 return Float_type::create_float_type(name, bits, runtime_type_kind);
4051 // Make an abstract float type.
4053 Float_type*
4054 Type::make_abstract_float_type()
4056 return Float_type::create_abstract_float_type();
4059 // Look up a float type.
4061 Named_type*
4062 Type::lookup_float_type(const char* name)
4064 return Float_type::lookup_float_type(name);
4067 // Class Complex_type.
4069 Complex_type::Named_complex_types Complex_type::named_complex_types;
4071 // Create a new complex type. Non-abstract complex types always have
4072 // names.
4074 Named_type*
4075 Complex_type::create_complex_type(const char* name, int bits,
4076 int runtime_type_kind)
4078 Complex_type* complex_type = new Complex_type(false, bits,
4079 runtime_type_kind);
4080 std::string sname(name);
4081 Named_object* named_object =
4082 Named_object::make_type(sname, NULL, complex_type,
4083 Linemap::predeclared_location());
4084 Named_type* named_type = named_object->type_value();
4085 std::pair<Named_complex_types::iterator, bool> ins =
4086 Complex_type::named_complex_types.insert(std::make_pair(sname,
4087 named_type));
4088 go_assert(ins.second);
4089 return named_type;
4092 // Look up an existing complex type.
4094 Named_type*
4095 Complex_type::lookup_complex_type(const char* name)
4097 Named_complex_types::const_iterator p =
4098 Complex_type::named_complex_types.find(name);
4099 go_assert(p != Complex_type::named_complex_types.end());
4100 return p->second;
4103 // Create a new abstract complex type.
4105 Complex_type*
4106 Complex_type::create_abstract_complex_type()
4108 static Complex_type* abstract_type;
4109 if (abstract_type == NULL)
4110 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4111 return abstract_type;
4114 // Whether this type is identical with T.
4116 bool
4117 Complex_type::is_identical(const Complex_type *t) const
4119 if (this->bits_ != t->bits_)
4120 return false;
4121 return this->is_abstract_ == t->is_abstract_;
4124 // Hash code.
4126 unsigned int
4127 Complex_type::do_hash_for_method(Gogo*) const
4129 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4132 // Convert to the backend representation.
4134 Btype*
4135 Complex_type::do_get_backend(Gogo* gogo)
4137 return gogo->backend()->complex_type(this->bits_);
4140 // The type descriptor for a complex type. Complex types are always
4141 // named.
4143 Expression*
4144 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4146 go_assert(name != NULL || saw_errors());
4147 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4150 // We should not be asked for the reflection string of a basic type.
4152 void
4153 Complex_type::do_reflection(Gogo*, std::string*) const
4155 go_assert(saw_errors());
4158 // Make a complex type.
4160 Named_type*
4161 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4163 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4166 // Make an abstract complex type.
4168 Complex_type*
4169 Type::make_abstract_complex_type()
4171 return Complex_type::create_abstract_complex_type();
4174 // Look up a complex type.
4176 Named_type*
4177 Type::lookup_complex_type(const char* name)
4179 return Complex_type::lookup_complex_type(name);
4182 // Class String_type.
4184 // Convert String_type to the backend representation. A string is a
4185 // struct with two fields: a pointer to the characters and a length.
4187 Btype*
4188 String_type::do_get_backend(Gogo* gogo)
4190 static Btype* backend_string_type;
4191 if (backend_string_type == NULL)
4193 std::vector<Backend::Btyped_identifier> fields(2);
4195 Type* b = gogo->lookup_global("byte")->type_value();
4196 Type* pb = Type::make_pointer_type(b);
4198 // We aren't going to get back to this field to finish the
4199 // backend representation, so force it to be finished now.
4200 if (!gogo->named_types_are_converted())
4202 Btype* bt = pb->get_backend_placeholder(gogo);
4203 pb->finish_backend(gogo, bt);
4206 fields[0].name = "__data";
4207 fields[0].btype = pb->get_backend(gogo);
4208 fields[0].location = Linemap::predeclared_location();
4210 Type* int_type = Type::lookup_integer_type("int");
4211 fields[1].name = "__length";
4212 fields[1].btype = int_type->get_backend(gogo);
4213 fields[1].location = fields[0].location;
4215 backend_string_type = gogo->backend()->struct_type(fields);
4217 return backend_string_type;
4220 // The type descriptor for the string type.
4222 Expression*
4223 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4225 if (name != NULL)
4226 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4227 else
4229 Named_object* no = gogo->lookup_global("string");
4230 go_assert(no != NULL);
4231 return Type::type_descriptor(gogo, no->type_value());
4235 // We should not be asked for the reflection string of a basic type.
4237 void
4238 String_type::do_reflection(Gogo*, std::string* ret) const
4240 ret->append("string");
4243 // Make a string type.
4245 Type*
4246 Type::make_string_type()
4248 static String_type string_type;
4249 return &string_type;
4252 // The named type "string".
4254 static Named_type* named_string_type;
4256 // Get the named type "string".
4258 Named_type*
4259 Type::lookup_string_type()
4261 return named_string_type;
4264 // Make the named type string.
4266 Named_type*
4267 Type::make_named_string_type()
4269 Type* string_type = Type::make_string_type();
4270 Named_object* named_object =
4271 Named_object::make_type("string", NULL, string_type,
4272 Linemap::predeclared_location());
4273 Named_type* named_type = named_object->type_value();
4274 named_string_type = named_type;
4275 return named_type;
4278 // The sink type. This is the type of the blank identifier _. Any
4279 // type may be assigned to it.
4281 class Sink_type : public Type
4283 public:
4284 Sink_type()
4285 : Type(TYPE_SINK)
4288 protected:
4289 bool
4290 do_compare_is_identity(Gogo*)
4291 { return false; }
4293 Btype*
4294 do_get_backend(Gogo*)
4295 { go_unreachable(); }
4297 Expression*
4298 do_type_descriptor(Gogo*, Named_type*)
4299 { go_unreachable(); }
4301 void
4302 do_reflection(Gogo*, std::string*) const
4303 { go_unreachable(); }
4305 void
4306 do_mangled_name(Gogo*, std::string*) const
4307 { go_unreachable(); }
4310 // Make the sink type.
4312 Type*
4313 Type::make_sink_type()
4315 static Sink_type sink_type;
4316 return &sink_type;
4319 // Class Function_type.
4321 // Traversal.
4324 Function_type::do_traverse(Traverse* traverse)
4326 if (this->receiver_ != NULL
4327 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4328 return TRAVERSE_EXIT;
4329 if (this->parameters_ != NULL
4330 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4331 return TRAVERSE_EXIT;
4332 if (this->results_ != NULL
4333 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4334 return TRAVERSE_EXIT;
4335 return TRAVERSE_CONTINUE;
4338 // Returns whether T is a valid redeclaration of this type. If this
4339 // returns false, and REASON is not NULL, *REASON may be set to a
4340 // brief explanation of why it returned false.
4342 bool
4343 Function_type::is_valid_redeclaration(const Function_type* t,
4344 std::string* reason) const
4346 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4347 return false;
4349 // A redeclaration of a function is required to use the same names
4350 // for the receiver and parameters.
4351 if (this->receiver() != NULL
4352 && this->receiver()->name() != t->receiver()->name())
4354 if (reason != NULL)
4355 *reason = "receiver name changed";
4356 return false;
4359 const Typed_identifier_list* parms1 = this->parameters();
4360 const Typed_identifier_list* parms2 = t->parameters();
4361 if (parms1 != NULL)
4363 Typed_identifier_list::const_iterator p1 = parms1->begin();
4364 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4365 p2 != parms2->end();
4366 ++p2, ++p1)
4368 if (p1->name() != p2->name())
4370 if (reason != NULL)
4371 *reason = "parameter name changed";
4372 return false;
4375 // This is called at parse time, so we may have unknown
4376 // types.
4377 Type* t1 = p1->type()->forwarded();
4378 Type* t2 = p2->type()->forwarded();
4379 if (t1 != t2
4380 && t1->forward_declaration_type() != NULL
4381 && (t2->forward_declaration_type() == NULL
4382 || (t1->forward_declaration_type()->named_object()
4383 != t2->forward_declaration_type()->named_object())))
4384 return false;
4388 const Typed_identifier_list* results1 = this->results();
4389 const Typed_identifier_list* results2 = t->results();
4390 if (results1 != NULL)
4392 Typed_identifier_list::const_iterator res1 = results1->begin();
4393 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4394 res2 != results2->end();
4395 ++res2, ++res1)
4397 if (res1->name() != res2->name())
4399 if (reason != NULL)
4400 *reason = "result name changed";
4401 return false;
4404 // This is called at parse time, so we may have unknown
4405 // types.
4406 Type* t1 = res1->type()->forwarded();
4407 Type* t2 = res2->type()->forwarded();
4408 if (t1 != t2
4409 && t1->forward_declaration_type() != NULL
4410 && (t2->forward_declaration_type() == NULL
4411 || (t1->forward_declaration_type()->named_object()
4412 != t2->forward_declaration_type()->named_object())))
4413 return false;
4417 return true;
4420 // Check whether T is the same as this type.
4422 bool
4423 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4424 Cmp_tags cmp_tags, bool errors_are_identical,
4425 std::string* reason) const
4427 if (!ignore_receiver)
4429 const Typed_identifier* r1 = this->receiver();
4430 const Typed_identifier* r2 = t->receiver();
4431 if ((r1 != NULL) != (r2 != NULL))
4433 if (reason != NULL)
4434 *reason = _("different receiver types");
4435 return false;
4437 if (r1 != NULL)
4439 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4440 errors_are_identical, reason))
4442 if (reason != NULL && !reason->empty())
4443 *reason = "receiver: " + *reason;
4444 return false;
4449 const Typed_identifier_list* parms1 = this->parameters();
4450 const Typed_identifier_list* parms2 = t->parameters();
4451 if ((parms1 != NULL) != (parms2 != NULL))
4453 if (reason != NULL)
4454 *reason = _("different number of parameters");
4455 return false;
4457 if (parms1 != NULL)
4459 Typed_identifier_list::const_iterator p1 = parms1->begin();
4460 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4461 p2 != parms2->end();
4462 ++p2, ++p1)
4464 if (p1 == parms1->end())
4466 if (reason != NULL)
4467 *reason = _("different number of parameters");
4468 return false;
4471 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4472 errors_are_identical, NULL))
4474 if (reason != NULL)
4475 *reason = _("different parameter types");
4476 return false;
4479 if (p1 != parms1->end())
4481 if (reason != NULL)
4482 *reason = _("different number of parameters");
4483 return false;
4487 if (this->is_varargs() != t->is_varargs())
4489 if (reason != NULL)
4490 *reason = _("different varargs");
4491 return false;
4494 const Typed_identifier_list* results1 = this->results();
4495 const Typed_identifier_list* results2 = t->results();
4496 if ((results1 != NULL) != (results2 != NULL))
4498 if (reason != NULL)
4499 *reason = _("different number of results");
4500 return false;
4502 if (results1 != NULL)
4504 Typed_identifier_list::const_iterator res1 = results1->begin();
4505 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4506 res2 != results2->end();
4507 ++res2, ++res1)
4509 if (res1 == results1->end())
4511 if (reason != NULL)
4512 *reason = _("different number of results");
4513 return false;
4516 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4517 cmp_tags, errors_are_identical,
4518 NULL))
4520 if (reason != NULL)
4521 *reason = _("different result types");
4522 return false;
4525 if (res1 != results1->end())
4527 if (reason != NULL)
4528 *reason = _("different number of results");
4529 return false;
4533 return true;
4536 // Hash code.
4538 unsigned int
4539 Function_type::do_hash_for_method(Gogo* gogo) const
4541 unsigned int ret = 0;
4542 // We ignore the receiver type for hash codes, because we need to
4543 // get the same hash code for a method in an interface and a method
4544 // declared for a type. The former will not have a receiver.
4545 if (this->parameters_ != NULL)
4547 int shift = 1;
4548 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4549 p != this->parameters_->end();
4550 ++p, ++shift)
4551 ret += p->type()->hash_for_method(gogo) << shift;
4553 if (this->results_ != NULL)
4555 int shift = 2;
4556 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4557 p != this->results_->end();
4558 ++p, ++shift)
4559 ret += p->type()->hash_for_method(gogo) << shift;
4561 if (this->is_varargs_)
4562 ret += 1;
4563 ret <<= 4;
4564 return ret;
4567 // Hash result parameters.
4569 unsigned int
4570 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4572 unsigned int hash = 0;
4573 for (Typed_identifier_list::const_iterator p = t->begin();
4574 p != t->end();
4575 ++p)
4577 hash <<= 2;
4578 hash = Type::hash_string(p->name(), hash);
4579 hash += p->type()->hash_for_method(NULL);
4581 return hash;
4584 // Compare result parameters so that can map identical result
4585 // parameters to a single struct type.
4587 bool
4588 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4589 const Typed_identifier_list* b) const
4591 if (a->size() != b->size())
4592 return false;
4593 Typed_identifier_list::const_iterator pa = a->begin();
4594 for (Typed_identifier_list::const_iterator pb = b->begin();
4595 pb != b->end();
4596 ++pa, ++pb)
4598 if (pa->name() != pb->name()
4599 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4600 return false;
4602 return true;
4605 // Hash from results to a backend struct type.
4607 Function_type::Results_structs Function_type::results_structs;
4609 // Get the backend representation for a function type.
4611 Btype*
4612 Function_type::get_backend_fntype(Gogo* gogo)
4614 if (this->fnbtype_ == NULL)
4616 Backend::Btyped_identifier breceiver;
4617 if (this->receiver_ != NULL)
4619 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4621 // We always pass the address of the receiver parameter, in
4622 // order to make interface calls work with unknown types.
4623 Type* rtype = this->receiver_->type();
4624 if (rtype->points_to() == NULL)
4625 rtype = Type::make_pointer_type(rtype);
4626 breceiver.btype = rtype->get_backend(gogo);
4627 breceiver.location = this->receiver_->location();
4630 std::vector<Backend::Btyped_identifier> bparameters;
4631 if (this->parameters_ != NULL)
4633 bparameters.resize(this->parameters_->size());
4634 size_t i = 0;
4635 for (Typed_identifier_list::const_iterator p =
4636 this->parameters_->begin(); p != this->parameters_->end();
4637 ++p, ++i)
4639 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4640 bparameters[i].btype = p->type()->get_backend(gogo);
4641 bparameters[i].location = p->location();
4643 go_assert(i == bparameters.size());
4646 std::vector<Backend::Btyped_identifier> bresults;
4647 Btype* bresult_struct = NULL;
4648 if (this->results_ != NULL)
4650 bresults.resize(this->results_->size());
4651 size_t i = 0;
4652 for (Typed_identifier_list::const_iterator p =
4653 this->results_->begin();
4654 p != this->results_->end();
4655 ++p, ++i)
4657 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4658 bresults[i].btype = p->type()->get_backend(gogo);
4659 bresults[i].location = p->location();
4661 go_assert(i == bresults.size());
4663 if (this->results_->size() > 1)
4665 // Use the same results struct for all functions that
4666 // return the same set of results. This is useful to
4667 // unify calls to interface methods with other calls.
4668 std::pair<Typed_identifier_list*, Btype*> val;
4669 val.first = this->results_;
4670 val.second = NULL;
4671 std::pair<Results_structs::iterator, bool> ins =
4672 Function_type::results_structs.insert(val);
4673 if (ins.second)
4675 // Build a new struct type.
4676 Struct_field_list* sfl = new Struct_field_list;
4677 for (Typed_identifier_list::const_iterator p =
4678 this->results_->begin();
4679 p != this->results_->end();
4680 ++p)
4682 Typed_identifier tid = *p;
4683 if (tid.name().empty())
4684 tid = Typed_identifier("UNNAMED", tid.type(),
4685 tid.location());
4686 sfl->push_back(Struct_field(tid));
4688 Struct_type* st = Type::make_struct_type(sfl,
4689 this->location());
4690 st->set_is_struct_incomparable();
4691 ins.first->second = st->get_backend(gogo);
4693 bresult_struct = ins.first->second;
4697 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4698 bresults, bresult_struct,
4699 this->location());
4703 return this->fnbtype_;
4706 // Get the backend representation for a Go function type.
4708 Btype*
4709 Function_type::do_get_backend(Gogo* gogo)
4711 // When we do anything with a function value other than call it, it
4712 // is represented as a pointer to a struct whose first field is the
4713 // actual function. So that is what we return as the type of a Go
4714 // function.
4716 Location loc = this->location();
4717 Btype* struct_type =
4718 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4719 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4721 std::vector<Backend::Btyped_identifier> fields(1);
4722 fields[0].name = "code";
4723 fields[0].btype = this->get_backend_fntype(gogo);
4724 fields[0].location = loc;
4725 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4726 return gogo->backend()->error_type();
4727 return ptr_struct_type;
4730 // The type of a function type descriptor.
4732 Type*
4733 Function_type::make_function_type_descriptor_type()
4735 static Type* ret;
4736 if (ret == NULL)
4738 Type* tdt = Type::make_type_descriptor_type();
4739 Type* ptdt = Type::make_type_descriptor_ptr_type();
4741 Type* bool_type = Type::lookup_bool_type();
4743 Type* slice_type = Type::make_array_type(ptdt, NULL);
4745 Struct_type* s = Type::make_builtin_struct_type(4,
4746 "", tdt,
4747 "dotdotdot", bool_type,
4748 "in", slice_type,
4749 "out", slice_type);
4751 ret = Type::make_builtin_named_type("FuncType", s);
4754 return ret;
4757 // The type descriptor for a function type.
4759 Expression*
4760 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4762 Location bloc = Linemap::predeclared_location();
4764 Type* ftdt = Function_type::make_function_type_descriptor_type();
4766 const Struct_field_list* fields = ftdt->struct_type()->fields();
4768 Expression_list* vals = new Expression_list();
4769 vals->reserve(4);
4771 Struct_field_list::const_iterator p = fields->begin();
4772 go_assert(p->is_field_name("_type"));
4773 vals->push_back(this->type_descriptor_constructor(gogo,
4774 RUNTIME_TYPE_KIND_FUNC,
4775 name, NULL, true));
4777 ++p;
4778 go_assert(p->is_field_name("dotdotdot"));
4779 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4781 ++p;
4782 go_assert(p->is_field_name("in"));
4783 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4784 this->parameters()));
4786 ++p;
4787 go_assert(p->is_field_name("out"));
4788 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4789 this->results()));
4791 ++p;
4792 go_assert(p == fields->end());
4794 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4797 // Return a composite literal for the parameters or results of a type
4798 // descriptor.
4800 Expression*
4801 Function_type::type_descriptor_params(Type* params_type,
4802 const Typed_identifier* receiver,
4803 const Typed_identifier_list* params)
4805 Location bloc = Linemap::predeclared_location();
4807 if (receiver == NULL && params == NULL)
4808 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4810 Expression_list* vals = new Expression_list();
4811 vals->reserve((params == NULL ? 0 : params->size())
4812 + (receiver != NULL ? 1 : 0));
4814 if (receiver != NULL)
4815 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4817 if (params != NULL)
4819 for (Typed_identifier_list::const_iterator p = params->begin();
4820 p != params->end();
4821 ++p)
4822 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4825 return Expression::make_slice_composite_literal(params_type, vals, bloc);
4828 // The reflection string.
4830 void
4831 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4833 // FIXME: Turn this off until we straighten out the type of the
4834 // struct field used in a go statement which calls a method.
4835 // go_assert(this->receiver_ == NULL);
4837 ret->append("func");
4839 if (this->receiver_ != NULL)
4841 ret->push_back('(');
4842 this->append_reflection(this->receiver_->type(), gogo, ret);
4843 ret->push_back(')');
4846 ret->push_back('(');
4847 const Typed_identifier_list* params = this->parameters();
4848 if (params != NULL)
4850 bool is_varargs = this->is_varargs_;
4851 for (Typed_identifier_list::const_iterator p = params->begin();
4852 p != params->end();
4853 ++p)
4855 if (p != params->begin())
4856 ret->append(", ");
4857 if (!is_varargs || p + 1 != params->end())
4858 this->append_reflection(p->type(), gogo, ret);
4859 else
4861 ret->append("...");
4862 this->append_reflection(p->type()->array_type()->element_type(),
4863 gogo, ret);
4867 ret->push_back(')');
4869 const Typed_identifier_list* results = this->results();
4870 if (results != NULL && !results->empty())
4872 if (results->size() == 1)
4873 ret->push_back(' ');
4874 else
4875 ret->append(" (");
4876 for (Typed_identifier_list::const_iterator p = results->begin();
4877 p != results->end();
4878 ++p)
4880 if (p != results->begin())
4881 ret->append(", ");
4882 this->append_reflection(p->type(), gogo, ret);
4884 if (results->size() > 1)
4885 ret->push_back(')');
4889 // Export a function type.
4891 void
4892 Function_type::do_export(Export* exp) const
4894 // We don't write out the receiver. The only function types which
4895 // should have a receiver are the ones associated with explicitly
4896 // defined methods. For those the receiver type is written out by
4897 // Function::export_func.
4899 exp->write_c_string("(");
4900 bool first = true;
4901 if (this->parameters_ != NULL)
4903 bool is_varargs = this->is_varargs_;
4904 for (Typed_identifier_list::const_iterator p =
4905 this->parameters_->begin();
4906 p != this->parameters_->end();
4907 ++p)
4909 if (first)
4910 first = false;
4911 else
4912 exp->write_c_string(", ");
4913 exp->write_name(p->name());
4914 exp->write_c_string(" ");
4915 if (!is_varargs || p + 1 != this->parameters_->end())
4916 exp->write_type(p->type());
4917 else
4919 exp->write_c_string("...");
4920 exp->write_type(p->type()->array_type()->element_type());
4924 exp->write_c_string(")");
4926 const Typed_identifier_list* results = this->results_;
4927 if (results != NULL)
4929 exp->write_c_string(" ");
4930 if (results->size() == 1 && results->begin()->name().empty())
4931 exp->write_type(results->begin()->type());
4932 else
4934 first = true;
4935 exp->write_c_string("(");
4936 for (Typed_identifier_list::const_iterator p = results->begin();
4937 p != results->end();
4938 ++p)
4940 if (first)
4941 first = false;
4942 else
4943 exp->write_c_string(", ");
4944 exp->write_name(p->name());
4945 exp->write_c_string(" ");
4946 exp->write_type(p->type());
4948 exp->write_c_string(")");
4953 // Import a function type.
4955 Function_type*
4956 Function_type::do_import(Import* imp)
4958 imp->require_c_string("(");
4959 Typed_identifier_list* parameters;
4960 bool is_varargs = false;
4961 if (imp->peek_char() == ')')
4962 parameters = NULL;
4963 else
4965 parameters = new Typed_identifier_list();
4966 while (true)
4968 std::string name = imp->read_name();
4969 imp->require_c_string(" ");
4971 if (imp->match_c_string("..."))
4973 imp->advance(3);
4974 is_varargs = true;
4977 Type* ptype = imp->read_type();
4978 if (is_varargs)
4979 ptype = Type::make_array_type(ptype, NULL);
4980 parameters->push_back(Typed_identifier(name, ptype,
4981 imp->location()));
4982 if (imp->peek_char() != ',')
4983 break;
4984 go_assert(!is_varargs);
4985 imp->require_c_string(", ");
4988 imp->require_c_string(")");
4990 Typed_identifier_list* results;
4991 if (imp->peek_char() != ' ')
4992 results = NULL;
4993 else
4995 imp->advance(1);
4996 results = new Typed_identifier_list;
4997 if (imp->peek_char() != '(')
4999 Type* rtype = imp->read_type();
5000 results->push_back(Typed_identifier("", rtype, imp->location()));
5002 else
5004 imp->advance(1);
5005 while (true)
5007 std::string name = imp->read_name();
5008 imp->require_c_string(" ");
5009 Type* rtype = imp->read_type();
5010 results->push_back(Typed_identifier(name, rtype,
5011 imp->location()));
5012 if (imp->peek_char() != ',')
5013 break;
5014 imp->require_c_string(", ");
5016 imp->require_c_string(")");
5020 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5021 imp->location());
5022 if (is_varargs)
5023 ret->set_is_varargs();
5024 return ret;
5027 // Make a copy of a function type without a receiver.
5029 Function_type*
5030 Function_type::copy_without_receiver() const
5032 go_assert(this->is_method());
5033 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5034 this->results_,
5035 this->location_);
5036 if (this->is_varargs())
5037 ret->set_is_varargs();
5038 if (this->is_builtin())
5039 ret->set_is_builtin();
5040 return ret;
5043 // Make a copy of a function type with a receiver.
5045 Function_type*
5046 Function_type::copy_with_receiver(Type* receiver_type) const
5048 go_assert(!this->is_method());
5049 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5050 this->location_);
5051 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5052 this->results_,
5053 this->location_);
5054 if (this->is_varargs_)
5055 ret->set_is_varargs();
5056 return ret;
5059 // Make a copy of a function type with the receiver as the first
5060 // parameter.
5062 Function_type*
5063 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5065 go_assert(this->is_method());
5066 Typed_identifier_list* new_params = new Typed_identifier_list();
5067 Type* rtype = this->receiver_->type();
5068 if (want_pointer_receiver)
5069 rtype = Type::make_pointer_type(rtype);
5070 Typed_identifier receiver(this->receiver_->name(), rtype,
5071 this->receiver_->location());
5072 new_params->push_back(receiver);
5073 const Typed_identifier_list* orig_params = this->parameters_;
5074 if (orig_params != NULL && !orig_params->empty())
5076 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5077 p != orig_params->end();
5078 ++p)
5079 new_params->push_back(*p);
5081 return Type::make_function_type(NULL, new_params, this->results_,
5082 this->location_);
5085 // Make a copy of a function type ignoring any receiver and adding a
5086 // closure parameter.
5088 Function_type*
5089 Function_type::copy_with_names() const
5091 Typed_identifier_list* new_params = new Typed_identifier_list();
5092 const Typed_identifier_list* orig_params = this->parameters_;
5093 if (orig_params != NULL && !orig_params->empty())
5095 static int count;
5096 char buf[50];
5097 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5098 p != orig_params->end();
5099 ++p)
5101 snprintf(buf, sizeof buf, "pt.%u", count);
5102 ++count;
5103 new_params->push_back(Typed_identifier(buf, p->type(),
5104 p->location()));
5108 const Typed_identifier_list* orig_results = this->results_;
5109 Typed_identifier_list* new_results;
5110 if (orig_results == NULL || orig_results->empty())
5111 new_results = NULL;
5112 else
5114 new_results = new Typed_identifier_list();
5115 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5116 p != orig_results->end();
5117 ++p)
5118 new_results->push_back(Typed_identifier("", p->type(),
5119 p->location()));
5122 return Type::make_function_type(NULL, new_params, new_results,
5123 this->location());
5126 // Make a function type.
5128 Function_type*
5129 Type::make_function_type(Typed_identifier* receiver,
5130 Typed_identifier_list* parameters,
5131 Typed_identifier_list* results,
5132 Location location)
5134 return new Function_type(receiver, parameters, results, location);
5137 // Make a backend function type.
5139 Backend_function_type*
5140 Type::make_backend_function_type(Typed_identifier* receiver,
5141 Typed_identifier_list* parameters,
5142 Typed_identifier_list* results,
5143 Location location)
5145 return new Backend_function_type(receiver, parameters, results, location);
5148 // Class Pointer_type.
5150 // Traversal.
5153 Pointer_type::do_traverse(Traverse* traverse)
5155 return Type::traverse(this->to_type_, traverse);
5158 // Hash code.
5160 unsigned int
5161 Pointer_type::do_hash_for_method(Gogo* gogo) const
5163 return this->to_type_->hash_for_method(gogo) << 4;
5166 // Get the backend representation for a pointer type.
5168 Btype*
5169 Pointer_type::do_get_backend(Gogo* gogo)
5171 Btype* to_btype = this->to_type_->get_backend(gogo);
5172 return gogo->backend()->pointer_type(to_btype);
5175 // The type of a pointer type descriptor.
5177 Type*
5178 Pointer_type::make_pointer_type_descriptor_type()
5180 static Type* ret;
5181 if (ret == NULL)
5183 Type* tdt = Type::make_type_descriptor_type();
5184 Type* ptdt = Type::make_type_descriptor_ptr_type();
5186 Struct_type* s = Type::make_builtin_struct_type(2,
5187 "", tdt,
5188 "elem", ptdt);
5190 ret = Type::make_builtin_named_type("PtrType", s);
5193 return ret;
5196 // The type descriptor for a pointer type.
5198 Expression*
5199 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5201 if (this->is_unsafe_pointer_type())
5203 go_assert(name != NULL);
5204 return this->plain_type_descriptor(gogo,
5205 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5206 name);
5208 else
5210 Location bloc = Linemap::predeclared_location();
5212 const Methods* methods;
5213 Type* deref = this->points_to();
5214 if (deref->named_type() != NULL)
5215 methods = deref->named_type()->methods();
5216 else if (deref->struct_type() != NULL)
5217 methods = deref->struct_type()->methods();
5218 else
5219 methods = NULL;
5221 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5223 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5225 Expression_list* vals = new Expression_list();
5226 vals->reserve(2);
5228 Struct_field_list::const_iterator p = fields->begin();
5229 go_assert(p->is_field_name("_type"));
5230 vals->push_back(this->type_descriptor_constructor(gogo,
5231 RUNTIME_TYPE_KIND_PTR,
5232 name, methods, false));
5234 ++p;
5235 go_assert(p->is_field_name("elem"));
5236 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5238 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5242 // Reflection string.
5244 void
5245 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5247 ret->push_back('*');
5248 this->append_reflection(this->to_type_, gogo, ret);
5251 // Export.
5253 void
5254 Pointer_type::do_export(Export* exp) const
5256 exp->write_c_string("*");
5257 if (this->is_unsafe_pointer_type())
5258 exp->write_c_string("any");
5259 else
5260 exp->write_type(this->to_type_);
5263 // Import.
5265 Pointer_type*
5266 Pointer_type::do_import(Import* imp)
5268 imp->require_c_string("*");
5269 if (imp->match_c_string("any"))
5271 imp->advance(3);
5272 return Type::make_pointer_type(Type::make_void_type());
5274 Type* to = imp->read_type();
5275 return Type::make_pointer_type(to);
5278 // Cache of pointer types. Key is "to" type, value is pointer type
5279 // that points to key.
5281 Type::Pointer_type_table Type::pointer_types;
5283 // A list of placeholder pointer types. We keep this so we can ensure
5284 // they are finalized.
5286 std::vector<Pointer_type*> Type::placeholder_pointers;
5288 // Make a pointer type.
5290 Pointer_type*
5291 Type::make_pointer_type(Type* to_type)
5293 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5294 if (p != pointer_types.end())
5295 return p->second;
5296 Pointer_type* ret = new Pointer_type(to_type);
5297 pointer_types[to_type] = ret;
5298 return ret;
5301 // This helper is invoked immediately after named types have been
5302 // converted, to clean up any unresolved pointer types remaining in
5303 // the pointer type cache.
5305 // The motivation for this routine: occasionally the compiler creates
5306 // some specific pointer type as part of a lowering operation (ex:
5307 // pointer-to-void), then Type::backend_type_size() is invoked on the
5308 // type (which creates a Btype placeholder for it), that placeholder
5309 // passed somewhere along the line to the back end, but since there is
5310 // no reference to the type in user code, there is never a call to
5311 // Type::finish_backend for the type (hence the Btype remains as an
5312 // unresolved placeholder). Calling this routine will clean up such
5313 // instances.
5315 void
5316 Type::finish_pointer_types(Gogo* gogo)
5318 // We don't use begin() and end() because it is possible to add new
5319 // placeholder pointer types as we finalized existing ones.
5320 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5322 Pointer_type* pt = Type::placeholder_pointers[i];
5323 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5324 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5326 pt->finish_backend(gogo, tbti->second.btype);
5327 tbti->second.is_placeholder = false;
5332 // Class Nil_type.
5334 // Get the backend representation of a nil type. FIXME: Is this ever
5335 // actually called?
5337 Btype*
5338 Nil_type::do_get_backend(Gogo* gogo)
5340 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5343 // Make the nil type.
5345 Type*
5346 Type::make_nil_type()
5348 static Nil_type singleton_nil_type;
5349 return &singleton_nil_type;
5352 // The type of a function call which returns multiple values. This is
5353 // really a struct, but we don't want to confuse a function call which
5354 // returns a struct with a function call which returns multiple
5355 // values.
5357 class Call_multiple_result_type : public Type
5359 public:
5360 Call_multiple_result_type(Call_expression* call)
5361 : Type(TYPE_CALL_MULTIPLE_RESULT),
5362 call_(call)
5365 protected:
5366 bool
5367 do_has_pointer() const
5368 { return false; }
5370 bool
5371 do_compare_is_identity(Gogo*)
5372 { return false; }
5374 Btype*
5375 do_get_backend(Gogo* gogo)
5377 go_assert(saw_errors());
5378 return gogo->backend()->error_type();
5381 Expression*
5382 do_type_descriptor(Gogo*, Named_type*)
5384 go_assert(saw_errors());
5385 return Expression::make_error(Linemap::unknown_location());
5388 void
5389 do_reflection(Gogo*, std::string*) const
5390 { go_assert(saw_errors()); }
5392 void
5393 do_mangled_name(Gogo*, std::string*) const
5394 { go_assert(saw_errors()); }
5396 private:
5397 // The expression being called.
5398 Call_expression* call_;
5401 // Make a call result type.
5403 Type*
5404 Type::make_call_multiple_result_type(Call_expression* call)
5406 return new Call_multiple_result_type(call);
5409 // Class Struct_field.
5411 // Get the name of a field.
5413 const std::string&
5414 Struct_field::field_name() const
5416 const std::string& name(this->typed_identifier_.name());
5417 if (!name.empty())
5418 return name;
5419 else
5421 // This is called during parsing, before anything is lowered, so
5422 // we have to be pretty careful to avoid dereferencing an
5423 // unknown type name.
5424 Type* t = this->typed_identifier_.type();
5425 Type* dt = t;
5426 if (t->classification() == Type::TYPE_POINTER)
5428 // Very ugly.
5429 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5430 dt = ptype->points_to();
5432 if (dt->forward_declaration_type() != NULL)
5433 return dt->forward_declaration_type()->name();
5434 else if (dt->named_type() != NULL)
5436 // Note that this can be an alias name.
5437 return dt->named_type()->name();
5439 else if (t->is_error_type() || dt->is_error_type())
5441 static const std::string error_string = "*error*";
5442 return error_string;
5444 else
5446 // Avoid crashing in the erroneous case where T is named but
5447 // DT is not.
5448 go_assert(t != dt);
5449 if (t->forward_declaration_type() != NULL)
5450 return t->forward_declaration_type()->name();
5451 else if (t->named_type() != NULL)
5452 return t->named_type()->name();
5453 else
5454 go_unreachable();
5459 // Return whether this field is named NAME.
5461 bool
5462 Struct_field::is_field_name(const std::string& name) const
5464 const std::string& me(this->typed_identifier_.name());
5465 if (!me.empty())
5466 return me == name;
5467 else
5469 Type* t = this->typed_identifier_.type();
5470 if (t->points_to() != NULL)
5471 t = t->points_to();
5472 Named_type* nt = t->named_type();
5473 if (nt != NULL && nt->name() == name)
5474 return true;
5476 // This is a horrible hack caused by the fact that we don't pack
5477 // the names of builtin types. FIXME.
5478 if (!this->is_imported_
5479 && nt != NULL
5480 && nt->is_builtin()
5481 && nt->name() == Gogo::unpack_hidden_name(name))
5482 return true;
5484 return false;
5488 // Return whether this field is an unexported field named NAME.
5490 bool
5491 Struct_field::is_unexported_field_name(Gogo* gogo,
5492 const std::string& name) const
5494 const std::string& field_name(this->field_name());
5495 if (Gogo::is_hidden_name(field_name)
5496 && name == Gogo::unpack_hidden_name(field_name)
5497 && gogo->pack_hidden_name(name, false) != field_name)
5498 return true;
5500 // Check for the name of a builtin type. This is like the test in
5501 // is_field_name, only there we return false if this->is_imported_,
5502 // and here we return true.
5503 if (this->is_imported_ && this->is_anonymous())
5505 Type* t = this->typed_identifier_.type();
5506 if (t->points_to() != NULL)
5507 t = t->points_to();
5508 Named_type* nt = t->named_type();
5509 if (nt != NULL
5510 && nt->is_builtin()
5511 && nt->name() == Gogo::unpack_hidden_name(name))
5512 return true;
5515 return false;
5518 // Return whether this field is an embedded built-in type.
5520 bool
5521 Struct_field::is_embedded_builtin(Gogo* gogo) const
5523 const std::string& name(this->field_name());
5524 // We know that a field is an embedded type if it is anonymous.
5525 // We can decide if it is a built-in type by checking to see if it is
5526 // registered globally under the field's name.
5527 // This allows us to distinguish between embedded built-in types and
5528 // embedded types that are aliases to built-in types.
5529 return (this->is_anonymous()
5530 && !Gogo::is_hidden_name(name)
5531 && gogo->lookup_global(name.c_str()) != NULL);
5534 // Class Struct_type.
5536 // A hash table used to find identical unnamed structs so that they
5537 // share method tables.
5539 Struct_type::Identical_structs Struct_type::identical_structs;
5541 // A hash table used to merge method sets for identical unnamed
5542 // structs.
5544 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5546 // Traversal.
5549 Struct_type::do_traverse(Traverse* traverse)
5551 Struct_field_list* fields = this->fields_;
5552 if (fields != NULL)
5554 for (Struct_field_list::iterator p = fields->begin();
5555 p != fields->end();
5556 ++p)
5558 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5559 return TRAVERSE_EXIT;
5562 return TRAVERSE_CONTINUE;
5565 // Verify that the struct type is complete and valid.
5567 bool
5568 Struct_type::do_verify()
5570 Struct_field_list* fields = this->fields_;
5571 if (fields == NULL)
5572 return true;
5573 for (Struct_field_list::iterator p = fields->begin();
5574 p != fields->end();
5575 ++p)
5577 Type* t = p->type();
5578 if (p->is_anonymous())
5580 if ((t->named_type() != NULL && t->points_to() != NULL)
5581 || (t->named_type() == NULL && t->points_to() != NULL
5582 && t->points_to()->points_to() != NULL))
5584 go_error_at(p->location(), "embedded type may not be a pointer");
5585 p->set_type(Type::make_error_type());
5587 else if (t->points_to() != NULL
5588 && t->points_to()->interface_type() != NULL)
5590 go_error_at(p->location(),
5591 "embedded type may not be pointer to interface");
5592 p->set_type(Type::make_error_type());
5596 return true;
5599 // Whether this contains a pointer.
5601 bool
5602 Struct_type::do_has_pointer() const
5604 const Struct_field_list* fields = this->fields();
5605 if (fields == NULL)
5606 return false;
5607 for (Struct_field_list::const_iterator p = fields->begin();
5608 p != fields->end();
5609 ++p)
5611 if (p->type()->has_pointer())
5612 return true;
5614 return false;
5617 // Whether this type is identical to T.
5619 bool
5620 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5621 bool errors_are_identical) const
5623 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5624 return false;
5625 const Struct_field_list* fields1 = this->fields();
5626 const Struct_field_list* fields2 = t->fields();
5627 if (fields1 == NULL || fields2 == NULL)
5628 return fields1 == fields2;
5629 Struct_field_list::const_iterator pf2 = fields2->begin();
5630 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5631 pf1 != fields1->end();
5632 ++pf1, ++pf2)
5634 if (pf2 == fields2->end())
5635 return false;
5636 if (pf1->field_name() != pf2->field_name())
5637 return false;
5638 if (pf1->is_anonymous() != pf2->is_anonymous()
5639 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5640 errors_are_identical, NULL))
5641 return false;
5642 if (cmp_tags == COMPARE_TAGS)
5644 if (!pf1->has_tag())
5646 if (pf2->has_tag())
5647 return false;
5649 else
5651 if (!pf2->has_tag())
5652 return false;
5653 if (pf1->tag() != pf2->tag())
5654 return false;
5658 if (pf2 != fields2->end())
5659 return false;
5660 return true;
5663 // Whether comparisons of this struct type are simple identity
5664 // comparisons.
5666 bool
5667 Struct_type::do_compare_is_identity(Gogo* gogo)
5669 const Struct_field_list* fields = this->fields_;
5670 if (fields == NULL)
5671 return true;
5672 int64_t offset = 0;
5673 for (Struct_field_list::const_iterator pf = fields->begin();
5674 pf != fields->end();
5675 ++pf)
5677 if (Gogo::is_sink_name(pf->field_name()))
5678 return false;
5680 if (!pf->type()->compare_is_identity(gogo))
5681 return false;
5683 int64_t field_align;
5684 if (!pf->type()->backend_type_align(gogo, &field_align))
5685 return false;
5686 if ((offset & (field_align - 1)) != 0)
5688 // This struct has padding. We don't guarantee that that
5689 // padding is zero-initialized for a stack variable, so we
5690 // can't use memcmp to compare struct values.
5691 return false;
5694 int64_t field_size;
5695 if (!pf->type()->backend_type_size(gogo, &field_size))
5696 return false;
5697 offset += field_size;
5700 int64_t struct_size;
5701 if (!this->backend_type_size(gogo, &struct_size))
5702 return false;
5703 if (offset != struct_size)
5705 // Trailing padding may not be zero when on the stack.
5706 return false;
5709 return true;
5712 // Return whether this struct type is reflexive--whether a value of
5713 // this type is always equal to itself.
5715 bool
5716 Struct_type::do_is_reflexive()
5718 const Struct_field_list* fields = this->fields_;
5719 if (fields == NULL)
5720 return true;
5721 for (Struct_field_list::const_iterator pf = fields->begin();
5722 pf != fields->end();
5723 ++pf)
5725 if (!pf->type()->is_reflexive())
5726 return false;
5728 return true;
5731 // Return whether this struct type needs a key update when used as a
5732 // map key.
5734 bool
5735 Struct_type::do_needs_key_update()
5737 const Struct_field_list* fields = this->fields_;
5738 if (fields == NULL)
5739 return false;
5740 for (Struct_field_list::const_iterator pf = fields->begin();
5741 pf != fields->end();
5742 ++pf)
5744 if (pf->type()->needs_key_update())
5745 return true;
5747 return false;
5750 // Return whether this struct type is permitted to be in the heap.
5752 bool
5753 Struct_type::do_in_heap()
5755 const Struct_field_list* fields = this->fields_;
5756 if (fields == NULL)
5757 return true;
5758 for (Struct_field_list::const_iterator pf = fields->begin();
5759 pf != fields->end();
5760 ++pf)
5762 if (!pf->type()->in_heap())
5763 return false;
5765 return true;
5768 // Build identity and hash functions for this struct.
5770 // Hash code.
5772 unsigned int
5773 Struct_type::do_hash_for_method(Gogo* gogo) const
5775 unsigned int ret = 0;
5776 if (this->fields() != NULL)
5778 for (Struct_field_list::const_iterator pf = this->fields()->begin();
5779 pf != this->fields()->end();
5780 ++pf)
5781 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5783 ret <<= 2;
5784 if (this->is_struct_incomparable_)
5785 ret <<= 1;
5786 return ret;
5789 // Find the local field NAME.
5791 const Struct_field*
5792 Struct_type::find_local_field(const std::string& name,
5793 unsigned int *pindex) const
5795 const Struct_field_list* fields = this->fields_;
5796 if (fields == NULL)
5797 return NULL;
5798 unsigned int i = 0;
5799 for (Struct_field_list::const_iterator pf = fields->begin();
5800 pf != fields->end();
5801 ++pf, ++i)
5803 if (pf->is_field_name(name))
5805 if (pindex != NULL)
5806 *pindex = i;
5807 return &*pf;
5810 return NULL;
5813 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5815 Field_reference_expression*
5816 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5817 Location location) const
5819 unsigned int depth;
5820 return this->field_reference_depth(struct_expr, name, location, NULL,
5821 &depth);
5824 // Return an expression for a field, along with the depth at which it
5825 // was found.
5827 Field_reference_expression*
5828 Struct_type::field_reference_depth(Expression* struct_expr,
5829 const std::string& name,
5830 Location location,
5831 Saw_named_type* saw,
5832 unsigned int* depth) const
5834 const Struct_field_list* fields = this->fields_;
5835 if (fields == NULL)
5836 return NULL;
5838 // Look for a field with this name.
5839 unsigned int i = 0;
5840 for (Struct_field_list::const_iterator pf = fields->begin();
5841 pf != fields->end();
5842 ++pf, ++i)
5844 if (pf->is_field_name(name))
5846 *depth = 0;
5847 return Expression::make_field_reference(struct_expr, i, location);
5851 // Look for an anonymous field which contains a field with this
5852 // name.
5853 unsigned int found_depth = 0;
5854 Field_reference_expression* ret = NULL;
5855 i = 0;
5856 for (Struct_field_list::const_iterator pf = fields->begin();
5857 pf != fields->end();
5858 ++pf, ++i)
5860 if (!pf->is_anonymous())
5861 continue;
5863 Struct_type* st = pf->type()->deref()->struct_type();
5864 if (st == NULL)
5865 continue;
5867 Saw_named_type* hold_saw = saw;
5868 Saw_named_type saw_here;
5869 Named_type* nt = pf->type()->named_type();
5870 if (nt == NULL)
5871 nt = pf->type()->deref()->named_type();
5872 if (nt != NULL)
5874 Saw_named_type* q;
5875 for (q = saw; q != NULL; q = q->next)
5877 if (q->nt == nt)
5879 // If this is an error, it will be reported
5880 // elsewhere.
5881 break;
5884 if (q != NULL)
5885 continue;
5886 saw_here.next = saw;
5887 saw_here.nt = nt;
5888 saw = &saw_here;
5891 // Look for a reference using a NULL struct expression. If we
5892 // find one, fill in the struct expression with a reference to
5893 // this field.
5894 unsigned int subdepth;
5895 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5896 location,
5897 saw,
5898 &subdepth);
5900 saw = hold_saw;
5902 if (sub == NULL)
5903 continue;
5905 if (ret == NULL || subdepth < found_depth)
5907 if (ret != NULL)
5908 delete ret;
5909 ret = sub;
5910 found_depth = subdepth;
5911 Expression* here = Expression::make_field_reference(struct_expr, i,
5912 location);
5913 if (pf->type()->points_to() != NULL)
5914 here = Expression::make_dereference(here,
5915 Expression::NIL_CHECK_DEFAULT,
5916 location);
5917 while (sub->expr() != NULL)
5919 sub = sub->expr()->deref()->field_reference_expression();
5920 go_assert(sub != NULL);
5922 sub->set_struct_expression(here);
5923 sub->set_implicit(true);
5925 else if (subdepth > found_depth)
5926 delete sub;
5927 else
5929 // We do not handle ambiguity here--it should be handled by
5930 // Type::bind_field_or_method.
5931 delete sub;
5932 found_depth = 0;
5933 ret = NULL;
5937 if (ret != NULL)
5938 *depth = found_depth + 1;
5940 return ret;
5943 // Return the total number of fields, including embedded fields.
5945 unsigned int
5946 Struct_type::total_field_count() const
5948 if (this->fields_ == NULL)
5949 return 0;
5950 unsigned int ret = 0;
5951 for (Struct_field_list::const_iterator pf = this->fields_->begin();
5952 pf != this->fields_->end();
5953 ++pf)
5955 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
5956 ++ret;
5957 else
5958 ret += pf->type()->struct_type()->total_field_count();
5960 return ret;
5963 // Return whether NAME is an unexported field, for better error reporting.
5965 bool
5966 Struct_type::is_unexported_local_field(Gogo* gogo,
5967 const std::string& name) const
5969 const Struct_field_list* fields = this->fields_;
5970 if (fields != NULL)
5972 for (Struct_field_list::const_iterator pf = fields->begin();
5973 pf != fields->end();
5974 ++pf)
5975 if (pf->is_unexported_field_name(gogo, name))
5976 return true;
5978 return false;
5981 // Finalize the methods of an unnamed struct.
5983 void
5984 Struct_type::finalize_methods(Gogo* gogo)
5986 if (this->all_methods_ != NULL)
5987 return;
5989 // It is possible to have multiple identical structs that have
5990 // methods. We want them to share method tables. Otherwise we will
5991 // emit identical methods more than once, which is bad since they
5992 // will even have the same names.
5993 std::pair<Identical_structs::iterator, bool> ins =
5994 Struct_type::identical_structs.insert(std::make_pair(this, this));
5995 if (!ins.second)
5997 // An identical struct was already entered into the hash table.
5998 // Note that finalize_methods is, fortunately, not recursive.
5999 this->all_methods_ = ins.first->second->all_methods_;
6000 return;
6003 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6006 // Return the method NAME, or NULL if there isn't one or if it is
6007 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6008 // ambiguous.
6010 Method*
6011 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6013 return Type::method_function(this->all_methods_, name, is_ambiguous);
6016 // Return a pointer to the interface method table for this type for
6017 // the interface INTERFACE. IS_POINTER is true if this is for a
6018 // pointer to THIS.
6020 Expression*
6021 Struct_type::interface_method_table(Interface_type* interface,
6022 bool is_pointer)
6024 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6025 val(this, NULL);
6026 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6027 Struct_type::struct_method_tables.insert(val);
6029 Struct_method_table_pair* smtp;
6030 if (!ins.second)
6031 smtp = ins.first->second;
6032 else
6034 smtp = new Struct_method_table_pair();
6035 smtp->first = NULL;
6036 smtp->second = NULL;
6037 ins.first->second = smtp;
6040 return Type::interface_method_table(this, interface, is_pointer,
6041 &smtp->first, &smtp->second);
6044 // Convert struct fields to the backend representation. This is not
6045 // declared in types.h so that types.h doesn't have to #include
6046 // backend.h.
6048 static void
6049 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6050 bool use_placeholder,
6051 std::vector<Backend::Btyped_identifier>* bfields)
6053 bfields->resize(fields->size());
6054 size_t i = 0;
6055 for (Struct_field_list::const_iterator p = fields->begin();
6056 p != fields->end();
6057 ++p, ++i)
6059 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6060 (*bfields)[i].btype = (use_placeholder
6061 ? p->type()->get_backend_placeholder(gogo)
6062 : p->type()->get_backend(gogo));
6063 (*bfields)[i].location = p->location();
6065 go_assert(i == fields->size());
6068 // Get the backend representation for a struct type.
6070 Btype*
6071 Struct_type::do_get_backend(Gogo* gogo)
6073 std::vector<Backend::Btyped_identifier> bfields;
6074 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6075 return gogo->backend()->struct_type(bfields);
6078 // Finish the backend representation of the fields of a struct.
6080 void
6081 Struct_type::finish_backend_fields(Gogo* gogo)
6083 const Struct_field_list* fields = this->fields_;
6084 if (fields != NULL)
6086 for (Struct_field_list::const_iterator p = fields->begin();
6087 p != fields->end();
6088 ++p)
6089 p->type()->get_backend(gogo);
6093 // The type of a struct type descriptor.
6095 Type*
6096 Struct_type::make_struct_type_descriptor_type()
6098 static Type* ret;
6099 if (ret == NULL)
6101 Type* tdt = Type::make_type_descriptor_type();
6102 Type* ptdt = Type::make_type_descriptor_ptr_type();
6104 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6105 Type* string_type = Type::lookup_string_type();
6106 Type* pointer_string_type = Type::make_pointer_type(string_type);
6108 Struct_type* sf =
6109 Type::make_builtin_struct_type(5,
6110 "name", pointer_string_type,
6111 "pkgPath", pointer_string_type,
6112 "typ", ptdt,
6113 "tag", pointer_string_type,
6114 "offsetAnon", uintptr_type);
6115 Type* nsf = Type::make_builtin_named_type("structField", sf);
6117 Type* slice_type = Type::make_array_type(nsf, NULL);
6119 Struct_type* s = Type::make_builtin_struct_type(2,
6120 "", tdt,
6121 "fields", slice_type);
6123 ret = Type::make_builtin_named_type("StructType", s);
6126 return ret;
6129 // Build a type descriptor for a struct type.
6131 Expression*
6132 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6134 Location bloc = Linemap::predeclared_location();
6136 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6138 const Struct_field_list* fields = stdt->struct_type()->fields();
6140 Expression_list* vals = new Expression_list();
6141 vals->reserve(2);
6143 const Methods* methods = this->methods();
6144 // A named struct should not have methods--the methods should attach
6145 // to the named type.
6146 go_assert(methods == NULL || name == NULL);
6148 Struct_field_list::const_iterator ps = fields->begin();
6149 go_assert(ps->is_field_name("_type"));
6150 vals->push_back(this->type_descriptor_constructor(gogo,
6151 RUNTIME_TYPE_KIND_STRUCT,
6152 name, methods, true));
6154 ++ps;
6155 go_assert(ps->is_field_name("fields"));
6157 Expression_list* elements = new Expression_list();
6158 elements->reserve(this->fields_->size());
6159 Type* element_type = ps->type()->array_type()->element_type();
6160 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6161 pf != this->fields_->end();
6162 ++pf)
6164 const Struct_field_list* f = element_type->struct_type()->fields();
6166 Expression_list* fvals = new Expression_list();
6167 fvals->reserve(5);
6169 Struct_field_list::const_iterator q = f->begin();
6170 go_assert(q->is_field_name("name"));
6171 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6172 Expression* s = Expression::make_string(n, bloc);
6173 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6175 ++q;
6176 go_assert(q->is_field_name("pkgPath"));
6177 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6178 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6179 fvals->push_back(Expression::make_nil(bloc));
6180 else
6182 std::string n;
6183 if (is_embedded_builtin)
6184 n = gogo->package_name();
6185 else
6186 n = Gogo::hidden_name_pkgpath(pf->field_name());
6187 Expression* s = Expression::make_string(n, bloc);
6188 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6191 ++q;
6192 go_assert(q->is_field_name("typ"));
6193 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6195 ++q;
6196 go_assert(q->is_field_name("tag"));
6197 if (!pf->has_tag())
6198 fvals->push_back(Expression::make_nil(bloc));
6199 else
6201 Expression* s = Expression::make_string(pf->tag(), bloc);
6202 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6205 ++q;
6206 go_assert(q->is_field_name("offsetAnon"));
6207 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6208 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6209 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6210 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6211 int av = pf->is_anonymous() ? 1 : 0;
6212 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6213 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6214 fvals->push_back(o);
6216 Expression* v = Expression::make_struct_composite_literal(element_type,
6217 fvals, bloc);
6218 elements->push_back(v);
6221 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6222 elements, bloc));
6224 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6227 // Write the hash function for a struct which can not use the identity
6228 // function.
6230 void
6231 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6232 Function_type* hash_fntype,
6233 Function_type* equal_fntype)
6235 Location bloc = Linemap::predeclared_location();
6237 // The pointer to the struct that we are going to hash. This is an
6238 // argument to the hash function we are implementing here.
6239 Named_object* key_arg = gogo->lookup("key", NULL);
6240 go_assert(key_arg != NULL);
6241 Type* key_arg_type = key_arg->var_value()->type();
6243 // The seed argument to the hash function.
6244 Named_object* seed_arg = gogo->lookup("seed", NULL);
6245 go_assert(seed_arg != NULL);
6247 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6249 // Make a temporary to hold the return value, initialized to the seed.
6250 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6251 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6252 bloc);
6253 gogo->add_statement(retval);
6255 // Make a temporary to hold the key as a uintptr.
6256 ref = Expression::make_var_reference(key_arg, bloc);
6257 ref = Expression::make_cast(uintptr_type, ref, bloc);
6258 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6259 bloc);
6260 gogo->add_statement(key);
6262 // Loop over the struct fields.
6263 const Struct_field_list* fields = this->fields_;
6264 for (Struct_field_list::const_iterator pf = fields->begin();
6265 pf != fields->end();
6266 ++pf)
6268 if (Gogo::is_sink_name(pf->field_name()))
6269 continue;
6271 // Get a pointer to the value of this field.
6272 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6273 ref = Expression::make_temporary_reference(key, bloc);
6274 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6275 bloc);
6276 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6278 // Get the hash function to use for the type of this field.
6279 Named_object* hash_fn;
6280 Named_object* equal_fn;
6281 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6282 equal_fntype, &hash_fn, &equal_fn);
6284 // Call the hash function for the field, passing retval as the seed.
6285 ref = Expression::make_temporary_reference(retval, bloc);
6286 Expression_list* args = new Expression_list();
6287 args->push_back(subkey);
6288 args->push_back(ref);
6289 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6290 Expression* call = Expression::make_call(func, args, false, bloc);
6292 // Set retval to the result.
6293 Temporary_reference_expression* tref =
6294 Expression::make_temporary_reference(retval, bloc);
6295 tref->set_is_lvalue();
6296 Statement* s = Statement::make_assignment(tref, call, bloc);
6297 gogo->add_statement(s);
6300 // Return retval to the caller of the hash function.
6301 Expression_list* vals = new Expression_list();
6302 ref = Expression::make_temporary_reference(retval, bloc);
6303 vals->push_back(ref);
6304 Statement* s = Statement::make_return_statement(vals, bloc);
6305 gogo->add_statement(s);
6308 // Write the equality function for a struct which can not use the
6309 // identity function.
6311 void
6312 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6314 Location bloc = Linemap::predeclared_location();
6316 // The pointers to the structs we are going to compare.
6317 Named_object* key1_arg = gogo->lookup("key1", NULL);
6318 Named_object* key2_arg = gogo->lookup("key2", NULL);
6319 go_assert(key1_arg != NULL && key2_arg != NULL);
6321 // Build temporaries with the right types.
6322 Type* pt = Type::make_pointer_type(name != NULL
6323 ? static_cast<Type*>(name)
6324 : static_cast<Type*>(this));
6326 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6327 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6328 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6329 gogo->add_statement(p1);
6331 ref = Expression::make_var_reference(key2_arg, bloc);
6332 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6333 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6334 gogo->add_statement(p2);
6336 const Struct_field_list* fields = this->fields_;
6337 unsigned int field_index = 0;
6338 for (Struct_field_list::const_iterator pf = fields->begin();
6339 pf != fields->end();
6340 ++pf, ++field_index)
6342 if (Gogo::is_sink_name(pf->field_name()))
6343 continue;
6345 // Compare one field in both P1 and P2.
6346 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6347 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6348 bloc);
6349 f1 = Expression::make_field_reference(f1, field_index, bloc);
6351 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6352 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6353 bloc);
6354 f2 = Expression::make_field_reference(f2, field_index, bloc);
6356 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6358 // If the values are not equal, return false.
6359 gogo->start_block(bloc);
6360 Expression_list* vals = new Expression_list();
6361 vals->push_back(Expression::make_boolean(false, bloc));
6362 Statement* s = Statement::make_return_statement(vals, bloc);
6363 gogo->add_statement(s);
6364 Block* then_block = gogo->finish_block(bloc);
6366 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6367 gogo->add_statement(s);
6370 // All the fields are equal, so return true.
6371 Expression_list* vals = new Expression_list();
6372 vals->push_back(Expression::make_boolean(true, bloc));
6373 Statement* s = Statement::make_return_statement(vals, bloc);
6374 gogo->add_statement(s);
6377 // Reflection string.
6379 void
6380 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6382 ret->append("struct {");
6384 for (Struct_field_list::const_iterator p = this->fields_->begin();
6385 p != this->fields_->end();
6386 ++p)
6388 if (p != this->fields_->begin())
6389 ret->push_back(';');
6390 ret->push_back(' ');
6391 if (p->is_anonymous())
6392 ret->push_back('?');
6393 else
6394 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6395 ret->push_back(' ');
6396 if (p->is_anonymous()
6397 && p->type()->named_type() != NULL
6398 && p->type()->named_type()->is_alias())
6399 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6400 else
6401 this->append_reflection(p->type(), gogo, ret);
6403 if (p->has_tag())
6405 const std::string& tag(p->tag());
6406 ret->append(" \"");
6407 for (std::string::const_iterator p = tag.begin();
6408 p != tag.end();
6409 ++p)
6411 if (*p == '\0')
6412 ret->append("\\x00");
6413 else if (*p == '\n')
6414 ret->append("\\n");
6415 else if (*p == '\t')
6416 ret->append("\\t");
6417 else if (*p == '"')
6418 ret->append("\\\"");
6419 else if (*p == '\\')
6420 ret->append("\\\\");
6421 else
6422 ret->push_back(*p);
6424 ret->push_back('"');
6428 if (!this->fields_->empty())
6429 ret->push_back(' ');
6431 ret->push_back('}');
6434 // If the offset of field INDEX in the backend implementation can be
6435 // determined, set *POFFSET to the offset in bytes and return true.
6436 // Otherwise, return false.
6438 bool
6439 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6440 int64_t* poffset)
6442 if (!this->is_backend_type_size_known(gogo))
6443 return false;
6444 Btype* bt = this->get_backend_placeholder(gogo);
6445 *poffset = gogo->backend()->type_field_offset(bt, index);
6446 return true;
6449 // Export.
6451 void
6452 Struct_type::do_export(Export* exp) const
6454 exp->write_c_string("struct { ");
6455 const Struct_field_list* fields = this->fields_;
6456 go_assert(fields != NULL);
6457 for (Struct_field_list::const_iterator p = fields->begin();
6458 p != fields->end();
6459 ++p)
6461 if (p->is_anonymous())
6462 exp->write_string("? ");
6463 else
6465 exp->write_string(p->field_name());
6466 exp->write_c_string(" ");
6468 exp->write_type(p->type());
6470 if (p->has_tag())
6472 exp->write_c_string(" ");
6473 Expression* expr =
6474 Expression::make_string(p->tag(), Linemap::predeclared_location());
6475 expr->export_expression(exp);
6476 delete expr;
6479 exp->write_c_string("; ");
6481 exp->write_c_string("}");
6484 // Import.
6486 Struct_type*
6487 Struct_type::do_import(Import* imp)
6489 imp->require_c_string("struct { ");
6490 Struct_field_list* fields = new Struct_field_list;
6491 if (imp->peek_char() != '}')
6493 while (true)
6495 std::string name;
6496 if (imp->match_c_string("? "))
6497 imp->advance(2);
6498 else
6500 name = imp->read_identifier();
6501 imp->require_c_string(" ");
6503 Type* ftype = imp->read_type();
6505 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6506 sf.set_is_imported();
6508 if (imp->peek_char() == ' ')
6510 imp->advance(1);
6511 Expression* expr = Expression::import_expression(imp);
6512 String_expression* sexpr = expr->string_expression();
6513 go_assert(sexpr != NULL);
6514 sf.set_tag(sexpr->val());
6515 delete sexpr;
6518 imp->require_c_string("; ");
6519 fields->push_back(sf);
6520 if (imp->peek_char() == '}')
6521 break;
6524 imp->require_c_string("}");
6526 return Type::make_struct_type(fields, imp->location());
6529 // Whether we can write this struct type to a C header file.
6530 // We can't if any of the fields are structs defined in a different package.
6532 bool
6533 Struct_type::can_write_to_c_header(
6534 std::vector<const Named_object*>* requires,
6535 std::vector<const Named_object*>* declare) const
6537 const Struct_field_list* fields = this->fields_;
6538 if (fields == NULL || fields->empty())
6539 return false;
6540 int sinks = 0;
6541 for (Struct_field_list::const_iterator p = fields->begin();
6542 p != fields->end();
6543 ++p)
6545 if (p->is_anonymous())
6546 return false;
6547 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6548 return false;
6549 if (Gogo::message_name(p->field_name()) == "_")
6550 sinks++;
6552 if (sinks > 1)
6553 return false;
6554 return true;
6557 // Whether we can write the type T to a C header file.
6559 bool
6560 Struct_type::can_write_type_to_c_header(
6561 const Type* t,
6562 std::vector<const Named_object*>* requires,
6563 std::vector<const Named_object*>* declare) const
6565 t = t->forwarded();
6566 switch (t->classification())
6568 case TYPE_ERROR:
6569 case TYPE_FORWARD:
6570 return false;
6572 case TYPE_VOID:
6573 case TYPE_BOOLEAN:
6574 case TYPE_INTEGER:
6575 case TYPE_FLOAT:
6576 case TYPE_COMPLEX:
6577 case TYPE_STRING:
6578 case TYPE_FUNCTION:
6579 case TYPE_MAP:
6580 case TYPE_CHANNEL:
6581 case TYPE_INTERFACE:
6582 return true;
6584 case TYPE_POINTER:
6585 // Don't try to handle a pointer to an array.
6586 if (t->points_to()->array_type() != NULL
6587 && !t->points_to()->is_slice_type())
6588 return false;
6590 if (t->points_to()->named_type() != NULL
6591 && t->points_to()->struct_type() != NULL)
6592 declare->push_back(t->points_to()->named_type()->named_object());
6593 return true;
6595 case TYPE_STRUCT:
6596 return t->struct_type()->can_write_to_c_header(requires, declare);
6598 case TYPE_ARRAY:
6599 if (t->is_slice_type())
6600 return true;
6601 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6602 requires, declare);
6604 case TYPE_NAMED:
6606 const Named_object* no = t->named_type()->named_object();
6607 if (no->package() != NULL)
6609 if (t->is_unsafe_pointer_type())
6610 return true;
6611 return false;
6613 if (t->struct_type() != NULL)
6615 requires->push_back(no);
6616 return t->struct_type()->can_write_to_c_header(requires, declare);
6618 return this->can_write_type_to_c_header(t->base(), requires, declare);
6621 case TYPE_CALL_MULTIPLE_RESULT:
6622 case TYPE_NIL:
6623 case TYPE_SINK:
6624 default:
6625 go_unreachable();
6629 // Write this struct to a C header file.
6631 void
6632 Struct_type::write_to_c_header(std::ostream& os) const
6634 const Struct_field_list* fields = this->fields_;
6635 for (Struct_field_list::const_iterator p = fields->begin();
6636 p != fields->end();
6637 ++p)
6639 os << '\t';
6640 this->write_field_to_c_header(os, p->field_name(), p->type());
6641 os << ';' << std::endl;
6645 // Write the type of a struct field to a C header file.
6647 void
6648 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6649 const Type *t) const
6651 bool print_name = true;
6652 t = t->forwarded();
6653 switch (t->classification())
6655 case TYPE_VOID:
6656 os << "void";
6657 break;
6659 case TYPE_BOOLEAN:
6660 os << "_Bool";
6661 break;
6663 case TYPE_INTEGER:
6665 const Integer_type* it = t->integer_type();
6666 if (it->is_unsigned())
6667 os << 'u';
6668 os << "int" << it->bits() << "_t";
6670 break;
6672 case TYPE_FLOAT:
6673 switch (t->float_type()->bits())
6675 case 32:
6676 os << "float";
6677 break;
6678 case 64:
6679 os << "double";
6680 break;
6681 default:
6682 go_unreachable();
6684 break;
6686 case TYPE_COMPLEX:
6687 switch (t->complex_type()->bits())
6689 case 64:
6690 os << "float _Complex";
6691 break;
6692 case 128:
6693 os << "double _Complex";
6694 break;
6695 default:
6696 go_unreachable();
6698 break;
6700 case TYPE_STRING:
6701 os << "String";
6702 break;
6704 case TYPE_FUNCTION:
6705 os << "FuncVal*";
6706 break;
6708 case TYPE_POINTER:
6710 std::vector<const Named_object*> requires;
6711 std::vector<const Named_object*> declare;
6712 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6713 &declare))
6714 os << "void*";
6715 else
6717 this->write_field_to_c_header(os, "", t->points_to());
6718 os << '*';
6721 break;
6723 case TYPE_MAP:
6724 os << "Map*";
6725 break;
6727 case TYPE_CHANNEL:
6728 os << "Chan*";
6729 break;
6731 case TYPE_INTERFACE:
6732 if (t->interface_type()->is_empty())
6733 os << "Eface";
6734 else
6735 os << "Iface";
6736 break;
6738 case TYPE_STRUCT:
6739 os << "struct {" << std::endl;
6740 t->struct_type()->write_to_c_header(os);
6741 os << "\t}";
6742 break;
6744 case TYPE_ARRAY:
6745 if (t->is_slice_type())
6746 os << "Slice";
6747 else
6749 const Type *ele = t;
6750 std::vector<const Type*> array_types;
6751 while (ele->array_type() != NULL && !ele->is_slice_type())
6753 array_types.push_back(ele);
6754 ele = ele->array_type()->element_type();
6756 this->write_field_to_c_header(os, "", ele);
6757 os << ' ' << Gogo::message_name(name);
6758 print_name = false;
6759 while (!array_types.empty())
6761 ele = array_types.back();
6762 array_types.pop_back();
6763 os << '[';
6764 Numeric_constant nc;
6765 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6766 go_unreachable();
6767 mpz_t val;
6768 if (!nc.to_int(&val))
6769 go_unreachable();
6770 char* s = mpz_get_str(NULL, 10, val);
6771 os << s;
6772 free(s);
6773 mpz_clear(val);
6774 os << ']';
6777 break;
6779 case TYPE_NAMED:
6781 const Named_object* no = t->named_type()->named_object();
6782 if (t->struct_type() != NULL)
6783 os << "struct " << no->message_name();
6784 else if (t->is_unsafe_pointer_type())
6785 os << "void*";
6786 else if (t == Type::lookup_integer_type("uintptr"))
6787 os << "uintptr_t";
6788 else
6790 this->write_field_to_c_header(os, name, t->base());
6791 print_name = false;
6794 break;
6796 case TYPE_ERROR:
6797 case TYPE_FORWARD:
6798 case TYPE_CALL_MULTIPLE_RESULT:
6799 case TYPE_NIL:
6800 case TYPE_SINK:
6801 default:
6802 go_unreachable();
6805 if (print_name && !name.empty())
6806 os << ' ' << Gogo::message_name(name);
6809 // Make a struct type.
6811 Struct_type*
6812 Type::make_struct_type(Struct_field_list* fields,
6813 Location location)
6815 return new Struct_type(fields, location);
6818 // Class Array_type.
6820 // Store the length of an array as an int64_t into *PLEN. Return
6821 // false if the length can not be determined. This will assert if
6822 // called for a slice.
6824 bool
6825 Array_type::int_length(int64_t* plen)
6827 go_assert(this->length_ != NULL);
6828 Numeric_constant nc;
6829 if (!this->length_->numeric_constant_value(&nc))
6830 return false;
6831 return nc.to_memory_size(plen);
6834 // Whether two array types are identical.
6836 bool
6837 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6838 bool errors_are_identical) const
6840 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6841 cmp_tags, errors_are_identical, NULL))
6842 return false;
6844 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6845 return false;
6847 Expression* l1 = this->length();
6848 Expression* l2 = t->length();
6850 // Slices of the same element type are identical.
6851 if (l1 == NULL && l2 == NULL)
6852 return true;
6854 // Arrays of the same element type are identical if they have the
6855 // same length.
6856 if (l1 != NULL && l2 != NULL)
6858 if (l1 == l2)
6859 return true;
6861 // Try to determine the lengths. If we can't, assume the arrays
6862 // are not identical.
6863 bool ret = false;
6864 Numeric_constant nc1, nc2;
6865 if (l1->numeric_constant_value(&nc1)
6866 && l2->numeric_constant_value(&nc2))
6868 mpz_t v1;
6869 if (nc1.to_int(&v1))
6871 mpz_t v2;
6872 if (nc2.to_int(&v2))
6874 ret = mpz_cmp(v1, v2) == 0;
6875 mpz_clear(v2);
6877 mpz_clear(v1);
6880 return ret;
6883 // Otherwise the arrays are not identical.
6884 return false;
6887 // Traversal.
6890 Array_type::do_traverse(Traverse* traverse)
6892 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6893 return TRAVERSE_EXIT;
6894 if (this->length_ != NULL
6895 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6896 return TRAVERSE_EXIT;
6897 return TRAVERSE_CONTINUE;
6900 // Check that the length is valid.
6902 bool
6903 Array_type::verify_length()
6905 if (this->length_ == NULL)
6906 return true;
6908 Type_context context(Type::lookup_integer_type("int"), false);
6909 this->length_->determine_type(&context);
6911 if (!this->length_->is_constant())
6913 go_error_at(this->length_->location(), "array bound is not constant");
6914 return false;
6917 Numeric_constant nc;
6918 if (!this->length_->numeric_constant_value(&nc))
6920 if (this->length_->type()->integer_type() != NULL
6921 || this->length_->type()->float_type() != NULL)
6922 go_error_at(this->length_->location(), "array bound is not constant");
6923 else
6924 go_error_at(this->length_->location(), "array bound is not numeric");
6925 return false;
6928 Type* int_type = Type::lookup_integer_type("int");
6929 unsigned int tbits = int_type->integer_type()->bits();
6930 unsigned long val;
6931 switch (nc.to_unsigned_long(&val))
6933 case Numeric_constant::NC_UL_VALID:
6934 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
6936 go_error_at(this->length_->location(), "array bound overflows");
6937 return false;
6939 break;
6940 case Numeric_constant::NC_UL_NOTINT:
6941 go_error_at(this->length_->location(), "array bound truncated to integer");
6942 return false;
6943 case Numeric_constant::NC_UL_NEGATIVE:
6944 go_error_at(this->length_->location(), "negative array bound");
6945 return false;
6946 case Numeric_constant::NC_UL_BIG:
6948 mpz_t val;
6949 if (!nc.to_int(&val))
6950 go_unreachable();
6951 unsigned int bits = mpz_sizeinbase(val, 2);
6952 mpz_clear(val);
6953 if (bits >= tbits)
6955 go_error_at(this->length_->location(), "array bound overflows");
6956 return false;
6959 break;
6960 default:
6961 go_unreachable();
6964 return true;
6967 // Verify the type.
6969 bool
6970 Array_type::do_verify()
6972 if (this->element_type()->is_error_type())
6973 return false;
6974 if (!this->verify_length())
6975 this->length_ = Expression::make_error(this->length_->location());
6976 return true;
6979 // Whether the type contains pointers. This is always true for a
6980 // slice. For an array it is true if the element type has pointers
6981 // and the length is greater than zero.
6983 bool
6984 Array_type::do_has_pointer() const
6986 if (this->length_ == NULL)
6987 return true;
6988 if (!this->element_type_->has_pointer())
6989 return false;
6991 Numeric_constant nc;
6992 if (!this->length_->numeric_constant_value(&nc))
6994 // Error reported elsewhere.
6995 return false;
6998 unsigned long val;
6999 switch (nc.to_unsigned_long(&val))
7001 case Numeric_constant::NC_UL_VALID:
7002 return val > 0;
7003 case Numeric_constant::NC_UL_BIG:
7004 return true;
7005 default:
7006 // Error reported elsewhere.
7007 return false;
7011 // Whether we can use memcmp to compare this array.
7013 bool
7014 Array_type::do_compare_is_identity(Gogo* gogo)
7016 if (this->length_ == NULL)
7017 return false;
7019 // Check for [...], which indicates that this is not a real type.
7020 if (this->length_->is_nil_expression())
7021 return false;
7023 if (!this->element_type_->compare_is_identity(gogo))
7024 return false;
7026 // If there is any padding, then we can't use memcmp.
7027 int64_t size;
7028 int64_t align;
7029 if (!this->element_type_->backend_type_size(gogo, &size)
7030 || !this->element_type_->backend_type_align(gogo, &align))
7031 return false;
7032 if ((size & (align - 1)) != 0)
7033 return false;
7035 return true;
7038 // Array type hash code.
7040 unsigned int
7041 Array_type::do_hash_for_method(Gogo* gogo) const
7043 unsigned int ret;
7045 // There is no very convenient way to get a hash code for the
7046 // length.
7047 ret = this->element_type_->hash_for_method(gogo) + 1;
7048 if (this->is_array_incomparable_)
7049 ret <<= 1;
7050 return ret;
7053 // Write the hash function for an array which can not use the identify
7054 // function.
7056 void
7057 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7058 Function_type* hash_fntype,
7059 Function_type* equal_fntype)
7061 Location bloc = Linemap::predeclared_location();
7063 // The pointer to the array that we are going to hash. This is an
7064 // argument to the hash function we are implementing here.
7065 Named_object* key_arg = gogo->lookup("key", NULL);
7066 go_assert(key_arg != NULL);
7067 Type* key_arg_type = key_arg->var_value()->type();
7069 // The seed argument to the hash function.
7070 Named_object* seed_arg = gogo->lookup("seed", NULL);
7071 go_assert(seed_arg != NULL);
7073 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7075 // Make a temporary to hold the return value, initialized to the seed.
7076 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7077 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7078 bloc);
7079 gogo->add_statement(retval);
7081 // Make a temporary to hold the key as a uintptr.
7082 ref = Expression::make_var_reference(key_arg, bloc);
7083 ref = Expression::make_cast(uintptr_type, ref, bloc);
7084 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7085 bloc);
7086 gogo->add_statement(key);
7088 // Loop over the array elements.
7089 // for i = range a
7090 Type* int_type = Type::lookup_integer_type("int");
7091 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7092 gogo->add_statement(index);
7094 Expression* iref = Expression::make_temporary_reference(index, bloc);
7095 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7096 Type* pt = Type::make_pointer_type(name != NULL
7097 ? static_cast<Type*>(name)
7098 : static_cast<Type*>(this));
7099 aref = Expression::make_cast(pt, aref, bloc);
7100 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7101 NULL,
7102 aref,
7103 bloc);
7105 gogo->start_block(bloc);
7107 // Get the hash function for the element type.
7108 Named_object* hash_fn;
7109 Named_object* equal_fn;
7110 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7111 hash_fntype, equal_fntype, &hash_fn,
7112 &equal_fn);
7114 // Get a pointer to this element in the loop.
7115 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7116 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7118 // Get the size of each element.
7119 Expression* ele_size = Expression::make_type_info(this->element_type_,
7120 Expression::TYPE_INFO_SIZE);
7122 // Get the hash of this element, passing retval as the seed.
7123 ref = Expression::make_temporary_reference(retval, bloc);
7124 Expression_list* args = new Expression_list();
7125 args->push_back(subkey);
7126 args->push_back(ref);
7127 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7128 Expression* call = Expression::make_call(func, args, false, bloc);
7130 // Set retval to the result.
7131 Temporary_reference_expression* tref =
7132 Expression::make_temporary_reference(retval, bloc);
7133 tref->set_is_lvalue();
7134 Statement* s = Statement::make_assignment(tref, call, bloc);
7135 gogo->add_statement(s);
7137 // Increase the element pointer.
7138 tref = Expression::make_temporary_reference(key, bloc);
7139 tref->set_is_lvalue();
7140 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7141 bloc);
7142 Block* statements = gogo->finish_block(bloc);
7144 for_range->add_statements(statements);
7145 gogo->add_statement(for_range);
7147 // Return retval to the caller of the hash function.
7148 Expression_list* vals = new Expression_list();
7149 ref = Expression::make_temporary_reference(retval, bloc);
7150 vals->push_back(ref);
7151 s = Statement::make_return_statement(vals, bloc);
7152 gogo->add_statement(s);
7155 // Write the equality function for an array which can not use the
7156 // identity function.
7158 void
7159 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7161 Location bloc = Linemap::predeclared_location();
7163 // The pointers to the arrays we are going to compare.
7164 Named_object* key1_arg = gogo->lookup("key1", NULL);
7165 Named_object* key2_arg = gogo->lookup("key2", NULL);
7166 go_assert(key1_arg != NULL && key2_arg != NULL);
7168 // Build temporaries for the keys with the right types.
7169 Type* pt = Type::make_pointer_type(name != NULL
7170 ? static_cast<Type*>(name)
7171 : static_cast<Type*>(this));
7173 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7174 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7175 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7176 gogo->add_statement(p1);
7178 ref = Expression::make_var_reference(key2_arg, bloc);
7179 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7180 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7181 gogo->add_statement(p2);
7183 // Loop over the array elements.
7184 // for i = range a
7185 Type* int_type = Type::lookup_integer_type("int");
7186 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7187 gogo->add_statement(index);
7189 Expression* iref = Expression::make_temporary_reference(index, bloc);
7190 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7191 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7192 NULL,
7193 aref,
7194 bloc);
7196 gogo->start_block(bloc);
7198 // Compare element in P1 and P2.
7199 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7200 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7201 ref = Expression::make_temporary_reference(index, bloc);
7202 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7204 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7205 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7206 ref = Expression::make_temporary_reference(index, bloc);
7207 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7209 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7211 // If the elements are not equal, return false.
7212 gogo->start_block(bloc);
7213 Expression_list* vals = new Expression_list();
7214 vals->push_back(Expression::make_boolean(false, bloc));
7215 Statement* s = Statement::make_return_statement(vals, bloc);
7216 gogo->add_statement(s);
7217 Block* then_block = gogo->finish_block(bloc);
7219 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7220 gogo->add_statement(s);
7222 Block* statements = gogo->finish_block(bloc);
7224 for_range->add_statements(statements);
7225 gogo->add_statement(for_range);
7227 // All the elements are equal, so return true.
7228 vals = new Expression_list();
7229 vals->push_back(Expression::make_boolean(true, bloc));
7230 s = Statement::make_return_statement(vals, bloc);
7231 gogo->add_statement(s);
7234 // Get the backend representation of the fields of a slice. This is
7235 // not declared in types.h so that types.h doesn't have to #include
7236 // backend.h.
7238 // We use int for the count and capacity fields. This matches 6g.
7239 // The language more or less assumes that we can't allocate space of a
7240 // size which does not fit in int.
7242 static void
7243 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7244 std::vector<Backend::Btyped_identifier>* bfields)
7246 bfields->resize(3);
7248 Type* pet = Type::make_pointer_type(type->element_type());
7249 Btype* pbet = (use_placeholder
7250 ? pet->get_backend_placeholder(gogo)
7251 : pet->get_backend(gogo));
7252 Location ploc = Linemap::predeclared_location();
7254 Backend::Btyped_identifier* p = &(*bfields)[0];
7255 p->name = "__values";
7256 p->btype = pbet;
7257 p->location = ploc;
7259 Type* int_type = Type::lookup_integer_type("int");
7261 p = &(*bfields)[1];
7262 p->name = "__count";
7263 p->btype = int_type->get_backend(gogo);
7264 p->location = ploc;
7266 p = &(*bfields)[2];
7267 p->name = "__capacity";
7268 p->btype = int_type->get_backend(gogo);
7269 p->location = ploc;
7272 // Get the backend representation for the type of this array. A fixed array is
7273 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7274 // just like an array in C. An open array is a struct with three
7275 // fields: a data pointer, the length, and the capacity.
7277 Btype*
7278 Array_type::do_get_backend(Gogo* gogo)
7280 if (this->length_ == NULL)
7282 std::vector<Backend::Btyped_identifier> bfields;
7283 get_backend_slice_fields(gogo, this, false, &bfields);
7284 return gogo->backend()->struct_type(bfields);
7286 else
7288 Btype* element = this->get_backend_element(gogo, false);
7289 Bexpression* len = this->get_backend_length(gogo);
7290 return gogo->backend()->array_type(element, len);
7294 // Return the backend representation of the element type.
7296 Btype*
7297 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7299 if (use_placeholder)
7300 return this->element_type_->get_backend_placeholder(gogo);
7301 else
7302 return this->element_type_->get_backend(gogo);
7305 // Return the backend representation of the length. The length may be
7306 // computed using a function call, so we must only evaluate it once.
7308 Bexpression*
7309 Array_type::get_backend_length(Gogo* gogo)
7311 go_assert(this->length_ != NULL);
7312 if (this->blength_ == NULL)
7314 if (this->length_->is_error_expression())
7316 this->blength_ = gogo->backend()->error_expression();
7317 return this->blength_;
7319 Numeric_constant nc;
7320 mpz_t val;
7321 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7323 if (mpz_sgn(val) < 0)
7325 this->blength_ = gogo->backend()->error_expression();
7326 return this->blength_;
7328 Type* t = nc.type();
7329 if (t == NULL)
7330 t = Type::lookup_integer_type("int");
7331 else if (t->is_abstract())
7332 t = t->make_non_abstract_type();
7333 Btype* btype = t->get_backend(gogo);
7334 this->blength_ =
7335 gogo->backend()->integer_constant_expression(btype, val);
7336 mpz_clear(val);
7338 else
7340 // Make up a translation context for the array length
7341 // expression. FIXME: This won't work in general.
7342 Translate_context context(gogo, NULL, NULL, NULL);
7343 this->blength_ = this->length_->get_backend(&context);
7345 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7346 this->blength_ =
7347 gogo->backend()->convert_expression(ibtype, this->blength_,
7348 this->length_->location());
7351 return this->blength_;
7354 // Finish backend representation of the array.
7356 void
7357 Array_type::finish_backend_element(Gogo* gogo)
7359 Type* et = this->array_type()->element_type();
7360 et->get_backend(gogo);
7361 if (this->is_slice_type())
7363 // This relies on the fact that we always use the same
7364 // structure for a pointer to any given type.
7365 Type* pet = Type::make_pointer_type(et);
7366 pet->get_backend(gogo);
7370 // Return an expression for a pointer to the values in ARRAY.
7372 Expression*
7373 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7375 if (this->length() != NULL)
7377 // Fixed array.
7378 go_assert(array->type()->array_type() != NULL);
7379 Type* etype = array->type()->array_type()->element_type();
7380 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7381 return Expression::make_cast(Type::make_pointer_type(etype), array,
7382 array->location());
7385 // Slice.
7387 if (is_lvalue)
7389 Temporary_reference_expression* tref =
7390 array->temporary_reference_expression();
7391 Var_expression* ve = array->var_expression();
7392 if (tref != NULL)
7394 tref = tref->copy()->temporary_reference_expression();
7395 tref->set_is_lvalue();
7396 array = tref;
7398 else if (ve != NULL)
7400 ve = new Var_expression(ve->named_object(), ve->location());
7401 array = ve;
7405 return Expression::make_slice_info(array,
7406 Expression::SLICE_INFO_VALUE_POINTER,
7407 array->location());
7410 // Return an expression for the length of the array ARRAY which has this
7411 // type.
7413 Expression*
7414 Array_type::get_length(Gogo*, Expression* array) const
7416 if (this->length_ != NULL)
7417 return this->length_;
7419 // This is a slice. We need to read the length field.
7420 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7421 array->location());
7424 // Return an expression for the capacity of the array ARRAY which has this
7425 // type.
7427 Expression*
7428 Array_type::get_capacity(Gogo*, Expression* array) const
7430 if (this->length_ != NULL)
7431 return this->length_;
7433 // This is a slice. We need to read the capacity field.
7434 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7435 array->location());
7438 // Export.
7440 void
7441 Array_type::do_export(Export* exp) const
7443 exp->write_c_string("[");
7444 if (this->length_ != NULL)
7445 this->length_->export_expression(exp);
7446 exp->write_c_string("] ");
7447 exp->write_type(this->element_type_);
7450 // Import.
7452 Array_type*
7453 Array_type::do_import(Import* imp)
7455 imp->require_c_string("[");
7456 Expression* length;
7457 if (imp->peek_char() == ']')
7458 length = NULL;
7459 else
7460 length = Expression::import_expression(imp);
7461 imp->require_c_string("] ");
7462 Type* element_type = imp->read_type();
7463 return Type::make_array_type(element_type, length);
7466 // The type of an array type descriptor.
7468 Type*
7469 Array_type::make_array_type_descriptor_type()
7471 static Type* ret;
7472 if (ret == NULL)
7474 Type* tdt = Type::make_type_descriptor_type();
7475 Type* ptdt = Type::make_type_descriptor_ptr_type();
7477 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7479 Struct_type* sf =
7480 Type::make_builtin_struct_type(4,
7481 "", tdt,
7482 "elem", ptdt,
7483 "slice", ptdt,
7484 "len", uintptr_type);
7486 ret = Type::make_builtin_named_type("ArrayType", sf);
7489 return ret;
7492 // The type of an slice type descriptor.
7494 Type*
7495 Array_type::make_slice_type_descriptor_type()
7497 static Type* ret;
7498 if (ret == NULL)
7500 Type* tdt = Type::make_type_descriptor_type();
7501 Type* ptdt = Type::make_type_descriptor_ptr_type();
7503 Struct_type* sf =
7504 Type::make_builtin_struct_type(2,
7505 "", tdt,
7506 "elem", ptdt);
7508 ret = Type::make_builtin_named_type("SliceType", sf);
7511 return ret;
7514 // Build a type descriptor for an array/slice type.
7516 Expression*
7517 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7519 if (this->length_ != NULL)
7520 return this->array_type_descriptor(gogo, name);
7521 else
7522 return this->slice_type_descriptor(gogo, name);
7525 // Build a type descriptor for an array type.
7527 Expression*
7528 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7530 Location bloc = Linemap::predeclared_location();
7532 Type* atdt = Array_type::make_array_type_descriptor_type();
7534 const Struct_field_list* fields = atdt->struct_type()->fields();
7536 Expression_list* vals = new Expression_list();
7537 vals->reserve(3);
7539 Struct_field_list::const_iterator p = fields->begin();
7540 go_assert(p->is_field_name("_type"));
7541 vals->push_back(this->type_descriptor_constructor(gogo,
7542 RUNTIME_TYPE_KIND_ARRAY,
7543 name, NULL, true));
7545 ++p;
7546 go_assert(p->is_field_name("elem"));
7547 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7549 ++p;
7550 go_assert(p->is_field_name("slice"));
7551 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7552 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7554 ++p;
7555 go_assert(p->is_field_name("len"));
7556 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7558 ++p;
7559 go_assert(p == fields->end());
7561 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7564 // Build a type descriptor for a slice type.
7566 Expression*
7567 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7569 Location bloc = Linemap::predeclared_location();
7571 Type* stdt = Array_type::make_slice_type_descriptor_type();
7573 const Struct_field_list* fields = stdt->struct_type()->fields();
7575 Expression_list* vals = new Expression_list();
7576 vals->reserve(2);
7578 Struct_field_list::const_iterator p = fields->begin();
7579 go_assert(p->is_field_name("_type"));
7580 vals->push_back(this->type_descriptor_constructor(gogo,
7581 RUNTIME_TYPE_KIND_SLICE,
7582 name, NULL, true));
7584 ++p;
7585 go_assert(p->is_field_name("elem"));
7586 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7588 ++p;
7589 go_assert(p == fields->end());
7591 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7594 // Reflection string.
7596 void
7597 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7599 ret->push_back('[');
7600 if (this->length_ != NULL)
7602 Numeric_constant nc;
7603 if (!this->length_->numeric_constant_value(&nc))
7605 go_assert(saw_errors());
7606 return;
7608 mpz_t val;
7609 if (!nc.to_int(&val))
7611 go_assert(saw_errors());
7612 return;
7614 char* s = mpz_get_str(NULL, 10, val);
7615 ret->append(s);
7616 free(s);
7617 mpz_clear(val);
7619 ret->push_back(']');
7621 this->append_reflection(this->element_type_, gogo, ret);
7624 // Make an array type.
7626 Array_type*
7627 Type::make_array_type(Type* element_type, Expression* length)
7629 return new Array_type(element_type, length);
7632 // Class Map_type.
7634 Named_object* Map_type::zero_value;
7635 int64_t Map_type::zero_value_size;
7636 int64_t Map_type::zero_value_align;
7638 // If this map requires the "fat" functions, return the pointer to
7639 // pass as the zero value to those functions. Otherwise, in the
7640 // normal case, return NULL. The map requires the "fat" functions if
7641 // the value size is larger than max_zero_size bytes. max_zero_size
7642 // must match maxZero in libgo/go/runtime/hashmap.go.
7644 Expression*
7645 Map_type::fat_zero_value(Gogo* gogo)
7647 int64_t valsize;
7648 if (!this->val_type_->backend_type_size(gogo, &valsize))
7650 go_assert(saw_errors());
7651 return NULL;
7653 if (valsize <= Map_type::max_zero_size)
7654 return NULL;
7656 if (Map_type::zero_value_size < valsize)
7657 Map_type::zero_value_size = valsize;
7659 int64_t valalign;
7660 if (!this->val_type_->backend_type_align(gogo, &valalign))
7662 go_assert(saw_errors());
7663 return NULL;
7666 if (Map_type::zero_value_align < valalign)
7667 Map_type::zero_value_align = valalign;
7669 Location bloc = Linemap::predeclared_location();
7671 if (Map_type::zero_value == NULL)
7673 // The final type will be set in backend_zero_value.
7674 Type* uint8_type = Type::lookup_integer_type("uint8");
7675 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7676 Array_type* array_type = Type::make_array_type(uint8_type, size);
7677 array_type->set_is_array_incomparable();
7678 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7679 std::string name = gogo->map_zero_value_name();
7680 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7683 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7684 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7685 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7686 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7687 return z;
7690 // Return whether VAR is the map zero value.
7692 bool
7693 Map_type::is_zero_value(Variable* var)
7695 return (Map_type::zero_value != NULL
7696 && Map_type::zero_value->var_value() == var);
7699 // Return the backend representation for the zero value.
7701 Bvariable*
7702 Map_type::backend_zero_value(Gogo* gogo)
7704 Location bloc = Linemap::predeclared_location();
7706 go_assert(Map_type::zero_value != NULL);
7708 Type* uint8_type = Type::lookup_integer_type("uint8");
7709 Btype* buint8_type = uint8_type->get_backend(gogo);
7711 Type* int_type = Type::lookup_integer_type("int");
7713 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7714 int_type, bloc);
7715 Translate_context context(gogo, NULL, NULL, NULL);
7716 Bexpression* blength = e->get_backend(&context);
7718 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7720 std::string zname = Map_type::zero_value->name();
7721 std::string asm_name(go_selectively_encode_id(zname));
7722 Bvariable* zvar =
7723 gogo->backend()->implicit_variable(zname, asm_name,
7724 barray_type, false, false, true,
7725 Map_type::zero_value_align);
7726 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7727 false, false, true, NULL);
7728 return zvar;
7731 // Traversal.
7734 Map_type::do_traverse(Traverse* traverse)
7736 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7737 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7738 return TRAVERSE_EXIT;
7739 return TRAVERSE_CONTINUE;
7742 // Check that the map type is OK.
7744 bool
7745 Map_type::do_verify()
7747 // The runtime support uses "map[void]void".
7748 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7749 go_error_at(this->location_, "invalid map key type");
7750 if (!this->key_type_->in_heap())
7751 go_error_at(this->location_, "go:notinheap map key not allowed");
7752 if (!this->val_type_->in_heap())
7753 go_error_at(this->location_, "go:notinheap map value not allowed");
7754 return true;
7757 // Whether two map types are identical.
7759 bool
7760 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7761 bool errors_are_identical) const
7763 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7764 cmp_tags, errors_are_identical, NULL)
7765 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7766 cmp_tags, errors_are_identical,
7767 NULL));
7770 // Hash code.
7772 unsigned int
7773 Map_type::do_hash_for_method(Gogo* gogo) const
7775 return (this->key_type_->hash_for_method(gogo)
7776 + this->val_type_->hash_for_method(gogo)
7777 + 2);
7780 // Get the backend representation for a map type. A map type is
7781 // represented as a pointer to a struct. The struct is hmap in
7782 // runtime/hashmap.go.
7784 Btype*
7785 Map_type::do_get_backend(Gogo* gogo)
7787 static Btype* backend_map_type;
7788 if (backend_map_type == NULL)
7790 std::vector<Backend::Btyped_identifier> bfields(9);
7792 Location bloc = Linemap::predeclared_location();
7794 Type* int_type = Type::lookup_integer_type("int");
7795 bfields[0].name = "count";
7796 bfields[0].btype = int_type->get_backend(gogo);
7797 bfields[0].location = bloc;
7799 Type* uint8_type = Type::lookup_integer_type("uint8");
7800 bfields[1].name = "flags";
7801 bfields[1].btype = uint8_type->get_backend(gogo);
7802 bfields[1].location = bloc;
7804 bfields[2].name = "B";
7805 bfields[2].btype = bfields[1].btype;
7806 bfields[2].location = bloc;
7808 Type* uint16_type = Type::lookup_integer_type("uint16");
7809 bfields[3].name = "noverflow";
7810 bfields[3].btype = uint16_type->get_backend(gogo);
7811 bfields[3].location = bloc;
7813 Type* uint32_type = Type::lookup_integer_type("uint32");
7814 bfields[4].name = "hash0";
7815 bfields[4].btype = uint32_type->get_backend(gogo);
7816 bfields[4].location = bloc;
7818 Btype* bvt = gogo->backend()->void_type();
7819 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7820 bfields[5].name = "buckets";
7821 bfields[5].btype = bpvt;
7822 bfields[5].location = bloc;
7824 bfields[6].name = "oldbuckets";
7825 bfields[6].btype = bpvt;
7826 bfields[6].location = bloc;
7828 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7829 bfields[7].name = "nevacuate";
7830 bfields[7].btype = uintptr_type->get_backend(gogo);
7831 bfields[7].location = bloc;
7833 bfields[8].name = "overflow";
7834 bfields[8].btype = bpvt;
7835 bfields[8].location = bloc;
7837 Btype *bt = gogo->backend()->struct_type(bfields);
7838 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7839 backend_map_type = gogo->backend()->pointer_type(bt);
7841 return backend_map_type;
7844 // The type of a map type descriptor.
7846 Type*
7847 Map_type::make_map_type_descriptor_type()
7849 static Type* ret;
7850 if (ret == NULL)
7852 Type* tdt = Type::make_type_descriptor_type();
7853 Type* ptdt = Type::make_type_descriptor_ptr_type();
7854 Type* uint8_type = Type::lookup_integer_type("uint8");
7855 Type* uint16_type = Type::lookup_integer_type("uint16");
7856 Type* bool_type = Type::lookup_bool_type();
7858 Struct_type* sf =
7859 Type::make_builtin_struct_type(12,
7860 "", tdt,
7861 "key", ptdt,
7862 "elem", ptdt,
7863 "bucket", ptdt,
7864 "hmap", ptdt,
7865 "keysize", uint8_type,
7866 "indirectkey", bool_type,
7867 "valuesize", uint8_type,
7868 "indirectvalue", bool_type,
7869 "bucketsize", uint16_type,
7870 "reflexivekey", bool_type,
7871 "needkeyupdate", bool_type);
7873 ret = Type::make_builtin_named_type("MapType", sf);
7876 return ret;
7879 // Build a type descriptor for a map type.
7881 Expression*
7882 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7884 Location bloc = Linemap::predeclared_location();
7886 Type* mtdt = Map_type::make_map_type_descriptor_type();
7887 Type* uint8_type = Type::lookup_integer_type("uint8");
7888 Type* uint16_type = Type::lookup_integer_type("uint16");
7890 int64_t keysize;
7891 if (!this->key_type_->backend_type_size(gogo, &keysize))
7893 go_error_at(this->location_, "error determining map key type size");
7894 return Expression::make_error(this->location_);
7897 int64_t valsize;
7898 if (!this->val_type_->backend_type_size(gogo, &valsize))
7900 go_error_at(this->location_, "error determining map value type size");
7901 return Expression::make_error(this->location_);
7904 int64_t ptrsize;
7905 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
7907 go_assert(saw_errors());
7908 return Expression::make_error(this->location_);
7911 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
7912 if (bucket_type == NULL)
7914 go_assert(saw_errors());
7915 return Expression::make_error(this->location_);
7918 int64_t bucketsize;
7919 if (!bucket_type->backend_type_size(gogo, &bucketsize))
7921 go_assert(saw_errors());
7922 return Expression::make_error(this->location_);
7925 const Struct_field_list* fields = mtdt->struct_type()->fields();
7927 Expression_list* vals = new Expression_list();
7928 vals->reserve(12);
7930 Struct_field_list::const_iterator p = fields->begin();
7931 go_assert(p->is_field_name("_type"));
7932 vals->push_back(this->type_descriptor_constructor(gogo,
7933 RUNTIME_TYPE_KIND_MAP,
7934 name, NULL, true));
7936 ++p;
7937 go_assert(p->is_field_name("key"));
7938 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
7940 ++p;
7941 go_assert(p->is_field_name("elem"));
7942 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
7944 ++p;
7945 go_assert(p->is_field_name("bucket"));
7946 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
7948 ++p;
7949 go_assert(p->is_field_name("hmap"));
7950 Type* hmap_type = this->hmap_type(bucket_type);
7951 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
7953 ++p;
7954 go_assert(p->is_field_name("keysize"));
7955 if (keysize > Map_type::max_key_size)
7956 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
7957 else
7958 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
7960 ++p;
7961 go_assert(p->is_field_name("indirectkey"));
7962 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
7963 bloc));
7965 ++p;
7966 go_assert(p->is_field_name("valuesize"));
7967 if (valsize > Map_type::max_val_size)
7968 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
7969 else
7970 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
7972 ++p;
7973 go_assert(p->is_field_name("indirectvalue"));
7974 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
7975 bloc));
7977 ++p;
7978 go_assert(p->is_field_name("bucketsize"));
7979 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
7980 bloc));
7982 ++p;
7983 go_assert(p->is_field_name("reflexivekey"));
7984 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
7985 bloc));
7987 ++p;
7988 go_assert(p->is_field_name("needkeyupdate"));
7989 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
7990 bloc));
7992 ++p;
7993 go_assert(p == fields->end());
7995 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
7998 // Return the bucket type to use for a map type. This must correspond
7999 // to libgo/go/runtime/hashmap.go.
8001 Type*
8002 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8004 if (this->bucket_type_ != NULL)
8005 return this->bucket_type_;
8007 Type* key_type = this->key_type_;
8008 if (keysize > Map_type::max_key_size)
8009 key_type = Type::make_pointer_type(key_type);
8011 Type* val_type = this->val_type_;
8012 if (valsize > Map_type::max_val_size)
8013 val_type = Type::make_pointer_type(val_type);
8015 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8016 NULL, this->location_);
8018 Type* uint8_type = Type::lookup_integer_type("uint8");
8019 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8020 topbits_type->set_is_array_incomparable();
8021 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8022 keys_type->set_is_array_incomparable();
8023 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8024 values_type->set_is_array_incomparable();
8026 // If keys and values have no pointers, the map implementation can
8027 // keep a list of overflow pointers on the side so that buckets can
8028 // be marked as having no pointers. Arrange for the bucket to have
8029 // no pointers by changing the type of the overflow field to uintptr
8030 // in this case. See comment on the hmap.overflow field in
8031 // libgo/go/runtime/hashmap.go.
8032 Type* overflow_type;
8033 if (!key_type->has_pointer() && !val_type->has_pointer())
8034 overflow_type = Type::lookup_integer_type("uintptr");
8035 else
8037 // This should really be a pointer to the bucket type itself,
8038 // but that would require us to construct a Named_type for it to
8039 // give it a way to refer to itself. Since nothing really cares
8040 // (except perhaps for someone using a debugger) just use an
8041 // unsafe pointer.
8042 overflow_type = Type::make_pointer_type(Type::make_void_type());
8045 // Make sure the overflow pointer is the last memory in the struct,
8046 // because the runtime assumes it can use size-ptrSize as the offset
8047 // of the overflow pointer. We double-check that property below
8048 // once the offsets and size are computed.
8050 int64_t topbits_field_size, topbits_field_align;
8051 int64_t keys_field_size, keys_field_align;
8052 int64_t values_field_size, values_field_align;
8053 int64_t overflow_field_size, overflow_field_align;
8054 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8055 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8056 || !keys_type->backend_type_size(gogo, &keys_field_size)
8057 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8058 || !values_type->backend_type_size(gogo, &values_field_size)
8059 || !values_type->backend_type_field_align(gogo, &values_field_align)
8060 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8061 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8063 go_assert(saw_errors());
8064 return NULL;
8067 Struct_type* ret;
8068 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8069 values_field_align);
8070 if (max_align <= overflow_field_align)
8071 ret = make_builtin_struct_type(4,
8072 "topbits", topbits_type,
8073 "keys", keys_type,
8074 "values", values_type,
8075 "overflow", overflow_type);
8076 else
8078 size_t off = topbits_field_size;
8079 off = ((off + keys_field_align - 1)
8080 &~ static_cast<size_t>(keys_field_align - 1));
8081 off += keys_field_size;
8082 off = ((off + values_field_align - 1)
8083 &~ static_cast<size_t>(values_field_align - 1));
8084 off += values_field_size;
8086 int64_t padded_overflow_field_size =
8087 ((overflow_field_size + max_align - 1)
8088 &~ static_cast<size_t>(max_align - 1));
8090 size_t ovoff = off;
8091 ovoff = ((ovoff + max_align - 1)
8092 &~ static_cast<size_t>(max_align - 1));
8093 size_t pad = (ovoff - off
8094 + padded_overflow_field_size - overflow_field_size);
8096 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8097 this->location_);
8098 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8099 pad_type->set_is_array_incomparable();
8101 ret = make_builtin_struct_type(5,
8102 "topbits", topbits_type,
8103 "keys", keys_type,
8104 "values", values_type,
8105 "pad", pad_type,
8106 "overflow", overflow_type);
8109 // Verify that the overflow field is just before the end of the
8110 // bucket type.
8112 Btype* btype = ret->get_backend(gogo);
8113 int64_t offset = gogo->backend()->type_field_offset(btype,
8114 ret->field_count() - 1);
8115 int64_t size;
8116 if (!ret->backend_type_size(gogo, &size))
8118 go_assert(saw_errors());
8119 return NULL;
8122 int64_t ptr_size;
8123 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8125 go_assert(saw_errors());
8126 return NULL;
8129 go_assert(offset + ptr_size == size);
8131 ret->set_is_struct_incomparable();
8133 this->bucket_type_ = ret;
8134 return ret;
8137 // Return the hashmap type for a map type.
8139 Type*
8140 Map_type::hmap_type(Type* bucket_type)
8142 if (this->hmap_type_ != NULL)
8143 return this->hmap_type_;
8145 Type* int_type = Type::lookup_integer_type("int");
8146 Type* uint8_type = Type::lookup_integer_type("uint8");
8147 Type* uint32_type = Type::lookup_integer_type("uint32");
8148 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8149 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8151 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8153 Struct_type* ret = make_builtin_struct_type(8,
8154 "count", int_type,
8155 "flags", uint8_type,
8156 "B", uint8_type,
8157 "hash0", uint32_type,
8158 "buckets", ptr_bucket_type,
8159 "oldbuckets", ptr_bucket_type,
8160 "nevacuate", uintptr_type,
8161 "overflow", void_ptr_type);
8162 ret->set_is_struct_incomparable();
8163 this->hmap_type_ = ret;
8164 return ret;
8167 // Return the iterator type for a map type. This is the type of the
8168 // value used when doing a range over a map.
8170 Type*
8171 Map_type::hiter_type(Gogo* gogo)
8173 if (this->hiter_type_ != NULL)
8174 return this->hiter_type_;
8176 int64_t keysize, valsize;
8177 if (!this->key_type_->backend_type_size(gogo, &keysize)
8178 || !this->val_type_->backend_type_size(gogo, &valsize))
8180 go_assert(saw_errors());
8181 return NULL;
8184 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8185 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8186 Type* uint8_type = Type::lookup_integer_type("uint8");
8187 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8188 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8189 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8190 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8191 Type* hmap_type = this->hmap_type(bucket_type);
8192 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8193 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8195 Struct_type* ret = make_builtin_struct_type(12,
8196 "key", key_ptr_type,
8197 "val", val_ptr_type,
8198 "t", uint8_ptr_type,
8199 "h", hmap_ptr_type,
8200 "buckets", bucket_ptr_type,
8201 "bptr", bucket_ptr_type,
8202 "overflow0", void_ptr_type,
8203 "overflow1", void_ptr_type,
8204 "startBucket", uintptr_type,
8205 "stuff", uintptr_type,
8206 "bucket", uintptr_type,
8207 "checkBucket", uintptr_type);
8208 ret->set_is_struct_incomparable();
8209 this->hiter_type_ = ret;
8210 return ret;
8213 // Reflection string for a map.
8215 void
8216 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8218 ret->append("map[");
8219 this->append_reflection(this->key_type_, gogo, ret);
8220 ret->append("]");
8221 this->append_reflection(this->val_type_, gogo, ret);
8224 // Export a map type.
8226 void
8227 Map_type::do_export(Export* exp) const
8229 exp->write_c_string("map [");
8230 exp->write_type(this->key_type_);
8231 exp->write_c_string("] ");
8232 exp->write_type(this->val_type_);
8235 // Import a map type.
8237 Map_type*
8238 Map_type::do_import(Import* imp)
8240 imp->require_c_string("map [");
8241 Type* key_type = imp->read_type();
8242 imp->require_c_string("] ");
8243 Type* val_type = imp->read_type();
8244 return Type::make_map_type(key_type, val_type, imp->location());
8247 // Make a map type.
8249 Map_type*
8250 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8252 return new Map_type(key_type, val_type, location);
8255 // Class Channel_type.
8257 // Verify.
8259 bool
8260 Channel_type::do_verify()
8262 // We have no location for this error, but this is not something the
8263 // ordinary user will see.
8264 if (!this->element_type_->in_heap())
8265 go_error_at(Linemap::unknown_location(),
8266 "chan of go:notinheap type not allowed");
8267 return true;
8270 // Hash code.
8272 unsigned int
8273 Channel_type::do_hash_for_method(Gogo* gogo) const
8275 unsigned int ret = 0;
8276 if (this->may_send_)
8277 ret += 1;
8278 if (this->may_receive_)
8279 ret += 2;
8280 if (this->element_type_ != NULL)
8281 ret += this->element_type_->hash_for_method(gogo) << 2;
8282 return ret << 3;
8285 // Whether this type is the same as T.
8287 bool
8288 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8289 bool errors_are_identical) const
8291 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8292 cmp_tags, errors_are_identical, NULL))
8293 return false;
8294 return (this->may_send_ == t->may_send_
8295 && this->may_receive_ == t->may_receive_);
8298 // Return the backend representation for a channel type. A channel is a pointer
8299 // to a __go_channel struct. The __go_channel struct is defined in
8300 // libgo/runtime/channel.h.
8302 Btype*
8303 Channel_type::do_get_backend(Gogo* gogo)
8305 static Btype* backend_channel_type;
8306 if (backend_channel_type == NULL)
8308 std::vector<Backend::Btyped_identifier> bfields;
8309 Btype* bt = gogo->backend()->struct_type(bfields);
8310 bt = gogo->backend()->named_type("__go_channel", bt,
8311 Linemap::predeclared_location());
8312 backend_channel_type = gogo->backend()->pointer_type(bt);
8314 return backend_channel_type;
8317 // Build a type descriptor for a channel type.
8319 Type*
8320 Channel_type::make_chan_type_descriptor_type()
8322 static Type* ret;
8323 if (ret == NULL)
8325 Type* tdt = Type::make_type_descriptor_type();
8326 Type* ptdt = Type::make_type_descriptor_ptr_type();
8328 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8330 Struct_type* sf =
8331 Type::make_builtin_struct_type(3,
8332 "", tdt,
8333 "elem", ptdt,
8334 "dir", uintptr_type);
8336 ret = Type::make_builtin_named_type("ChanType", sf);
8339 return ret;
8342 // Build a type descriptor for a map type.
8344 Expression*
8345 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8347 Location bloc = Linemap::predeclared_location();
8349 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8351 const Struct_field_list* fields = ctdt->struct_type()->fields();
8353 Expression_list* vals = new Expression_list();
8354 vals->reserve(3);
8356 Struct_field_list::const_iterator p = fields->begin();
8357 go_assert(p->is_field_name("_type"));
8358 vals->push_back(this->type_descriptor_constructor(gogo,
8359 RUNTIME_TYPE_KIND_CHAN,
8360 name, NULL, true));
8362 ++p;
8363 go_assert(p->is_field_name("elem"));
8364 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8366 ++p;
8367 go_assert(p->is_field_name("dir"));
8368 // These bits must match the ones in libgo/runtime/go-type.h.
8369 int val = 0;
8370 if (this->may_receive_)
8371 val |= 1;
8372 if (this->may_send_)
8373 val |= 2;
8374 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8376 ++p;
8377 go_assert(p == fields->end());
8379 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8382 // Reflection string.
8384 void
8385 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8387 if (!this->may_send_)
8388 ret->append("<-");
8389 ret->append("chan");
8390 if (!this->may_receive_)
8391 ret->append("<-");
8392 ret->push_back(' ');
8393 this->append_reflection(this->element_type_, gogo, ret);
8396 // Export.
8398 void
8399 Channel_type::do_export(Export* exp) const
8401 exp->write_c_string("chan ");
8402 if (this->may_send_ && !this->may_receive_)
8403 exp->write_c_string("-< ");
8404 else if (this->may_receive_ && !this->may_send_)
8405 exp->write_c_string("<- ");
8406 exp->write_type(this->element_type_);
8409 // Import.
8411 Channel_type*
8412 Channel_type::do_import(Import* imp)
8414 imp->require_c_string("chan ");
8416 bool may_send;
8417 bool may_receive;
8418 if (imp->match_c_string("-< "))
8420 imp->advance(3);
8421 may_send = true;
8422 may_receive = false;
8424 else if (imp->match_c_string("<- "))
8426 imp->advance(3);
8427 may_receive = true;
8428 may_send = false;
8430 else
8432 may_send = true;
8433 may_receive = true;
8436 Type* element_type = imp->read_type();
8438 return Type::make_channel_type(may_send, may_receive, element_type);
8441 // Return the type to manage a select statement with ncases case
8442 // statements. A value of this type is allocated on the stack. This
8443 // must match the type hselect in libgo/go/runtime/select.go.
8445 Type*
8446 Channel_type::select_type(int ncases)
8448 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8449 Type* uint16_type = Type::lookup_integer_type("uint16");
8451 static Struct_type* scase_type;
8452 if (scase_type == NULL)
8454 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8455 Type* uint64_type = Type::lookup_integer_type("uint64");
8456 scase_type =
8457 Type::make_builtin_struct_type(7,
8458 "elem", unsafe_pointer_type,
8459 "chan", unsafe_pointer_type,
8460 "pc", uintptr_type,
8461 "kind", uint16_type,
8462 "index", uint16_type,
8463 "receivedp", unsafe_pointer_type,
8464 "releasetime", uint64_type);
8465 scase_type->set_is_struct_incomparable();
8468 Expression* ncases_expr =
8469 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8470 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8471 scases->set_is_array_incomparable();
8472 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8473 order->set_is_array_incomparable();
8475 Struct_type* ret =
8476 Type::make_builtin_struct_type(7,
8477 "tcase", uint16_type,
8478 "ncase", uint16_type,
8479 "pollorder", unsafe_pointer_type,
8480 "lockorder", unsafe_pointer_type,
8481 "scase", scases,
8482 "lockorderarr", order,
8483 "pollorderarr", order);
8484 ret->set_is_struct_incomparable();
8485 return ret;
8488 // Make a new channel type.
8490 Channel_type*
8491 Type::make_channel_type(bool send, bool receive, Type* element_type)
8493 return new Channel_type(send, receive, element_type);
8496 // Class Interface_type.
8498 // Return the list of methods.
8500 const Typed_identifier_list*
8501 Interface_type::methods() const
8503 go_assert(this->methods_are_finalized_ || saw_errors());
8504 return this->all_methods_;
8507 // Return the number of methods.
8509 size_t
8510 Interface_type::method_count() const
8512 go_assert(this->methods_are_finalized_ || saw_errors());
8513 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8516 // Traversal.
8519 Interface_type::do_traverse(Traverse* traverse)
8521 Typed_identifier_list* methods = (this->methods_are_finalized_
8522 ? this->all_methods_
8523 : this->parse_methods_);
8524 if (methods == NULL)
8525 return TRAVERSE_CONTINUE;
8526 return methods->traverse(traverse);
8529 // Finalize the methods. This handles interface inheritance.
8531 void
8532 Interface_type::finalize_methods()
8534 if (this->methods_are_finalized_)
8535 return;
8536 this->methods_are_finalized_ = true;
8537 if (this->parse_methods_ == NULL)
8538 return;
8540 this->all_methods_ = new Typed_identifier_list();
8541 this->all_methods_->reserve(this->parse_methods_->size());
8542 Typed_identifier_list inherit;
8543 for (Typed_identifier_list::const_iterator pm =
8544 this->parse_methods_->begin();
8545 pm != this->parse_methods_->end();
8546 ++pm)
8548 const Typed_identifier* p = &*pm;
8549 if (p->name().empty())
8550 inherit.push_back(*p);
8551 else if (this->find_method(p->name()) == NULL)
8552 this->all_methods_->push_back(*p);
8553 else
8554 go_error_at(p->location(), "duplicate method %qs",
8555 Gogo::message_name(p->name()).c_str());
8558 std::vector<Named_type*> seen;
8559 seen.reserve(inherit.size());
8560 bool issued_recursive_error = false;
8561 while (!inherit.empty())
8563 Type* t = inherit.back().type();
8564 Location tl = inherit.back().location();
8565 inherit.pop_back();
8567 Interface_type* it = t->interface_type();
8568 if (it == NULL)
8570 if (!t->is_error())
8571 go_error_at(tl, "interface contains embedded non-interface");
8572 continue;
8574 if (it == this)
8576 if (!issued_recursive_error)
8578 go_error_at(tl, "invalid recursive interface");
8579 issued_recursive_error = true;
8581 continue;
8584 Named_type* nt = t->named_type();
8585 if (nt != NULL && it->parse_methods_ != NULL)
8587 std::vector<Named_type*>::const_iterator q;
8588 for (q = seen.begin(); q != seen.end(); ++q)
8590 if (*q == nt)
8592 go_error_at(tl, "inherited interface loop");
8593 break;
8596 if (q != seen.end())
8597 continue;
8598 seen.push_back(nt);
8601 const Typed_identifier_list* imethods = it->parse_methods_;
8602 if (imethods == NULL)
8603 continue;
8604 for (Typed_identifier_list::const_iterator q = imethods->begin();
8605 q != imethods->end();
8606 ++q)
8608 if (q->name().empty())
8609 inherit.push_back(*q);
8610 else if (this->find_method(q->name()) == NULL)
8611 this->all_methods_->push_back(Typed_identifier(q->name(),
8612 q->type(), tl));
8613 else
8614 go_error_at(tl, "inherited method %qs is ambiguous",
8615 Gogo::message_name(q->name()).c_str());
8619 if (!this->all_methods_->empty())
8620 this->all_methods_->sort_by_name();
8621 else
8623 delete this->all_methods_;
8624 this->all_methods_ = NULL;
8628 // Return the method NAME, or NULL.
8630 const Typed_identifier*
8631 Interface_type::find_method(const std::string& name) const
8633 go_assert(this->methods_are_finalized_);
8634 if (this->all_methods_ == NULL)
8635 return NULL;
8636 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8637 p != this->all_methods_->end();
8638 ++p)
8639 if (p->name() == name)
8640 return &*p;
8641 return NULL;
8644 // Return the method index.
8646 size_t
8647 Interface_type::method_index(const std::string& name) const
8649 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8650 size_t ret = 0;
8651 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8652 p != this->all_methods_->end();
8653 ++p, ++ret)
8654 if (p->name() == name)
8655 return ret;
8656 go_unreachable();
8659 // Return whether NAME is an unexported method, for better error
8660 // reporting.
8662 bool
8663 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8665 go_assert(this->methods_are_finalized_);
8666 if (this->all_methods_ == NULL)
8667 return false;
8668 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8669 p != this->all_methods_->end();
8670 ++p)
8672 const std::string& method_name(p->name());
8673 if (Gogo::is_hidden_name(method_name)
8674 && name == Gogo::unpack_hidden_name(method_name)
8675 && gogo->pack_hidden_name(name, false) != method_name)
8676 return true;
8678 return false;
8681 // Whether this type is identical with T.
8683 bool
8684 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
8685 bool errors_are_identical) const
8687 // If methods have not been finalized, then we are asking whether
8688 // func redeclarations are the same. This is an error, so for
8689 // simplicity we say they are never the same.
8690 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8691 return false;
8693 // We require the same methods with the same types. The methods
8694 // have already been sorted.
8695 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8696 return this->all_methods_ == t->all_methods_;
8698 if (this->assume_identical(this, t) || t->assume_identical(t, this))
8699 return true;
8701 Assume_identical* hold_ai = this->assume_identical_;
8702 Assume_identical ai;
8703 ai.t1 = this;
8704 ai.t2 = t;
8705 ai.next = hold_ai;
8706 this->assume_identical_ = &ai;
8708 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8709 Typed_identifier_list::const_iterator p2;
8710 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8712 if (p1 == this->all_methods_->end())
8713 break;
8714 if (p1->name() != p2->name()
8715 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
8716 errors_are_identical, NULL))
8717 break;
8720 this->assume_identical_ = hold_ai;
8722 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8725 // Return true if T1 and T2 are assumed to be identical during a type
8726 // comparison.
8728 bool
8729 Interface_type::assume_identical(const Interface_type* t1,
8730 const Interface_type* t2) const
8732 for (Assume_identical* p = this->assume_identical_;
8733 p != NULL;
8734 p = p->next)
8735 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8736 return true;
8737 return false;
8740 // Whether we can assign the interface type T to this type. The types
8741 // are known to not be identical. An interface assignment is only
8742 // permitted if T is known to implement all methods in THIS.
8743 // Otherwise a type guard is required.
8745 bool
8746 Interface_type::is_compatible_for_assign(const Interface_type* t,
8747 std::string* reason) const
8749 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8750 if (this->all_methods_ == NULL)
8751 return true;
8752 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8753 p != this->all_methods_->end();
8754 ++p)
8756 const Typed_identifier* m = t->find_method(p->name());
8757 if (m == NULL)
8759 if (reason != NULL)
8761 char buf[200];
8762 snprintf(buf, sizeof buf,
8763 _("need explicit conversion; missing method %s%s%s"),
8764 go_open_quote(), Gogo::message_name(p->name()).c_str(),
8765 go_close_quote());
8766 reason->assign(buf);
8768 return false;
8771 std::string subreason;
8772 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8774 if (reason != NULL)
8776 std::string n = Gogo::message_name(p->name());
8777 size_t len = 100 + n.length() + subreason.length();
8778 char* buf = new char[len];
8779 if (subreason.empty())
8780 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8781 go_open_quote(), n.c_str(), go_close_quote());
8782 else
8783 snprintf(buf, len,
8784 _("incompatible type for method %s%s%s (%s)"),
8785 go_open_quote(), n.c_str(), go_close_quote(),
8786 subreason.c_str());
8787 reason->assign(buf);
8788 delete[] buf;
8790 return false;
8794 return true;
8797 // Hash code.
8799 unsigned int
8800 Interface_type::do_hash_for_method(Gogo*) const
8802 go_assert(this->methods_are_finalized_);
8803 unsigned int ret = 0;
8804 if (this->all_methods_ != NULL)
8806 for (Typed_identifier_list::const_iterator p =
8807 this->all_methods_->begin();
8808 p != this->all_methods_->end();
8809 ++p)
8811 ret = Type::hash_string(p->name(), ret);
8812 // We don't use the method type in the hash, to avoid
8813 // infinite recursion if an interface method uses a type
8814 // which is an interface which inherits from the interface
8815 // itself.
8816 // type T interface { F() interface {T}}
8817 ret <<= 1;
8820 return ret;
8823 // Return true if T implements the interface. If it does not, and
8824 // REASON is not NULL, set *REASON to a useful error message.
8826 bool
8827 Interface_type::implements_interface(const Type* t, std::string* reason) const
8829 go_assert(this->methods_are_finalized_);
8830 if (this->all_methods_ == NULL)
8831 return true;
8833 bool is_pointer = false;
8834 const Named_type* nt = t->named_type();
8835 const Struct_type* st = t->struct_type();
8836 // If we start with a named type, we don't dereference it to find
8837 // methods.
8838 if (nt == NULL)
8840 const Type* pt = t->points_to();
8841 if (pt != NULL)
8843 // If T is a pointer to a named type, then we need to look at
8844 // the type to which it points.
8845 is_pointer = true;
8846 nt = pt->named_type();
8847 st = pt->struct_type();
8851 // If we have a named type, get the methods from it rather than from
8852 // any struct type.
8853 if (nt != NULL)
8854 st = NULL;
8856 // Only named and struct types have methods.
8857 if (nt == NULL && st == NULL)
8859 if (reason != NULL)
8861 if (t->points_to() != NULL
8862 && t->points_to()->interface_type() != NULL)
8863 reason->assign(_("pointer to interface type has no methods"));
8864 else
8865 reason->assign(_("type has no methods"));
8867 return false;
8870 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8872 if (reason != NULL)
8874 if (t->points_to() != NULL
8875 && t->points_to()->interface_type() != NULL)
8876 reason->assign(_("pointer to interface type has no methods"));
8877 else
8878 reason->assign(_("type has no methods"));
8880 return false;
8883 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8884 p != this->all_methods_->end();
8885 ++p)
8887 bool is_ambiguous = false;
8888 Method* m = (nt != NULL
8889 ? nt->method_function(p->name(), &is_ambiguous)
8890 : st->method_function(p->name(), &is_ambiguous));
8891 if (m == NULL)
8893 if (reason != NULL)
8895 std::string n = Gogo::message_name(p->name());
8896 size_t len = n.length() + 100;
8897 char* buf = new char[len];
8898 if (is_ambiguous)
8899 snprintf(buf, len, _("ambiguous method %s%s%s"),
8900 go_open_quote(), n.c_str(), go_close_quote());
8901 else
8902 snprintf(buf, len, _("missing method %s%s%s"),
8903 go_open_quote(), n.c_str(), go_close_quote());
8904 reason->assign(buf);
8905 delete[] buf;
8907 return false;
8910 Function_type *p_fn_type = p->type()->function_type();
8911 Function_type* m_fn_type = m->type()->function_type();
8912 go_assert(p_fn_type != NULL && m_fn_type != NULL);
8913 std::string subreason;
8914 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
8915 &subreason))
8917 if (reason != NULL)
8919 std::string n = Gogo::message_name(p->name());
8920 size_t len = 100 + n.length() + subreason.length();
8921 char* buf = new char[len];
8922 if (subreason.empty())
8923 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8924 go_open_quote(), n.c_str(), go_close_quote());
8925 else
8926 snprintf(buf, len,
8927 _("incompatible type for method %s%s%s (%s)"),
8928 go_open_quote(), n.c_str(), go_close_quote(),
8929 subreason.c_str());
8930 reason->assign(buf);
8931 delete[] buf;
8933 return false;
8936 if (!is_pointer && !m->is_value_method())
8938 if (reason != NULL)
8940 std::string n = Gogo::message_name(p->name());
8941 size_t len = 100 + n.length();
8942 char* buf = new char[len];
8943 snprintf(buf, len,
8944 _("method %s%s%s requires a pointer receiver"),
8945 go_open_quote(), n.c_str(), go_close_quote());
8946 reason->assign(buf);
8947 delete[] buf;
8949 return false;
8952 // If the magic //go:nointerface comment was used, the method
8953 // may not be used to implement interfaces.
8954 if (m->nointerface())
8956 if (reason != NULL)
8958 std::string n = Gogo::message_name(p->name());
8959 size_t len = 100 + n.length();
8960 char* buf = new char[len];
8961 snprintf(buf, len,
8962 _("method %s%s%s is marked go:nointerface"),
8963 go_open_quote(), n.c_str(), go_close_quote());
8964 reason->assign(buf);
8965 delete[] buf;
8967 return false;
8971 return true;
8974 // Return the backend representation of the empty interface type. We
8975 // use the same struct for all empty interfaces.
8977 Btype*
8978 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
8980 static Btype* empty_interface_type;
8981 if (empty_interface_type == NULL)
8983 std::vector<Backend::Btyped_identifier> bfields(2);
8985 Location bloc = Linemap::predeclared_location();
8987 Type* pdt = Type::make_type_descriptor_ptr_type();
8988 bfields[0].name = "__type_descriptor";
8989 bfields[0].btype = pdt->get_backend(gogo);
8990 bfields[0].location = bloc;
8992 Type* vt = Type::make_pointer_type(Type::make_void_type());
8993 bfields[1].name = "__object";
8994 bfields[1].btype = vt->get_backend(gogo);
8995 bfields[1].location = bloc;
8997 empty_interface_type = gogo->backend()->struct_type(bfields);
8999 return empty_interface_type;
9002 // Return a pointer to the backend representation of the method table.
9004 Btype*
9005 Interface_type::get_backend_methods(Gogo* gogo)
9007 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9008 return this->bmethods_;
9010 Location loc = this->location();
9012 std::vector<Backend::Btyped_identifier>
9013 mfields(this->all_methods_->size() + 1);
9015 Type* pdt = Type::make_type_descriptor_ptr_type();
9016 mfields[0].name = "__type_descriptor";
9017 mfields[0].btype = pdt->get_backend(gogo);
9018 mfields[0].location = loc;
9020 std::string last_name = "";
9021 size_t i = 1;
9022 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9023 p != this->all_methods_->end();
9024 ++p, ++i)
9026 // The type of the method in Go only includes the parameters.
9027 // The actual method also has a receiver, which is always a
9028 // pointer. We need to add that pointer type here in order to
9029 // generate the correct type for the backend.
9030 Function_type* ft = p->type()->function_type();
9031 go_assert(ft->receiver() == NULL);
9033 const Typed_identifier_list* params = ft->parameters();
9034 Typed_identifier_list* mparams = new Typed_identifier_list();
9035 if (params != NULL)
9036 mparams->reserve(params->size() + 1);
9037 Type* vt = Type::make_pointer_type(Type::make_void_type());
9038 mparams->push_back(Typed_identifier("", vt, ft->location()));
9039 if (params != NULL)
9041 for (Typed_identifier_list::const_iterator pp = params->begin();
9042 pp != params->end();
9043 ++pp)
9044 mparams->push_back(*pp);
9047 Typed_identifier_list* mresults = (ft->results() == NULL
9048 ? NULL
9049 : ft->results()->copy());
9050 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9051 ft->location());
9053 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9054 mfields[i].btype = mft->get_backend_fntype(gogo);
9055 mfields[i].location = loc;
9057 // Sanity check: the names should be sorted.
9058 go_assert(Gogo::unpack_hidden_name(p->name())
9059 > Gogo::unpack_hidden_name(last_name));
9060 last_name = p->name();
9063 Btype* st = gogo->backend()->struct_type(mfields);
9064 Btype* ret = gogo->backend()->pointer_type(st);
9066 if (this->bmethods_ != NULL && this->bmethods_is_placeholder_)
9067 gogo->backend()->set_placeholder_pointer_type(this->bmethods_, ret);
9068 this->bmethods_ = ret;
9069 this->bmethods_is_placeholder_ = false;
9070 return ret;
9073 // Return a placeholder for the pointer to the backend methods table.
9075 Btype*
9076 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9078 if (this->bmethods_ == NULL)
9080 Location loc = this->location();
9081 this->bmethods_ = gogo->backend()->placeholder_pointer_type("", loc,
9082 false);
9083 this->bmethods_is_placeholder_ = true;
9085 return this->bmethods_;
9088 // Return the fields of a non-empty interface type. This is not
9089 // declared in types.h so that types.h doesn't have to #include
9090 // backend.h.
9092 static void
9093 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9094 bool use_placeholder,
9095 std::vector<Backend::Btyped_identifier>* bfields)
9097 Location loc = type->location();
9099 bfields->resize(2);
9101 (*bfields)[0].name = "__methods";
9102 (*bfields)[0].btype = (use_placeholder
9103 ? type->get_backend_methods_placeholder(gogo)
9104 : type->get_backend_methods(gogo));
9105 (*bfields)[0].location = loc;
9107 Type* vt = Type::make_pointer_type(Type::make_void_type());
9108 (*bfields)[1].name = "__object";
9109 (*bfields)[1].btype = vt->get_backend(gogo);
9110 (*bfields)[1].location = Linemap::predeclared_location();
9113 // Return the backend representation for an interface type. An interface is a
9114 // pointer to a struct. The struct has three fields. The first field is a
9115 // pointer to the type descriptor for the dynamic type of the object.
9116 // The second field is a pointer to a table of methods for the
9117 // interface to be used with the object. The third field is the value
9118 // of the object itself.
9120 Btype*
9121 Interface_type::do_get_backend(Gogo* gogo)
9123 if (this->is_empty())
9124 return Interface_type::get_backend_empty_interface_type(gogo);
9125 else
9127 if (this->interface_btype_ != NULL)
9128 return this->interface_btype_;
9129 this->interface_btype_ =
9130 gogo->backend()->placeholder_struct_type("", this->location_);
9131 std::vector<Backend::Btyped_identifier> bfields;
9132 get_backend_interface_fields(gogo, this, false, &bfields);
9133 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9134 bfields))
9135 this->interface_btype_ = gogo->backend()->error_type();
9136 return this->interface_btype_;
9140 // Finish the backend representation of the methods.
9142 void
9143 Interface_type::finish_backend_methods(Gogo* gogo)
9145 if (!this->is_empty())
9147 const Typed_identifier_list* methods = this->methods();
9148 if (methods != NULL)
9150 for (Typed_identifier_list::const_iterator p = methods->begin();
9151 p != methods->end();
9152 ++p)
9153 p->type()->get_backend(gogo);
9156 // Getting the backend methods now will set the placeholder
9157 // pointer.
9158 this->get_backend_methods(gogo);
9162 // The type of an interface type descriptor.
9164 Type*
9165 Interface_type::make_interface_type_descriptor_type()
9167 static Type* ret;
9168 if (ret == NULL)
9170 Type* tdt = Type::make_type_descriptor_type();
9171 Type* ptdt = Type::make_type_descriptor_ptr_type();
9173 Type* string_type = Type::lookup_string_type();
9174 Type* pointer_string_type = Type::make_pointer_type(string_type);
9176 Struct_type* sm =
9177 Type::make_builtin_struct_type(3,
9178 "name", pointer_string_type,
9179 "pkgPath", pointer_string_type,
9180 "typ", ptdt);
9182 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9184 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9186 Struct_type* s = Type::make_builtin_struct_type(2,
9187 "", tdt,
9188 "methods", slice_nsm);
9190 ret = Type::make_builtin_named_type("InterfaceType", s);
9193 return ret;
9196 // Build a type descriptor for an interface type.
9198 Expression*
9199 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9201 Location bloc = Linemap::predeclared_location();
9203 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9205 const Struct_field_list* ifields = itdt->struct_type()->fields();
9207 Expression_list* ivals = new Expression_list();
9208 ivals->reserve(2);
9210 Struct_field_list::const_iterator pif = ifields->begin();
9211 go_assert(pif->is_field_name("_type"));
9212 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9213 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9214 true));
9216 ++pif;
9217 go_assert(pif->is_field_name("methods"));
9219 Expression_list* methods = new Expression_list();
9220 if (this->all_methods_ != NULL)
9222 Type* elemtype = pif->type()->array_type()->element_type();
9224 methods->reserve(this->all_methods_->size());
9225 for (Typed_identifier_list::const_iterator pm =
9226 this->all_methods_->begin();
9227 pm != this->all_methods_->end();
9228 ++pm)
9230 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9232 Expression_list* mvals = new Expression_list();
9233 mvals->reserve(3);
9235 Struct_field_list::const_iterator pmf = mfields->begin();
9236 go_assert(pmf->is_field_name("name"));
9237 std::string s = Gogo::unpack_hidden_name(pm->name());
9238 Expression* e = Expression::make_string(s, bloc);
9239 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9241 ++pmf;
9242 go_assert(pmf->is_field_name("pkgPath"));
9243 if (!Gogo::is_hidden_name(pm->name()))
9244 mvals->push_back(Expression::make_nil(bloc));
9245 else
9247 s = Gogo::hidden_name_pkgpath(pm->name());
9248 e = Expression::make_string(s, bloc);
9249 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9252 ++pmf;
9253 go_assert(pmf->is_field_name("typ"));
9254 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9256 ++pmf;
9257 go_assert(pmf == mfields->end());
9259 e = Expression::make_struct_composite_literal(elemtype, mvals,
9260 bloc);
9261 methods->push_back(e);
9265 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9266 methods, bloc));
9268 ++pif;
9269 go_assert(pif == ifields->end());
9271 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9274 // Reflection string.
9276 void
9277 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9279 ret->append("interface {");
9280 const Typed_identifier_list* methods = this->parse_methods_;
9281 if (methods != NULL)
9283 ret->push_back(' ');
9284 for (Typed_identifier_list::const_iterator p = methods->begin();
9285 p != methods->end();
9286 ++p)
9288 if (p != methods->begin())
9289 ret->append("; ");
9290 if (p->name().empty())
9291 this->append_reflection(p->type(), gogo, ret);
9292 else
9294 if (!Gogo::is_hidden_name(p->name()))
9295 ret->append(p->name());
9296 else if (gogo->pkgpath_from_option())
9297 ret->append(p->name().substr(1));
9298 else
9300 // If no -fgo-pkgpath option, backward compatibility
9301 // for how this used to work before -fgo-pkgpath was
9302 // introduced.
9303 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9304 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9305 ret->push_back('.');
9306 ret->append(Gogo::unpack_hidden_name(p->name()));
9308 std::string sub = p->type()->reflection(gogo);
9309 go_assert(sub.compare(0, 4, "func") == 0);
9310 sub = sub.substr(4);
9311 ret->append(sub);
9314 ret->push_back(' ');
9316 ret->append("}");
9319 // Export.
9321 void
9322 Interface_type::do_export(Export* exp) const
9324 exp->write_c_string("interface { ");
9326 const Typed_identifier_list* methods = this->parse_methods_;
9327 if (methods != NULL)
9329 for (Typed_identifier_list::const_iterator pm = methods->begin();
9330 pm != methods->end();
9331 ++pm)
9333 if (pm->name().empty())
9335 exp->write_c_string("? ");
9336 exp->write_type(pm->type());
9338 else
9340 exp->write_string(pm->name());
9341 exp->write_c_string(" (");
9343 const Function_type* fntype = pm->type()->function_type();
9345 bool first = true;
9346 const Typed_identifier_list* parameters = fntype->parameters();
9347 if (parameters != NULL)
9349 bool is_varargs = fntype->is_varargs();
9350 for (Typed_identifier_list::const_iterator pp =
9351 parameters->begin();
9352 pp != parameters->end();
9353 ++pp)
9355 if (first)
9356 first = false;
9357 else
9358 exp->write_c_string(", ");
9359 exp->write_name(pp->name());
9360 exp->write_c_string(" ");
9361 if (!is_varargs || pp + 1 != parameters->end())
9362 exp->write_type(pp->type());
9363 else
9365 exp->write_c_string("...");
9366 Type *pptype = pp->type();
9367 exp->write_type(pptype->array_type()->element_type());
9372 exp->write_c_string(")");
9374 const Typed_identifier_list* results = fntype->results();
9375 if (results != NULL)
9377 exp->write_c_string(" ");
9378 if (results->size() == 1 && results->begin()->name().empty())
9379 exp->write_type(results->begin()->type());
9380 else
9382 first = true;
9383 exp->write_c_string("(");
9384 for (Typed_identifier_list::const_iterator p =
9385 results->begin();
9386 p != results->end();
9387 ++p)
9389 if (first)
9390 first = false;
9391 else
9392 exp->write_c_string(", ");
9393 exp->write_name(p->name());
9394 exp->write_c_string(" ");
9395 exp->write_type(p->type());
9397 exp->write_c_string(")");
9402 exp->write_c_string("; ");
9406 exp->write_c_string("}");
9409 // Import an interface type.
9411 Interface_type*
9412 Interface_type::do_import(Import* imp)
9414 imp->require_c_string("interface { ");
9416 Typed_identifier_list* methods = new Typed_identifier_list;
9417 while (imp->peek_char() != '}')
9419 std::string name = imp->read_identifier();
9421 if (name == "?")
9423 imp->require_c_string(" ");
9424 Type* t = imp->read_type();
9425 methods->push_back(Typed_identifier("", t, imp->location()));
9426 imp->require_c_string("; ");
9427 continue;
9430 imp->require_c_string(" (");
9432 Typed_identifier_list* parameters;
9433 bool is_varargs = false;
9434 if (imp->peek_char() == ')')
9435 parameters = NULL;
9436 else
9438 parameters = new Typed_identifier_list;
9439 while (true)
9441 std::string name = imp->read_name();
9442 imp->require_c_string(" ");
9444 if (imp->match_c_string("..."))
9446 imp->advance(3);
9447 is_varargs = true;
9450 Type* ptype = imp->read_type();
9451 if (is_varargs)
9452 ptype = Type::make_array_type(ptype, NULL);
9453 parameters->push_back(Typed_identifier(name, ptype,
9454 imp->location()));
9455 if (imp->peek_char() != ',')
9456 break;
9457 go_assert(!is_varargs);
9458 imp->require_c_string(", ");
9461 imp->require_c_string(")");
9463 Typed_identifier_list* results;
9464 if (imp->peek_char() != ' ')
9465 results = NULL;
9466 else
9468 results = new Typed_identifier_list;
9469 imp->advance(1);
9470 if (imp->peek_char() != '(')
9472 Type* rtype = imp->read_type();
9473 results->push_back(Typed_identifier("", rtype, imp->location()));
9475 else
9477 imp->advance(1);
9478 while (true)
9480 std::string name = imp->read_name();
9481 imp->require_c_string(" ");
9482 Type* rtype = imp->read_type();
9483 results->push_back(Typed_identifier(name, rtype,
9484 imp->location()));
9485 if (imp->peek_char() != ',')
9486 break;
9487 imp->require_c_string(", ");
9489 imp->require_c_string(")");
9493 Function_type* fntype = Type::make_function_type(NULL, parameters,
9494 results,
9495 imp->location());
9496 if (is_varargs)
9497 fntype->set_is_varargs();
9498 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9500 imp->require_c_string("; ");
9503 imp->require_c_string("}");
9505 if (methods->empty())
9507 delete methods;
9508 methods = NULL;
9511 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9512 ret->package_ = imp->package();
9513 return ret;
9516 // Make an interface type.
9518 Interface_type*
9519 Type::make_interface_type(Typed_identifier_list* methods,
9520 Location location)
9522 return new Interface_type(methods, location);
9525 // Make an empty interface type.
9527 Interface_type*
9528 Type::make_empty_interface_type(Location location)
9530 Interface_type* ret = new Interface_type(NULL, location);
9531 ret->finalize_methods();
9532 return ret;
9535 // Class Method.
9537 // Bind a method to an object.
9539 Expression*
9540 Method::bind_method(Expression* expr, Location location) const
9542 if (this->stub_ == NULL)
9544 // When there is no stub object, the binding is determined by
9545 // the child class.
9546 return this->do_bind_method(expr, location);
9548 return Expression::make_bound_method(expr, this, this->stub_, location);
9551 // Return the named object associated with a method. This may only be
9552 // called after methods are finalized.
9554 Named_object*
9555 Method::named_object() const
9557 if (this->stub_ != NULL)
9558 return this->stub_;
9559 return this->do_named_object();
9562 // Class Named_method.
9564 // The type of the method.
9566 Function_type*
9567 Named_method::do_type() const
9569 if (this->named_object_->is_function())
9570 return this->named_object_->func_value()->type();
9571 else if (this->named_object_->is_function_declaration())
9572 return this->named_object_->func_declaration_value()->type();
9573 else
9574 go_unreachable();
9577 // Return the location of the method receiver.
9579 Location
9580 Named_method::do_receiver_location() const
9582 return this->do_type()->receiver()->location();
9585 // Bind a method to an object.
9587 Expression*
9588 Named_method::do_bind_method(Expression* expr, Location location) const
9590 Named_object* no = this->named_object_;
9591 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9592 no, location);
9593 // If this is not a local method, and it does not use a stub, then
9594 // the real method expects a different type. We need to cast the
9595 // first argument.
9596 if (this->depth() > 0 && !this->needs_stub_method())
9598 Function_type* ftype = this->do_type();
9599 go_assert(ftype->is_method());
9600 Type* frtype = ftype->receiver()->type();
9601 bme->set_first_argument_type(frtype);
9603 return bme;
9606 // Return whether this method should not participate in interfaces.
9608 bool
9609 Named_method::do_nointerface() const
9611 Named_object* no = this->named_object_;
9612 return no->is_function() && no->func_value()->nointerface();
9615 // Class Interface_method.
9617 // Bind a method to an object.
9619 Expression*
9620 Interface_method::do_bind_method(Expression* expr,
9621 Location location) const
9623 return Expression::make_interface_field_reference(expr, this->name_,
9624 location);
9627 // Class Methods.
9629 // Insert a new method. Return true if it was inserted, false
9630 // otherwise.
9632 bool
9633 Methods::insert(const std::string& name, Method* m)
9635 std::pair<Method_map::iterator, bool> ins =
9636 this->methods_.insert(std::make_pair(name, m));
9637 if (ins.second)
9638 return true;
9639 else
9641 Method* old_method = ins.first->second;
9642 if (m->depth() < old_method->depth())
9644 delete old_method;
9645 ins.first->second = m;
9646 return true;
9648 else
9650 if (m->depth() == old_method->depth())
9651 old_method->set_is_ambiguous();
9652 return false;
9657 // Return the number of unambiguous methods.
9659 size_t
9660 Methods::count() const
9662 size_t ret = 0;
9663 for (Method_map::const_iterator p = this->methods_.begin();
9664 p != this->methods_.end();
9665 ++p)
9666 if (!p->second->is_ambiguous())
9667 ++ret;
9668 return ret;
9671 // Class Named_type.
9673 // Return the name of the type.
9675 const std::string&
9676 Named_type::name() const
9678 return this->named_object_->name();
9681 // Return the name of the type to use in an error message.
9683 std::string
9684 Named_type::message_name() const
9686 return this->named_object_->message_name();
9689 // Return the base type for this type. We have to be careful about
9690 // circular type definitions, which are invalid but may be seen here.
9692 Type*
9693 Named_type::named_base()
9695 if (this->seen_)
9696 return this;
9697 this->seen_ = true;
9698 Type* ret = this->type_->base();
9699 this->seen_ = false;
9700 return ret;
9703 const Type*
9704 Named_type::named_base() const
9706 if (this->seen_)
9707 return this;
9708 this->seen_ = true;
9709 const Type* ret = this->type_->base();
9710 this->seen_ = false;
9711 return ret;
9714 // Return whether this is an error type. We have to be careful about
9715 // circular type definitions, which are invalid but may be seen here.
9717 bool
9718 Named_type::is_named_error_type() const
9720 if (this->seen_)
9721 return false;
9722 this->seen_ = true;
9723 bool ret = this->type_->is_error_type();
9724 this->seen_ = false;
9725 return ret;
9728 // Whether this type is comparable. We have to be careful about
9729 // circular type definitions.
9731 bool
9732 Named_type::named_type_is_comparable(std::string* reason) const
9734 if (this->seen_)
9735 return false;
9736 this->seen_ = true;
9737 bool ret = Type::are_compatible_for_comparison(true, this->type_,
9738 this->type_, reason);
9739 this->seen_ = false;
9740 return ret;
9743 // Add a method to this type.
9745 Named_object*
9746 Named_type::add_method(const std::string& name, Function* function)
9748 go_assert(!this->is_alias_);
9749 if (this->local_methods_ == NULL)
9750 this->local_methods_ = new Bindings(NULL);
9751 return this->local_methods_->add_function(name, NULL, function);
9754 // Add a method declaration to this type.
9756 Named_object*
9757 Named_type::add_method_declaration(const std::string& name, Package* package,
9758 Function_type* type,
9759 Location location)
9761 go_assert(!this->is_alias_);
9762 if (this->local_methods_ == NULL)
9763 this->local_methods_ = new Bindings(NULL);
9764 return this->local_methods_->add_function_declaration(name, package, type,
9765 location);
9768 // Add an existing method to this type.
9770 void
9771 Named_type::add_existing_method(Named_object* no)
9773 go_assert(!this->is_alias_);
9774 if (this->local_methods_ == NULL)
9775 this->local_methods_ = new Bindings(NULL);
9776 this->local_methods_->add_named_object(no);
9779 // Look for a local method NAME, and returns its named object, or NULL
9780 // if not there.
9782 Named_object*
9783 Named_type::find_local_method(const std::string& name) const
9785 if (this->is_error_)
9786 return NULL;
9787 if (this->is_alias_)
9789 Named_type* nt = this->type_->named_type();
9790 if (nt != NULL)
9792 if (this->seen_alias_)
9793 return NULL;
9794 this->seen_alias_ = true;
9795 Named_object* ret = nt->find_local_method(name);
9796 this->seen_alias_ = false;
9797 return ret;
9799 return NULL;
9801 if (this->local_methods_ == NULL)
9802 return NULL;
9803 return this->local_methods_->lookup(name);
9806 // Return the list of local methods.
9808 const Bindings*
9809 Named_type::local_methods() const
9811 if (this->is_error_)
9812 return NULL;
9813 if (this->is_alias_)
9815 Named_type* nt = this->type_->named_type();
9816 if (nt != NULL)
9818 if (this->seen_alias_)
9819 return NULL;
9820 this->seen_alias_ = true;
9821 const Bindings* ret = nt->local_methods();
9822 this->seen_alias_ = false;
9823 return ret;
9825 return NULL;
9827 return this->local_methods_;
9830 // Return whether NAME is an unexported field or method, for better
9831 // error reporting.
9833 bool
9834 Named_type::is_unexported_local_method(Gogo* gogo,
9835 const std::string& name) const
9837 if (this->is_error_)
9838 return false;
9839 if (this->is_alias_)
9841 Named_type* nt = this->type_->named_type();
9842 if (nt != NULL)
9844 if (this->seen_alias_)
9845 return false;
9846 this->seen_alias_ = true;
9847 bool ret = nt->is_unexported_local_method(gogo, name);
9848 this->seen_alias_ = false;
9849 return ret;
9851 return false;
9853 Bindings* methods = this->local_methods_;
9854 if (methods != NULL)
9856 for (Bindings::const_declarations_iterator p =
9857 methods->begin_declarations();
9858 p != methods->end_declarations();
9859 ++p)
9861 if (Gogo::is_hidden_name(p->first)
9862 && name == Gogo::unpack_hidden_name(p->first)
9863 && gogo->pack_hidden_name(name, false) != p->first)
9864 return true;
9867 return false;
9870 // Build the complete list of methods for this type, which means
9871 // recursively including all methods for anonymous fields. Create all
9872 // stub methods.
9874 void
9875 Named_type::finalize_methods(Gogo* gogo)
9877 if (this->is_alias_)
9878 return;
9879 if (this->all_methods_ != NULL)
9880 return;
9882 if (this->local_methods_ != NULL
9883 && (this->points_to() != NULL || this->interface_type() != NULL))
9885 const Bindings* lm = this->local_methods_;
9886 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
9887 p != lm->end_declarations();
9888 ++p)
9889 go_error_at(p->second->location(),
9890 "invalid pointer or interface receiver type");
9891 delete this->local_methods_;
9892 this->local_methods_ = NULL;
9893 return;
9896 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
9899 // Return whether this type has any methods.
9901 bool
9902 Named_type::has_any_methods() const
9904 if (this->is_error_)
9905 return false;
9906 if (this->is_alias_)
9908 if (this->type_->named_type() != NULL)
9910 if (this->seen_alias_)
9911 return false;
9912 this->seen_alias_ = true;
9913 bool ret = this->type_->named_type()->has_any_methods();
9914 this->seen_alias_ = false;
9915 return ret;
9917 if (this->type_->struct_type() != NULL)
9918 return this->type_->struct_type()->has_any_methods();
9919 return false;
9921 return this->all_methods_ != NULL;
9924 // Return the methods for this type.
9926 const Methods*
9927 Named_type::methods() const
9929 if (this->is_error_)
9930 return NULL;
9931 if (this->is_alias_)
9933 if (this->type_->named_type() != NULL)
9935 if (this->seen_alias_)
9936 return NULL;
9937 this->seen_alias_ = true;
9938 const Methods* ret = this->type_->named_type()->methods();
9939 this->seen_alias_ = false;
9940 return ret;
9942 if (this->type_->struct_type() != NULL)
9943 return this->type_->struct_type()->methods();
9944 return NULL;
9946 return this->all_methods_;
9949 // Return the method NAME, or NULL if there isn't one or if it is
9950 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
9951 // ambiguous.
9953 Method*
9954 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
9956 if (this->is_error_)
9957 return NULL;
9958 if (this->is_alias_)
9960 if (is_ambiguous != NULL)
9961 *is_ambiguous = false;
9962 if (this->type_->named_type() != NULL)
9964 if (this->seen_alias_)
9965 return NULL;
9966 this->seen_alias_ = true;
9967 Named_type* nt = this->type_->named_type();
9968 Method* ret = nt->method_function(name, is_ambiguous);
9969 this->seen_alias_ = false;
9970 return ret;
9972 if (this->type_->struct_type() != NULL)
9973 return this->type_->struct_type()->method_function(name, is_ambiguous);
9974 return NULL;
9976 return Type::method_function(this->all_methods_, name, is_ambiguous);
9979 // Return a pointer to the interface method table for this type for
9980 // the interface INTERFACE. IS_POINTER is true if this is for a
9981 // pointer to THIS.
9983 Expression*
9984 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
9986 if (this->is_error_)
9987 return Expression::make_error(this->location_);
9988 if (this->is_alias_)
9990 if (this->type_->named_type() != NULL)
9992 if (this->seen_alias_)
9993 return Expression::make_error(this->location_);
9994 this->seen_alias_ = true;
9995 Named_type* nt = this->type_->named_type();
9996 Expression* ret = nt->interface_method_table(interface, is_pointer);
9997 this->seen_alias_ = false;
9998 return ret;
10000 if (this->type_->struct_type() != NULL)
10001 return this->type_->struct_type()->interface_method_table(interface,
10002 is_pointer);
10003 go_unreachable();
10005 return Type::interface_method_table(this, interface, is_pointer,
10006 &this->interface_method_tables_,
10007 &this->pointer_interface_method_tables_);
10010 // Look for a use of a complete type within another type. This is
10011 // used to check that we don't try to use a type within itself.
10013 class Find_type_use : public Traverse
10015 public:
10016 Find_type_use(Named_type* find_type)
10017 : Traverse(traverse_types),
10018 find_type_(find_type), found_(false)
10021 // Whether we found the type.
10022 bool
10023 found() const
10024 { return this->found_; }
10026 protected:
10028 type(Type*);
10030 private:
10031 // The type we are looking for.
10032 Named_type* find_type_;
10033 // Whether we found the type.
10034 bool found_;
10037 // Check for FIND_TYPE in TYPE.
10040 Find_type_use::type(Type* type)
10042 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10044 this->found_ = true;
10045 return TRAVERSE_EXIT;
10048 // It's OK if we see a reference to the type in any type which is
10049 // essentially a pointer: a pointer, a slice, a function, a map, or
10050 // a channel.
10051 if (type->points_to() != NULL
10052 || type->is_slice_type()
10053 || type->function_type() != NULL
10054 || type->map_type() != NULL
10055 || type->channel_type() != NULL)
10056 return TRAVERSE_SKIP_COMPONENTS;
10058 // For an interface, a reference to the type in a method type should
10059 // be ignored, but we have to consider direct inheritance. When
10060 // this is called, there may be cases of direct inheritance
10061 // represented as a method with no name.
10062 if (type->interface_type() != NULL)
10064 const Typed_identifier_list* methods = type->interface_type()->methods();
10065 if (methods != NULL)
10067 for (Typed_identifier_list::const_iterator p = methods->begin();
10068 p != methods->end();
10069 ++p)
10071 if (p->name().empty())
10073 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10074 return TRAVERSE_EXIT;
10078 return TRAVERSE_SKIP_COMPONENTS;
10081 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10082 // to convert TYPE to the backend representation before we convert
10083 // FIND_TYPE_.
10084 if (type->named_type() != NULL)
10086 switch (type->base()->classification())
10088 case Type::TYPE_ERROR:
10089 case Type::TYPE_BOOLEAN:
10090 case Type::TYPE_INTEGER:
10091 case Type::TYPE_FLOAT:
10092 case Type::TYPE_COMPLEX:
10093 case Type::TYPE_STRING:
10094 case Type::TYPE_NIL:
10095 break;
10097 case Type::TYPE_ARRAY:
10098 case Type::TYPE_STRUCT:
10099 this->find_type_->add_dependency(type->named_type());
10100 break;
10102 case Type::TYPE_NAMED:
10103 case Type::TYPE_FORWARD:
10104 go_assert(saw_errors());
10105 break;
10107 case Type::TYPE_VOID:
10108 case Type::TYPE_SINK:
10109 case Type::TYPE_FUNCTION:
10110 case Type::TYPE_POINTER:
10111 case Type::TYPE_CALL_MULTIPLE_RESULT:
10112 case Type::TYPE_MAP:
10113 case Type::TYPE_CHANNEL:
10114 case Type::TYPE_INTERFACE:
10115 default:
10116 go_unreachable();
10120 return TRAVERSE_CONTINUE;
10123 // Look for a circular reference of an alias.
10125 class Find_alias : public Traverse
10127 public:
10128 Find_alias(Named_type* find_type)
10129 : Traverse(traverse_types),
10130 find_type_(find_type), found_(false)
10133 // Whether we found the type.
10134 bool
10135 found() const
10136 { return this->found_; }
10138 protected:
10140 type(Type*);
10142 private:
10143 // The type we are looking for.
10144 Named_type* find_type_;
10145 // Whether we found the type.
10146 bool found_;
10150 Find_alias::type(Type* type)
10152 Named_type* nt = type->named_type();
10153 if (nt != NULL)
10155 if (nt == this->find_type_)
10157 this->found_ = true;
10158 return TRAVERSE_EXIT;
10161 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10162 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10163 // an alias itself, it's OK if whatever T2 is defined as refers
10164 // to T1.
10165 if (!nt->is_alias())
10166 return TRAVERSE_SKIP_COMPONENTS;
10169 return TRAVERSE_CONTINUE;
10172 // Verify that a named type does not refer to itself.
10174 bool
10175 Named_type::do_verify()
10177 if (this->is_verified_)
10178 return true;
10179 this->is_verified_ = true;
10181 if (this->is_error_)
10182 return false;
10184 if (this->is_alias_)
10186 Find_alias find(this);
10187 Type::traverse(this->type_, &find);
10188 if (find.found())
10190 go_error_at(this->location_, "invalid recursive alias %qs",
10191 this->message_name().c_str());
10192 this->is_error_ = true;
10193 return false;
10197 Find_type_use find(this);
10198 Type::traverse(this->type_, &find);
10199 if (find.found())
10201 go_error_at(this->location_, "invalid recursive type %qs",
10202 this->message_name().c_str());
10203 this->is_error_ = true;
10204 return false;
10207 // Check whether any of the local methods overloads an existing
10208 // struct field or interface method. We don't need to check the
10209 // list of methods against itself: that is handled by the Bindings
10210 // code.
10211 if (this->local_methods_ != NULL)
10213 Struct_type* st = this->type_->struct_type();
10214 if (st != NULL)
10216 for (Bindings::const_declarations_iterator p =
10217 this->local_methods_->begin_declarations();
10218 p != this->local_methods_->end_declarations();
10219 ++p)
10221 const std::string& name(p->first);
10222 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10224 go_error_at(p->second->location(),
10225 "method %qs redeclares struct field name",
10226 Gogo::message_name(name).c_str());
10232 return true;
10235 // Return whether this type is or contains a pointer.
10237 bool
10238 Named_type::do_has_pointer() const
10240 if (this->seen_)
10241 return false;
10242 this->seen_ = true;
10243 bool ret = this->type_->has_pointer();
10244 this->seen_ = false;
10245 return ret;
10248 // Return whether comparisons for this type can use the identity
10249 // function.
10251 bool
10252 Named_type::do_compare_is_identity(Gogo* gogo)
10254 // We don't use this->seen_ here because compare_is_identity may
10255 // call base() later, and that will mess up if seen_ is set here.
10256 if (this->seen_in_compare_is_identity_)
10257 return false;
10258 this->seen_in_compare_is_identity_ = true;
10259 bool ret = this->type_->compare_is_identity(gogo);
10260 this->seen_in_compare_is_identity_ = false;
10261 return ret;
10264 // Return whether this type is reflexive--whether it is always equal
10265 // to itself.
10267 bool
10268 Named_type::do_is_reflexive()
10270 if (this->seen_in_compare_is_identity_)
10271 return false;
10272 this->seen_in_compare_is_identity_ = true;
10273 bool ret = this->type_->is_reflexive();
10274 this->seen_in_compare_is_identity_ = false;
10275 return ret;
10278 // Return whether this type needs a key update when used as a map key.
10280 bool
10281 Named_type::do_needs_key_update()
10283 if (this->seen_in_compare_is_identity_)
10284 return true;
10285 this->seen_in_compare_is_identity_ = true;
10286 bool ret = this->type_->needs_key_update();
10287 this->seen_in_compare_is_identity_ = false;
10288 return ret;
10291 // Return a hash code. This is used for method lookup. We simply
10292 // hash on the name itself.
10294 unsigned int
10295 Named_type::do_hash_for_method(Gogo* gogo) const
10297 if (this->is_error_)
10298 return 0;
10300 // Aliases are handled in Type::hash_for_method.
10301 go_assert(!this->is_alias_);
10303 const std::string& name(this->named_object()->name());
10304 unsigned int ret = Type::hash_string(name, 0);
10306 // GOGO will be NULL here when called from Type_hash_identical.
10307 // That is OK because that is only used for internal hash tables
10308 // where we are going to be comparing named types for equality. In
10309 // other cases, which are cases where the runtime is going to
10310 // compare hash codes to see if the types are the same, we need to
10311 // include the pkgpath in the hash.
10312 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10314 const Package* package = this->named_object()->package();
10315 if (package == NULL)
10316 ret = Type::hash_string(gogo->pkgpath(), ret);
10317 else
10318 ret = Type::hash_string(package->pkgpath(), ret);
10321 return ret;
10324 // Convert a named type to the backend representation. In order to
10325 // get dependencies right, we fill in a dummy structure for this type,
10326 // then convert all the dependencies, then complete this type. When
10327 // this function is complete, the size of the type is known.
10329 void
10330 Named_type::convert(Gogo* gogo)
10332 if (this->is_error_ || this->is_converted_)
10333 return;
10335 this->create_placeholder(gogo);
10337 // If we are called to turn unsafe.Sizeof into a constant, we may
10338 // not have verified the type yet. We have to make sure it is
10339 // verified, since that sets the list of dependencies.
10340 this->verify();
10342 // Convert all the dependencies. If they refer indirectly back to
10343 // this type, they will pick up the intermediate representation we just
10344 // created.
10345 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10346 p != this->dependencies_.end();
10347 ++p)
10348 (*p)->convert(gogo);
10350 // Complete this type.
10351 Btype* bt = this->named_btype_;
10352 Type* base = this->type_->base();
10353 switch (base->classification())
10355 case TYPE_VOID:
10356 case TYPE_BOOLEAN:
10357 case TYPE_INTEGER:
10358 case TYPE_FLOAT:
10359 case TYPE_COMPLEX:
10360 case TYPE_STRING:
10361 case TYPE_NIL:
10362 break;
10364 case TYPE_MAP:
10365 case TYPE_CHANNEL:
10366 break;
10368 case TYPE_FUNCTION:
10369 case TYPE_POINTER:
10370 // The size of these types is already correct. We don't worry
10371 // about filling them in until later, when we also track
10372 // circular references.
10373 break;
10375 case TYPE_STRUCT:
10377 std::vector<Backend::Btyped_identifier> bfields;
10378 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10379 true, &bfields);
10380 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10381 bt = gogo->backend()->error_type();
10383 break;
10385 case TYPE_ARRAY:
10386 // Slice types were completed in create_placeholder.
10387 if (!base->is_slice_type())
10389 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10390 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10391 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10392 bt = gogo->backend()->error_type();
10394 break;
10396 case TYPE_INTERFACE:
10397 // Interface types were completed in create_placeholder.
10398 break;
10400 case TYPE_ERROR:
10401 return;
10403 default:
10404 case TYPE_SINK:
10405 case TYPE_CALL_MULTIPLE_RESULT:
10406 case TYPE_NAMED:
10407 case TYPE_FORWARD:
10408 go_unreachable();
10411 this->named_btype_ = bt;
10412 this->is_converted_ = true;
10413 this->is_placeholder_ = false;
10416 // Create the placeholder for a named type. This is the first step in
10417 // converting to the backend representation.
10419 void
10420 Named_type::create_placeholder(Gogo* gogo)
10422 if (this->is_error_)
10423 this->named_btype_ = gogo->backend()->error_type();
10425 if (this->named_btype_ != NULL)
10426 return;
10428 // Create the structure for this type. Note that because we call
10429 // base() here, we don't attempt to represent a named type defined
10430 // as another named type. Instead both named types will point to
10431 // different base representations.
10432 Type* base = this->type_->base();
10433 Btype* bt;
10434 bool set_name = true;
10435 switch (base->classification())
10437 case TYPE_ERROR:
10438 this->is_error_ = true;
10439 this->named_btype_ = gogo->backend()->error_type();
10440 return;
10442 case TYPE_VOID:
10443 case TYPE_BOOLEAN:
10444 case TYPE_INTEGER:
10445 case TYPE_FLOAT:
10446 case TYPE_COMPLEX:
10447 case TYPE_STRING:
10448 case TYPE_NIL:
10449 // These are simple basic types, we can just create them
10450 // directly.
10451 bt = Type::get_named_base_btype(gogo, base);
10452 break;
10454 case TYPE_MAP:
10455 case TYPE_CHANNEL:
10456 // All maps and channels have the same backend representation.
10457 bt = Type::get_named_base_btype(gogo, base);
10458 break;
10460 case TYPE_FUNCTION:
10461 case TYPE_POINTER:
10463 bool for_function = base->classification() == TYPE_FUNCTION;
10464 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10465 this->location_,
10466 for_function);
10467 set_name = false;
10469 break;
10471 case TYPE_STRUCT:
10472 bt = gogo->backend()->placeholder_struct_type(this->name(),
10473 this->location_);
10474 this->is_placeholder_ = true;
10475 set_name = false;
10476 break;
10478 case TYPE_ARRAY:
10479 if (base->is_slice_type())
10480 bt = gogo->backend()->placeholder_struct_type(this->name(),
10481 this->location_);
10482 else
10484 bt = gogo->backend()->placeholder_array_type(this->name(),
10485 this->location_);
10486 this->is_placeholder_ = true;
10488 set_name = false;
10489 break;
10491 case TYPE_INTERFACE:
10492 if (base->interface_type()->is_empty())
10493 bt = Interface_type::get_backend_empty_interface_type(gogo);
10494 else
10496 bt = gogo->backend()->placeholder_struct_type(this->name(),
10497 this->location_);
10498 set_name = false;
10500 break;
10502 default:
10503 case TYPE_SINK:
10504 case TYPE_CALL_MULTIPLE_RESULT:
10505 case TYPE_NAMED:
10506 case TYPE_FORWARD:
10507 go_unreachable();
10510 if (set_name)
10511 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10513 this->named_btype_ = bt;
10515 if (base->is_slice_type())
10517 // We do not record slices as dependencies of other types,
10518 // because we can fill them in completely here with the final
10519 // size.
10520 std::vector<Backend::Btyped_identifier> bfields;
10521 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10522 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10523 this->named_btype_ = gogo->backend()->error_type();
10525 else if (base->interface_type() != NULL
10526 && !base->interface_type()->is_empty())
10528 // We do not record interfaces as dependencies of other types,
10529 // because we can fill them in completely here with the final
10530 // size.
10531 std::vector<Backend::Btyped_identifier> bfields;
10532 get_backend_interface_fields(gogo, base->interface_type(), true,
10533 &bfields);
10534 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10535 this->named_btype_ = gogo->backend()->error_type();
10539 // Get the backend representation for a named type.
10541 Btype*
10542 Named_type::do_get_backend(Gogo* gogo)
10544 if (this->is_error_)
10545 return gogo->backend()->error_type();
10547 Btype* bt = this->named_btype_;
10549 if (!gogo->named_types_are_converted())
10551 // We have not completed converting named types. NAMED_BTYPE_
10552 // is a placeholder and we shouldn't do anything further.
10553 if (bt != NULL)
10554 return bt;
10556 // We don't build dependencies for types whose sizes do not
10557 // change or are not relevant, so we may see them here while
10558 // converting types.
10559 this->create_placeholder(gogo);
10560 bt = this->named_btype_;
10561 go_assert(bt != NULL);
10562 return bt;
10565 // We are not converting types. This should only be called if the
10566 // type has already been converted.
10567 if (!this->is_converted_)
10569 go_assert(saw_errors());
10570 return gogo->backend()->error_type();
10573 go_assert(bt != NULL);
10575 // Complete the backend representation.
10576 Type* base = this->type_->base();
10577 Btype* bt1;
10578 switch (base->classification())
10580 case TYPE_ERROR:
10581 return gogo->backend()->error_type();
10583 case TYPE_VOID:
10584 case TYPE_BOOLEAN:
10585 case TYPE_INTEGER:
10586 case TYPE_FLOAT:
10587 case TYPE_COMPLEX:
10588 case TYPE_STRING:
10589 case TYPE_NIL:
10590 case TYPE_MAP:
10591 case TYPE_CHANNEL:
10592 return bt;
10594 case TYPE_STRUCT:
10595 if (!this->seen_in_get_backend_)
10597 this->seen_in_get_backend_ = true;
10598 base->struct_type()->finish_backend_fields(gogo);
10599 this->seen_in_get_backend_ = false;
10601 return bt;
10603 case TYPE_ARRAY:
10604 if (!this->seen_in_get_backend_)
10606 this->seen_in_get_backend_ = true;
10607 base->array_type()->finish_backend_element(gogo);
10608 this->seen_in_get_backend_ = false;
10610 return bt;
10612 case TYPE_INTERFACE:
10613 if (!this->seen_in_get_backend_)
10615 this->seen_in_get_backend_ = true;
10616 base->interface_type()->finish_backend_methods(gogo);
10617 this->seen_in_get_backend_ = false;
10619 return bt;
10621 case TYPE_FUNCTION:
10622 // Don't build a circular data structure. GENERIC can't handle
10623 // it.
10624 if (this->seen_in_get_backend_)
10626 this->is_circular_ = true;
10627 return gogo->backend()->circular_pointer_type(bt, true);
10629 this->seen_in_get_backend_ = true;
10630 bt1 = Type::get_named_base_btype(gogo, base);
10631 this->seen_in_get_backend_ = false;
10632 if (this->is_circular_)
10633 bt1 = gogo->backend()->circular_pointer_type(bt, true);
10634 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10635 bt = gogo->backend()->error_type();
10636 return bt;
10638 case TYPE_POINTER:
10639 // Don't build a circular data structure. GENERIC can't handle
10640 // it.
10641 if (this->seen_in_get_backend_)
10643 this->is_circular_ = true;
10644 return gogo->backend()->circular_pointer_type(bt, false);
10646 this->seen_in_get_backend_ = true;
10647 bt1 = Type::get_named_base_btype(gogo, base);
10648 this->seen_in_get_backend_ = false;
10649 if (this->is_circular_)
10650 bt1 = gogo->backend()->circular_pointer_type(bt, false);
10651 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10652 bt = gogo->backend()->error_type();
10653 return bt;
10655 default:
10656 case TYPE_SINK:
10657 case TYPE_CALL_MULTIPLE_RESULT:
10658 case TYPE_NAMED:
10659 case TYPE_FORWARD:
10660 go_unreachable();
10663 go_unreachable();
10666 // Build a type descriptor for a named type.
10668 Expression*
10669 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10671 if (this->is_error_)
10672 return Expression::make_error(this->location_);
10673 if (name == NULL && this->is_alias_)
10675 if (this->seen_alias_)
10676 return Expression::make_error(this->location_);
10677 this->seen_alias_ = true;
10678 Expression* ret = this->type_->type_descriptor(gogo, NULL);
10679 this->seen_alias_ = false;
10680 return ret;
10683 // If NAME is not NULL, then we don't really want the type
10684 // descriptor for this type; we want the descriptor for the
10685 // underlying type, giving it the name NAME.
10686 return this->named_type_descriptor(gogo, this->type_,
10687 name == NULL ? this : name);
10690 // Add to the reflection string. This is used mostly for the name of
10691 // the type used in a type descriptor, not for actual reflection
10692 // strings.
10694 void
10695 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10697 this->append_reflection_type_name(gogo, false, ret);
10700 // Add to the reflection string. For an alias we normally use the
10701 // real name, but if USE_ALIAS is true we use the alias name itself.
10703 void
10704 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10705 std::string* ret) const
10707 if (this->is_error_)
10708 return;
10709 if (this->is_alias_ && !use_alias)
10711 if (this->seen_alias_)
10712 return;
10713 this->seen_alias_ = true;
10714 this->append_reflection(this->type_, gogo, ret);
10715 this->seen_alias_ = false;
10716 return;
10718 if (!this->is_builtin())
10720 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10721 // make a unique reflection string, so that the type
10722 // canonicalization in the reflect package will work. In order
10723 // to be compatible with the gc compiler, we put tabs into the
10724 // package path, so that the reflect methods can discard it.
10725 const Package* package = this->named_object_->package();
10726 ret->push_back('\t');
10727 ret->append(package != NULL
10728 ? package->pkgpath_symbol()
10729 : gogo->pkgpath_symbol());
10730 ret->push_back('\t');
10731 ret->append(package != NULL
10732 ? package->package_name()
10733 : gogo->package_name());
10734 ret->push_back('.');
10736 if (this->in_function_ != NULL)
10738 ret->push_back('\t');
10739 const Typed_identifier* rcvr =
10740 this->in_function_->func_value()->type()->receiver();
10741 if (rcvr != NULL)
10743 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10744 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10745 ret->push_back('.');
10747 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10748 ret->push_back('$');
10749 if (this->in_function_index_ > 0)
10751 char buf[30];
10752 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10753 ret->append(buf);
10754 ret->push_back('$');
10756 ret->push_back('\t');
10758 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10761 // Export the type. This is called to export a global type.
10763 void
10764 Named_type::export_named_type(Export* exp, const std::string&) const
10766 // We don't need to write the name of the type here, because it will
10767 // be written by Export::write_type anyhow.
10768 exp->write_c_string("type ");
10769 exp->write_type(this);
10770 exp->write_c_string(";\n");
10773 // Import a named type.
10775 void
10776 Named_type::import_named_type(Import* imp, Named_type** ptype)
10778 imp->require_c_string("type ");
10779 Type *type = imp->read_type();
10780 *ptype = type->named_type();
10781 go_assert(*ptype != NULL);
10782 imp->require_c_string(";\n");
10785 // Export the type when it is referenced by another type. In this
10786 // case Export::export_type will already have issued the name.
10788 void
10789 Named_type::do_export(Export* exp) const
10791 exp->write_type(this->type_);
10793 // To save space, we only export the methods directly attached to
10794 // this type.
10795 Bindings* methods = this->local_methods_;
10796 if (methods == NULL)
10797 return;
10799 exp->write_c_string("\n");
10800 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10801 p != methods->end_definitions();
10802 ++p)
10804 exp->write_c_string(" ");
10805 (*p)->export_named_object(exp);
10808 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10809 p != methods->end_declarations();
10810 ++p)
10812 if (p->second->is_function_declaration())
10814 exp->write_c_string(" ");
10815 p->second->export_named_object(exp);
10820 // Make a named type.
10822 Named_type*
10823 Type::make_named_type(Named_object* named_object, Type* type,
10824 Location location)
10826 return new Named_type(named_object, type, location);
10829 // Finalize the methods for TYPE. It will be a named type or a struct
10830 // type. This sets *ALL_METHODS to the list of methods, and builds
10831 // all required stubs.
10833 void
10834 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10835 Methods** all_methods)
10837 *all_methods = new Methods();
10838 std::vector<const Named_type*> seen;
10839 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10840 if ((*all_methods)->empty())
10842 delete *all_methods;
10843 *all_methods = NULL;
10845 Type::build_stub_methods(gogo, type, *all_methods, location);
10848 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
10849 // build up the struct field indexes as we go. DEPTH is the depth of
10850 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
10851 // adding these methods for an anonymous field with pointer type.
10852 // NEEDS_STUB_METHOD is true if we need to use a stub method which
10853 // calls the real method. TYPES_SEEN is used to avoid infinite
10854 // recursion.
10856 void
10857 Type::add_methods_for_type(const Type* type,
10858 const Method::Field_indexes* field_indexes,
10859 unsigned int depth,
10860 bool is_embedded_pointer,
10861 bool needs_stub_method,
10862 std::vector<const Named_type*>* seen,
10863 Methods* methods)
10865 // Pointer types may not have methods.
10866 if (type->points_to() != NULL)
10867 return;
10869 const Named_type* nt = type->named_type();
10870 if (nt != NULL)
10872 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
10873 p != seen->end();
10874 ++p)
10876 if (*p == nt)
10877 return;
10880 seen->push_back(nt);
10882 Type::add_local_methods_for_type(nt, field_indexes, depth,
10883 is_embedded_pointer, needs_stub_method,
10884 methods);
10887 Type::add_embedded_methods_for_type(type, field_indexes, depth,
10888 is_embedded_pointer, needs_stub_method,
10889 seen, methods);
10891 // If we are called with depth > 0, then we are looking at an
10892 // anonymous field of a struct. If such a field has interface type,
10893 // then we need to add the interface methods. We don't want to add
10894 // them when depth == 0, because we will already handle them
10895 // following the usual rules for an interface type.
10896 if (depth > 0)
10897 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
10899 if (nt != NULL)
10900 seen->pop_back();
10903 // Add the local methods for the named type NT to *METHODS. The
10904 // parameters are as for add_methods_to_type.
10906 void
10907 Type::add_local_methods_for_type(const Named_type* nt,
10908 const Method::Field_indexes* field_indexes,
10909 unsigned int depth,
10910 bool is_embedded_pointer,
10911 bool needs_stub_method,
10912 Methods* methods)
10914 const Bindings* local_methods = nt->local_methods();
10915 if (local_methods == NULL)
10916 return;
10918 for (Bindings::const_declarations_iterator p =
10919 local_methods->begin_declarations();
10920 p != local_methods->end_declarations();
10921 ++p)
10923 Named_object* no = p->second;
10924 bool is_value_method = (is_embedded_pointer
10925 || !Type::method_expects_pointer(no));
10926 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
10927 (needs_stub_method || depth > 0));
10928 if (!methods->insert(no->name(), m))
10929 delete m;
10933 // Add the embedded methods for TYPE to *METHODS. These are the
10934 // methods attached to anonymous fields. The parameters are as for
10935 // add_methods_to_type.
10937 void
10938 Type::add_embedded_methods_for_type(const Type* type,
10939 const Method::Field_indexes* field_indexes,
10940 unsigned int depth,
10941 bool is_embedded_pointer,
10942 bool needs_stub_method,
10943 std::vector<const Named_type*>* seen,
10944 Methods* methods)
10946 // Look for anonymous fields in TYPE. TYPE has fields if it is a
10947 // struct.
10948 const Struct_type* st = type->struct_type();
10949 if (st == NULL)
10950 return;
10952 const Struct_field_list* fields = st->fields();
10953 if (fields == NULL)
10954 return;
10956 unsigned int i = 0;
10957 for (Struct_field_list::const_iterator pf = fields->begin();
10958 pf != fields->end();
10959 ++pf, ++i)
10961 if (!pf->is_anonymous())
10962 continue;
10964 Type* ftype = pf->type();
10965 bool is_pointer = false;
10966 if (ftype->points_to() != NULL)
10968 ftype = ftype->points_to();
10969 is_pointer = true;
10971 Named_type* fnt = ftype->named_type();
10972 if (fnt == NULL)
10974 // This is an error, but it will be diagnosed elsewhere.
10975 continue;
10978 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
10979 sub_field_indexes->next = field_indexes;
10980 sub_field_indexes->field_index = i;
10982 Methods tmp_methods;
10983 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
10984 (is_embedded_pointer || is_pointer),
10985 (needs_stub_method
10986 || is_pointer
10987 || i > 0),
10988 seen,
10989 &tmp_methods);
10990 // Check if there are promoted methods that conflict with field names and
10991 // don't add them to the method map.
10992 for (Methods::const_iterator p = tmp_methods.begin();
10993 p != tmp_methods.end();
10994 ++p)
10996 bool found = false;
10997 for (Struct_field_list::const_iterator fp = fields->begin();
10998 fp != fields->end();
10999 ++fp)
11001 if (fp->field_name() == p->first)
11003 found = true;
11004 break;
11007 if (!found &&
11008 !methods->insert(p->first, p->second))
11009 delete p->second;
11014 // If TYPE is an interface type, then add its method to *METHODS.
11015 // This is for interface methods attached to an anonymous field. The
11016 // parameters are as for add_methods_for_type.
11018 void
11019 Type::add_interface_methods_for_type(const Type* type,
11020 const Method::Field_indexes* field_indexes,
11021 unsigned int depth,
11022 Methods* methods)
11024 const Interface_type* it = type->interface_type();
11025 if (it == NULL)
11026 return;
11028 const Typed_identifier_list* imethods = it->methods();
11029 if (imethods == NULL)
11030 return;
11032 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11033 pm != imethods->end();
11034 ++pm)
11036 Function_type* fntype = pm->type()->function_type();
11037 if (fntype == NULL)
11039 // This is an error, but it should be reported elsewhere
11040 // when we look at the methods for IT.
11041 continue;
11043 go_assert(!fntype->is_method());
11044 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11045 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11046 field_indexes, depth);
11047 if (!methods->insert(pm->name(), m))
11048 delete m;
11052 // Build stub methods for TYPE as needed. METHODS is the set of
11053 // methods for the type. A stub method may be needed when a type
11054 // inherits a method from an anonymous field. When we need the
11055 // address of the method, as in a type descriptor, we need to build a
11056 // little stub which does the required field dereferences and jumps to
11057 // the real method. LOCATION is the location of the type definition.
11059 void
11060 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11061 Location location)
11063 if (methods == NULL)
11064 return;
11065 for (Methods::const_iterator p = methods->begin();
11066 p != methods->end();
11067 ++p)
11069 Method* m = p->second;
11070 if (m->is_ambiguous() || !m->needs_stub_method())
11071 continue;
11073 const std::string& name(p->first);
11075 // Build a stub method.
11077 const Function_type* fntype = m->type();
11079 static unsigned int counter;
11080 char buf[100];
11081 snprintf(buf, sizeof buf, "$this%u", counter);
11082 ++counter;
11084 Type* receiver_type = const_cast<Type*>(type);
11085 if (!m->is_value_method())
11086 receiver_type = Type::make_pointer_type(receiver_type);
11087 Location receiver_location = m->receiver_location();
11088 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11089 receiver_location);
11091 const Typed_identifier_list* fnparams = fntype->parameters();
11092 Typed_identifier_list* stub_params;
11093 if (fnparams == NULL || fnparams->empty())
11094 stub_params = NULL;
11095 else
11097 // We give each stub parameter a unique name.
11098 stub_params = new Typed_identifier_list();
11099 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11100 pp != fnparams->end();
11101 ++pp)
11103 char pbuf[100];
11104 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11105 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11106 pp->location()));
11107 ++counter;
11111 const Typed_identifier_list* fnresults = fntype->results();
11112 Typed_identifier_list* stub_results;
11113 if (fnresults == NULL || fnresults->empty())
11114 stub_results = NULL;
11115 else
11117 // We create the result parameters without any names, since
11118 // we won't refer to them.
11119 stub_results = new Typed_identifier_list();
11120 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11121 pr != fnresults->end();
11122 ++pr)
11123 stub_results->push_back(Typed_identifier("", pr->type(),
11124 pr->location()));
11127 Function_type* stub_type = Type::make_function_type(receiver,
11128 stub_params,
11129 stub_results,
11130 fntype->location());
11131 if (fntype->is_varargs())
11132 stub_type->set_is_varargs();
11134 // We only create the function in the package which creates the
11135 // type.
11136 const Package* package;
11137 if (type->named_type() == NULL)
11138 package = NULL;
11139 else
11140 package = type->named_type()->named_object()->package();
11141 std::string stub_name = gogo->stub_method_name(name);
11142 Named_object* stub;
11143 if (package != NULL)
11144 stub = Named_object::make_function_declaration(stub_name, package,
11145 stub_type, location);
11146 else
11148 stub = gogo->start_function(stub_name, stub_type, false,
11149 fntype->location());
11150 Type::build_one_stub_method(gogo, m, buf, stub_params,
11151 fntype->is_varargs(), location);
11152 gogo->finish_function(fntype->location());
11154 if (type->named_type() == NULL && stub->is_function())
11155 stub->func_value()->set_is_unnamed_type_stub_method();
11156 if (m->nointerface() && stub->is_function())
11157 stub->func_value()->set_nointerface();
11160 m->set_stub_object(stub);
11164 // Build a stub method which adjusts the receiver as required to call
11165 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11166 // PARAMS is the list of function parameters.
11168 void
11169 Type::build_one_stub_method(Gogo* gogo, Method* method,
11170 const char* receiver_name,
11171 const Typed_identifier_list* params,
11172 bool is_varargs,
11173 Location location)
11175 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11176 go_assert(receiver_object != NULL);
11178 Expression* expr = Expression::make_var_reference(receiver_object, location);
11179 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11180 if (expr->type()->points_to() == NULL)
11181 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11183 Expression_list* arguments;
11184 if (params == NULL || params->empty())
11185 arguments = NULL;
11186 else
11188 arguments = new Expression_list();
11189 for (Typed_identifier_list::const_iterator p = params->begin();
11190 p != params->end();
11191 ++p)
11193 Named_object* param = gogo->lookup(p->name(), NULL);
11194 go_assert(param != NULL);
11195 Expression* param_ref = Expression::make_var_reference(param,
11196 location);
11197 arguments->push_back(param_ref);
11201 Expression* func = method->bind_method(expr, location);
11202 go_assert(func != NULL);
11203 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11204 location);
11206 gogo->add_statement(Statement::make_return_from_call(call, location));
11209 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11210 // in reverse order.
11212 Expression*
11213 Type::apply_field_indexes(Expression* expr,
11214 const Method::Field_indexes* field_indexes,
11215 Location location)
11217 if (field_indexes == NULL)
11218 return expr;
11219 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11220 Struct_type* stype = expr->type()->deref()->struct_type();
11221 go_assert(stype != NULL
11222 && field_indexes->field_index < stype->field_count());
11223 if (expr->type()->struct_type() == NULL)
11225 go_assert(expr->type()->points_to() != NULL);
11226 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11227 location);
11228 go_assert(expr->type()->struct_type() == stype);
11230 return Expression::make_field_reference(expr, field_indexes->field_index,
11231 location);
11234 // Return whether NO is a method for which the receiver is a pointer.
11236 bool
11237 Type::method_expects_pointer(const Named_object* no)
11239 const Function_type *fntype;
11240 if (no->is_function())
11241 fntype = no->func_value()->type();
11242 else if (no->is_function_declaration())
11243 fntype = no->func_declaration_value()->type();
11244 else
11245 go_unreachable();
11246 return fntype->receiver()->type()->points_to() != NULL;
11249 // Given a set of methods for a type, METHODS, return the method NAME,
11250 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11251 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11252 // but is ambiguous (and return NULL).
11254 Method*
11255 Type::method_function(const Methods* methods, const std::string& name,
11256 bool* is_ambiguous)
11258 if (is_ambiguous != NULL)
11259 *is_ambiguous = false;
11260 if (methods == NULL)
11261 return NULL;
11262 Methods::const_iterator p = methods->find(name);
11263 if (p == methods->end())
11264 return NULL;
11265 Method* m = p->second;
11266 if (m->is_ambiguous())
11268 if (is_ambiguous != NULL)
11269 *is_ambiguous = true;
11270 return NULL;
11272 return m;
11275 // Return a pointer to the interface method table for TYPE for the
11276 // interface INTERFACE.
11278 Expression*
11279 Type::interface_method_table(Type* type,
11280 Interface_type *interface,
11281 bool is_pointer,
11282 Interface_method_tables** method_tables,
11283 Interface_method_tables** pointer_tables)
11285 go_assert(!interface->is_empty());
11287 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11289 if (*pimt == NULL)
11290 *pimt = new Interface_method_tables(5);
11292 std::pair<Interface_type*, Expression*> val(interface, NULL);
11293 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11295 Location loc = Linemap::predeclared_location();
11296 if (ins.second)
11298 // This is a new entry in the hash table.
11299 go_assert(ins.first->second == NULL);
11300 ins.first->second =
11301 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11303 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11306 // Look for field or method NAME for TYPE. Return an Expression for
11307 // the field or method bound to EXPR. If there is no such field or
11308 // method, give an appropriate error and return an error expression.
11310 Expression*
11311 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11312 const std::string& name,
11313 Location location)
11315 if (type->deref()->is_error_type())
11316 return Expression::make_error(location);
11318 const Named_type* nt = type->deref()->named_type();
11319 const Struct_type* st = type->deref()->struct_type();
11320 const Interface_type* it = type->interface_type();
11322 // If this is a pointer to a pointer, then it is possible that the
11323 // pointed-to type has methods.
11324 bool dereferenced = false;
11325 if (nt == NULL
11326 && st == NULL
11327 && it == NULL
11328 && type->points_to() != NULL
11329 && type->points_to()->points_to() != NULL)
11331 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11332 location);
11333 type = type->points_to();
11334 if (type->deref()->is_error_type())
11335 return Expression::make_error(location);
11336 nt = type->points_to()->named_type();
11337 st = type->points_to()->struct_type();
11338 dereferenced = true;
11341 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11342 || expr->is_addressable());
11343 std::vector<const Named_type*> seen;
11344 bool is_method = false;
11345 bool found_pointer_method = false;
11346 std::string ambig1;
11347 std::string ambig2;
11348 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11349 &seen, NULL, &is_method,
11350 &found_pointer_method, &ambig1, &ambig2))
11352 Expression* ret;
11353 if (!is_method)
11355 go_assert(st != NULL);
11356 if (type->struct_type() == NULL)
11358 if (dereferenced)
11360 go_error_at(location, "pointer type has no field %qs",
11361 Gogo::message_name(name).c_str());
11362 return Expression::make_error(location);
11364 go_assert(type->points_to() != NULL);
11365 expr = Expression::make_dereference(expr,
11366 Expression::NIL_CHECK_DEFAULT,
11367 location);
11368 go_assert(expr->type()->struct_type() == st);
11370 ret = st->field_reference(expr, name, location);
11371 if (ret == NULL)
11373 go_error_at(location, "type has no field %qs",
11374 Gogo::message_name(name).c_str());
11375 return Expression::make_error(location);
11378 else if (it != NULL && it->find_method(name) != NULL)
11379 ret = Expression::make_interface_field_reference(expr, name,
11380 location);
11381 else
11383 Method* m;
11384 if (nt != NULL)
11385 m = nt->method_function(name, NULL);
11386 else if (st != NULL)
11387 m = st->method_function(name, NULL);
11388 else
11389 go_unreachable();
11390 go_assert(m != NULL);
11391 if (dereferenced)
11393 go_error_at(location,
11394 "calling method %qs requires explicit dereference",
11395 Gogo::message_name(name).c_str());
11396 return Expression::make_error(location);
11398 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11399 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11400 ret = m->bind_method(expr, location);
11402 go_assert(ret != NULL);
11403 return ret;
11405 else
11407 if (Gogo::is_erroneous_name(name))
11409 // An error was already reported.
11411 else if (!ambig1.empty())
11412 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11413 Gogo::message_name(name).c_str(), ambig1.c_str(),
11414 ambig2.c_str());
11415 else if (found_pointer_method)
11416 go_error_at(location, "method requires a pointer receiver");
11417 else if (nt == NULL && st == NULL && it == NULL)
11418 go_error_at(location,
11419 ("reference to field %qs in object which "
11420 "has no fields or methods"),
11421 Gogo::message_name(name).c_str());
11422 else
11424 bool is_unexported;
11425 // The test for 'a' and 'z' is to handle builtin names,
11426 // which are not hidden.
11427 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11428 is_unexported = false;
11429 else
11431 std::string unpacked = Gogo::unpack_hidden_name(name);
11432 seen.clear();
11433 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11434 unpacked,
11435 &seen);
11437 if (is_unexported)
11438 go_error_at(location, "reference to unexported field or method %qs",
11439 Gogo::message_name(name).c_str());
11440 else
11441 go_error_at(location, "reference to undefined field or method %qs",
11442 Gogo::message_name(name).c_str());
11444 return Expression::make_error(location);
11448 // Look in TYPE for a field or method named NAME, return true if one
11449 // is found. This looks through embedded anonymous fields and handles
11450 // ambiguity. If a method is found, sets *IS_METHOD to true;
11451 // otherwise, if a field is found, set it to false. If
11452 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11453 // whose address can not be taken. SEEN is used to avoid infinite
11454 // recursion on invalid types.
11456 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11457 // method we couldn't use because it requires a pointer. LEVEL is
11458 // used for recursive calls, and can be NULL for a non-recursive call.
11459 // When this function returns false because it finds that the name is
11460 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11461 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11462 // will be unchanged.
11464 // This function just returns whether or not there is a field or
11465 // method, and whether it is a field or method. It doesn't build an
11466 // expression to refer to it. If it is a method, we then look in the
11467 // list of all methods for the type. If it is a field, the search has
11468 // to be done again, looking only for fields, and building up the
11469 // expression as we go.
11471 bool
11472 Type::find_field_or_method(const Type* type,
11473 const std::string& name,
11474 bool receiver_can_be_pointer,
11475 std::vector<const Named_type*>* seen,
11476 int* level,
11477 bool* is_method,
11478 bool* found_pointer_method,
11479 std::string* ambig1,
11480 std::string* ambig2)
11482 // Named types can have locally defined methods.
11483 const Named_type* nt = type->named_type();
11484 if (nt == NULL && type->points_to() != NULL)
11485 nt = type->points_to()->named_type();
11486 if (nt != NULL)
11488 Named_object* no = nt->find_local_method(name);
11489 if (no != NULL)
11491 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11493 *is_method = true;
11494 return true;
11497 // Record that we have found a pointer method in order to
11498 // give a better error message if we don't find anything
11499 // else.
11500 *found_pointer_method = true;
11503 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11504 p != seen->end();
11505 ++p)
11507 if (*p == nt)
11509 // We've already seen this type when searching for methods.
11510 return false;
11515 // Interface types can have methods.
11516 const Interface_type* it = type->interface_type();
11517 if (it != NULL && it->find_method(name) != NULL)
11519 *is_method = true;
11520 return true;
11523 // Struct types can have fields. They can also inherit fields and
11524 // methods from anonymous fields.
11525 const Struct_type* st = type->deref()->struct_type();
11526 if (st == NULL)
11527 return false;
11528 const Struct_field_list* fields = st->fields();
11529 if (fields == NULL)
11530 return false;
11532 if (nt != NULL)
11533 seen->push_back(nt);
11535 int found_level = 0;
11536 bool found_is_method = false;
11537 std::string found_ambig1;
11538 std::string found_ambig2;
11539 const Struct_field* found_parent = NULL;
11540 for (Struct_field_list::const_iterator pf = fields->begin();
11541 pf != fields->end();
11542 ++pf)
11544 if (pf->is_field_name(name))
11546 *is_method = false;
11547 if (nt != NULL)
11548 seen->pop_back();
11549 return true;
11552 if (!pf->is_anonymous())
11553 continue;
11555 if (pf->type()->deref()->is_error_type()
11556 || pf->type()->deref()->is_undefined())
11557 continue;
11559 Named_type* fnt = pf->type()->named_type();
11560 if (fnt == NULL)
11561 fnt = pf->type()->deref()->named_type();
11562 go_assert(fnt != NULL);
11564 // Methods with pointer receivers on embedded field are
11565 // inherited by the pointer to struct, and also by the struct
11566 // type if the field itself is a pointer.
11567 bool can_be_pointer = (receiver_can_be_pointer
11568 || pf->type()->points_to() != NULL);
11569 int sublevel = level == NULL ? 1 : *level + 1;
11570 bool sub_is_method;
11571 std::string subambig1;
11572 std::string subambig2;
11573 bool subfound = Type::find_field_or_method(fnt,
11574 name,
11575 can_be_pointer,
11576 seen,
11577 &sublevel,
11578 &sub_is_method,
11579 found_pointer_method,
11580 &subambig1,
11581 &subambig2);
11582 if (!subfound)
11584 if (!subambig1.empty())
11586 // The name was found via this field, but is ambiguous.
11587 // if the ambiguity is lower or at the same level as
11588 // anything else we have already found, then we want to
11589 // pass the ambiguity back to the caller.
11590 if (found_level == 0 || sublevel <= found_level)
11592 found_ambig1 = (Gogo::message_name(pf->field_name())
11593 + '.' + subambig1);
11594 found_ambig2 = (Gogo::message_name(pf->field_name())
11595 + '.' + subambig2);
11596 found_level = sublevel;
11600 else
11602 // The name was found via this field. Use the level to see
11603 // if we want to use this one, or whether it introduces an
11604 // ambiguity.
11605 if (found_level == 0 || sublevel < found_level)
11607 found_level = sublevel;
11608 found_is_method = sub_is_method;
11609 found_ambig1.clear();
11610 found_ambig2.clear();
11611 found_parent = &*pf;
11613 else if (sublevel > found_level)
11615 else if (found_ambig1.empty())
11617 // We found an ambiguity.
11618 go_assert(found_parent != NULL);
11619 found_ambig1 = Gogo::message_name(found_parent->field_name());
11620 found_ambig2 = Gogo::message_name(pf->field_name());
11622 else
11624 // We found an ambiguity, but we already know of one.
11625 // Just report the earlier one.
11630 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
11631 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11632 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
11633 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11635 if (nt != NULL)
11636 seen->pop_back();
11638 if (found_level == 0)
11639 return false;
11640 else if (found_is_method
11641 && type->named_type() != NULL
11642 && type->points_to() != NULL)
11644 // If this is a method inherited from a struct field in a named pointer
11645 // type, it is invalid to automatically dereference the pointer to the
11646 // struct to find this method.
11647 if (level != NULL)
11648 *level = found_level;
11649 *is_method = true;
11650 return false;
11652 else if (!found_ambig1.empty())
11654 go_assert(!found_ambig1.empty());
11655 ambig1->assign(found_ambig1);
11656 ambig2->assign(found_ambig2);
11657 if (level != NULL)
11658 *level = found_level;
11659 return false;
11661 else
11663 if (level != NULL)
11664 *level = found_level;
11665 *is_method = found_is_method;
11666 return true;
11670 // Return whether NAME is an unexported field or method for TYPE.
11672 bool
11673 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11674 const std::string& name,
11675 std::vector<const Named_type*>* seen)
11677 const Named_type* nt = type->named_type();
11678 if (nt == NULL)
11679 nt = type->deref()->named_type();
11680 if (nt != NULL)
11682 if (nt->is_unexported_local_method(gogo, name))
11683 return true;
11685 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11686 p != seen->end();
11687 ++p)
11689 if (*p == nt)
11691 // We've already seen this type.
11692 return false;
11697 const Interface_type* it = type->interface_type();
11698 if (it != NULL && it->is_unexported_method(gogo, name))
11699 return true;
11701 type = type->deref();
11703 const Struct_type* st = type->struct_type();
11704 if (st != NULL && st->is_unexported_local_field(gogo, name))
11705 return true;
11707 if (st == NULL)
11708 return false;
11710 const Struct_field_list* fields = st->fields();
11711 if (fields == NULL)
11712 return false;
11714 if (nt != NULL)
11715 seen->push_back(nt);
11717 for (Struct_field_list::const_iterator pf = fields->begin();
11718 pf != fields->end();
11719 ++pf)
11721 if (pf->is_anonymous()
11722 && !pf->type()->deref()->is_error_type()
11723 && !pf->type()->deref()->is_undefined())
11725 Named_type* subtype = pf->type()->named_type();
11726 if (subtype == NULL)
11727 subtype = pf->type()->deref()->named_type();
11728 if (subtype == NULL)
11730 // This is an error, but it will be diagnosed elsewhere.
11731 continue;
11733 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11735 if (nt != NULL)
11736 seen->pop_back();
11737 return true;
11742 if (nt != NULL)
11743 seen->pop_back();
11745 return false;
11748 // Class Forward_declaration.
11750 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11751 : Type(TYPE_FORWARD),
11752 named_object_(named_object->resolve()), warned_(false)
11754 go_assert(this->named_object_->is_unknown()
11755 || this->named_object_->is_type_declaration());
11758 // Return the named object.
11760 Named_object*
11761 Forward_declaration_type::named_object()
11763 return this->named_object_->resolve();
11766 const Named_object*
11767 Forward_declaration_type::named_object() const
11769 return this->named_object_->resolve();
11772 // Return the name of the forward declared type.
11774 const std::string&
11775 Forward_declaration_type::name() const
11777 return this->named_object()->name();
11780 // Warn about a use of a type which has been declared but not defined.
11782 void
11783 Forward_declaration_type::warn() const
11785 Named_object* no = this->named_object_->resolve();
11786 if (no->is_unknown())
11788 // The name was not defined anywhere.
11789 if (!this->warned_)
11791 go_error_at(this->named_object_->location(),
11792 "use of undefined type %qs",
11793 no->message_name().c_str());
11794 this->warned_ = true;
11797 else if (no->is_type_declaration())
11799 // The name was seen as a type, but the type was never defined.
11800 if (no->type_declaration_value()->using_type())
11802 go_error_at(this->named_object_->location(),
11803 "use of undefined type %qs",
11804 no->message_name().c_str());
11805 this->warned_ = true;
11808 else
11810 // The name was defined, but not as a type.
11811 if (!this->warned_)
11813 go_error_at(this->named_object_->location(), "expected type");
11814 this->warned_ = true;
11819 // Get the base type of a declaration. This gives an error if the
11820 // type has not yet been defined.
11822 Type*
11823 Forward_declaration_type::real_type()
11825 if (this->is_defined())
11827 Named_type* nt = this->named_object()->type_value();
11828 if (!nt->is_valid())
11829 return Type::make_error_type();
11830 return this->named_object()->type_value();
11832 else
11834 this->warn();
11835 return Type::make_error_type();
11839 const Type*
11840 Forward_declaration_type::real_type() const
11842 if (this->is_defined())
11844 const Named_type* nt = this->named_object()->type_value();
11845 if (!nt->is_valid())
11846 return Type::make_error_type();
11847 return this->named_object()->type_value();
11849 else
11851 this->warn();
11852 return Type::make_error_type();
11856 // Return whether the base type is defined.
11858 bool
11859 Forward_declaration_type::is_defined() const
11861 return this->named_object()->is_type();
11864 // Add a method. This is used when methods are defined before the
11865 // type.
11867 Named_object*
11868 Forward_declaration_type::add_method(const std::string& name,
11869 Function* function)
11871 Named_object* no = this->named_object();
11872 if (no->is_unknown())
11873 no->declare_as_type();
11874 return no->type_declaration_value()->add_method(name, function);
11877 // Add a method declaration. This is used when methods are declared
11878 // before the type.
11880 Named_object*
11881 Forward_declaration_type::add_method_declaration(const std::string& name,
11882 Package* package,
11883 Function_type* type,
11884 Location location)
11886 Named_object* no = this->named_object();
11887 if (no->is_unknown())
11888 no->declare_as_type();
11889 Type_declaration* td = no->type_declaration_value();
11890 return td->add_method_declaration(name, package, type, location);
11893 // Add an already created object as a method.
11895 void
11896 Forward_declaration_type::add_existing_method(Named_object* nom)
11898 Named_object* no = this->named_object();
11899 if (no->is_unknown())
11900 no->declare_as_type();
11901 no->type_declaration_value()->add_existing_method(nom);
11904 // Traversal.
11907 Forward_declaration_type::do_traverse(Traverse* traverse)
11909 if (this->is_defined()
11910 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
11911 return TRAVERSE_EXIT;
11912 return TRAVERSE_CONTINUE;
11915 // Verify the type.
11917 bool
11918 Forward_declaration_type::do_verify()
11920 if (!this->is_defined() && !this->is_nil_constant_as_type())
11922 this->warn();
11923 return false;
11925 return true;
11928 // Get the backend representation for the type.
11930 Btype*
11931 Forward_declaration_type::do_get_backend(Gogo* gogo)
11933 if (this->is_defined())
11934 return Type::get_named_base_btype(gogo, this->real_type());
11936 if (this->warned_)
11937 return gogo->backend()->error_type();
11939 // We represent an undefined type as a struct with no fields. That
11940 // should work fine for the backend, since the same case can arise
11941 // in C.
11942 std::vector<Backend::Btyped_identifier> fields;
11943 Btype* bt = gogo->backend()->struct_type(fields);
11944 return gogo->backend()->named_type(this->name(), bt,
11945 this->named_object()->location());
11948 // Build a type descriptor for a forwarded type.
11950 Expression*
11951 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11953 Location ploc = Linemap::predeclared_location();
11954 if (!this->is_defined())
11955 return Expression::make_error(ploc);
11956 else
11958 Type* t = this->real_type();
11959 if (name != NULL)
11960 return this->named_type_descriptor(gogo, t, name);
11961 else
11962 return Expression::make_error(this->named_object_->location());
11966 // The reflection string.
11968 void
11969 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
11971 this->append_reflection(this->real_type(), gogo, ret);
11974 // Export a forward declaration. This can happen when a defined type
11975 // refers to a type which is only declared (and is presumably defined
11976 // in some other file in the same package).
11978 void
11979 Forward_declaration_type::do_export(Export*) const
11981 // If there is a base type, that should be exported instead of this.
11982 go_assert(!this->is_defined());
11984 // We don't output anything.
11987 // Make a forward declaration.
11989 Type*
11990 Type::make_forward_declaration(Named_object* named_object)
11992 return new Forward_declaration_type(named_object);
11995 // Class Typed_identifier_list.
11997 // Sort the entries by name.
11999 struct Typed_identifier_list_sort
12001 public:
12002 bool
12003 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12005 return (Gogo::unpack_hidden_name(t1.name())
12006 < Gogo::unpack_hidden_name(t2.name()));
12010 void
12011 Typed_identifier_list::sort_by_name()
12013 std::sort(this->entries_.begin(), this->entries_.end(),
12014 Typed_identifier_list_sort());
12017 // Traverse types.
12020 Typed_identifier_list::traverse(Traverse* traverse)
12022 for (Typed_identifier_list::const_iterator p = this->begin();
12023 p != this->end();
12024 ++p)
12026 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12027 return TRAVERSE_EXIT;
12029 return TRAVERSE_CONTINUE;
12032 // Copy the list.
12034 Typed_identifier_list*
12035 Typed_identifier_list::copy() const
12037 Typed_identifier_list* ret = new Typed_identifier_list();
12038 for (Typed_identifier_list::const_iterator p = this->begin();
12039 p != this->end();
12040 ++p)
12041 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12042 return ret;