2018-07-05 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / go / gofrontend / types.cc
blobe5f84c51549c0ebd960fd6dd6aa0aa7a853abb4c
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 // Skip alias definitions.
112 Type*
113 Type::unalias()
115 Type* t = this->forwarded();
116 Named_type* nt = t->named_type();
117 while (nt != NULL && nt->is_alias())
119 t = nt->real_type()->forwarded();
120 nt = t->named_type();
122 return t;
125 const Type*
126 Type::unalias() const
128 const Type* t = this->forwarded();
129 const Named_type* nt = t->named_type();
130 while (nt != NULL && nt->is_alias())
132 t = nt->real_type()->forwarded();
133 nt = t->named_type();
135 return t;
138 // If this is a named type, return it. Otherwise, return NULL.
140 Named_type*
141 Type::named_type()
143 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
146 const Named_type*
147 Type::named_type() const
149 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
152 // Return true if this type is not defined.
154 bool
155 Type::is_undefined() const
157 return this->forwarded()->forward_declaration_type() != NULL;
160 // Return true if this is a basic type: a type which is not composed
161 // of other types, and is not void.
163 bool
164 Type::is_basic_type() const
166 switch (this->classification_)
168 case TYPE_INTEGER:
169 case TYPE_FLOAT:
170 case TYPE_COMPLEX:
171 case TYPE_BOOLEAN:
172 case TYPE_STRING:
173 case TYPE_NIL:
174 return true;
176 case TYPE_ERROR:
177 case TYPE_VOID:
178 case TYPE_FUNCTION:
179 case TYPE_POINTER:
180 case TYPE_STRUCT:
181 case TYPE_ARRAY:
182 case TYPE_MAP:
183 case TYPE_CHANNEL:
184 case TYPE_INTERFACE:
185 return false;
187 case TYPE_NAMED:
188 case TYPE_FORWARD:
189 return this->base()->is_basic_type();
191 default:
192 go_unreachable();
196 // Return true if this is an abstract type.
198 bool
199 Type::is_abstract() const
201 switch (this->classification())
203 case TYPE_INTEGER:
204 return this->integer_type()->is_abstract();
205 case TYPE_FLOAT:
206 return this->float_type()->is_abstract();
207 case TYPE_COMPLEX:
208 return this->complex_type()->is_abstract();
209 case TYPE_STRING:
210 return this->is_abstract_string_type();
211 case TYPE_BOOLEAN:
212 return this->is_abstract_boolean_type();
213 default:
214 return false;
218 // Return a non-abstract version of an abstract type.
220 Type*
221 Type::make_non_abstract_type()
223 go_assert(this->is_abstract());
224 switch (this->classification())
226 case TYPE_INTEGER:
227 if (this->integer_type()->is_rune())
228 return Type::lookup_integer_type("int32");
229 else
230 return Type::lookup_integer_type("int");
231 case TYPE_FLOAT:
232 return Type::lookup_float_type("float64");
233 case TYPE_COMPLEX:
234 return Type::lookup_complex_type("complex128");
235 case TYPE_STRING:
236 return Type::lookup_string_type();
237 case TYPE_BOOLEAN:
238 return Type::lookup_bool_type();
239 default:
240 go_unreachable();
244 // Return true if this is an error type. Don't give an error if we
245 // try to dereference an undefined forwarding type, as this is called
246 // in the parser when the type may legitimately be undefined.
248 bool
249 Type::is_error_type() const
251 const Type* t = this->forwarded();
252 // Note that we return false for an undefined forward type.
253 switch (t->classification_)
255 case TYPE_ERROR:
256 return true;
257 case TYPE_NAMED:
258 return t->named_type()->is_named_error_type();
259 default:
260 return false;
264 // If this is a pointer type, return the type to which it points.
265 // Otherwise, return NULL.
267 Type*
268 Type::points_to() const
270 const Pointer_type* ptype = this->convert<const Pointer_type,
271 TYPE_POINTER>();
272 return ptype == NULL ? NULL : ptype->points_to();
275 // Return whether this is a slice type.
277 bool
278 Type::is_slice_type() const
280 return this->array_type() != NULL && this->array_type()->length() == NULL;
283 // Return whether this is the predeclared constant nil being used as a
284 // type.
286 bool
287 Type::is_nil_constant_as_type() const
289 const Type* t = this->forwarded();
290 if (t->forward_declaration_type() != NULL)
292 const Named_object* no = t->forward_declaration_type()->named_object();
293 if (no->is_unknown())
294 no = no->unknown_value()->real_named_object();
295 if (no != NULL
296 && no->is_const()
297 && no->const_value()->expr()->is_nil_expression())
298 return true;
300 return false;
303 // Traverse a type.
306 Type::traverse(Type* type, Traverse* traverse)
308 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
309 || (traverse->traverse_mask()
310 & Traverse::traverse_expressions) != 0);
311 if (traverse->remember_type(type))
313 // We have already traversed this type.
314 return TRAVERSE_CONTINUE;
316 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
318 int t = traverse->type(type);
319 if (t == TRAVERSE_EXIT)
320 return TRAVERSE_EXIT;
321 else if (t == TRAVERSE_SKIP_COMPONENTS)
322 return TRAVERSE_CONTINUE;
324 // An array type has an expression which we need to traverse if
325 // traverse_expressions is set.
326 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
327 return TRAVERSE_EXIT;
328 return TRAVERSE_CONTINUE;
331 // Default implementation for do_traverse for child class.
334 Type::do_traverse(Traverse*)
336 return TRAVERSE_CONTINUE;
339 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
340 // then return true for all erroneous types; this is used to avoid
341 // cascading errors. If REASON is not NULL, optionally set *REASON to
342 // the reason the types are not identical.
344 bool
345 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
346 std::string* reason)
348 return Type::are_identical_cmp_tags(t1, t2, COMPARE_TAGS,
349 errors_are_identical, reason);
352 // Like are_identical, but with a CMP_TAGS parameter.
354 bool
355 Type::are_identical_cmp_tags(const Type* t1, const Type* t2, Cmp_tags cmp_tags,
356 bool errors_are_identical, std::string* reason)
358 if (t1 == NULL || t2 == NULL)
360 // Something is wrong.
361 return errors_are_identical ? true : t1 == t2;
364 // Skip defined forward declarations. Ignore aliases.
365 t1 = t1->unalias();
366 t2 = t2->unalias();
368 if (t1 == t2)
369 return true;
371 // An undefined forward declaration is an error.
372 if (t1->forward_declaration_type() != NULL
373 || t2->forward_declaration_type() != NULL)
374 return errors_are_identical;
376 // Avoid cascading errors with error types.
377 if (t1->is_error_type() || t2->is_error_type())
379 if (errors_are_identical)
380 return true;
381 return t1->is_error_type() && t2->is_error_type();
384 // Get a good reason for the sink type. Note that the sink type on
385 // the left hand side of an assignment is handled in are_assignable.
386 if (t1->is_sink_type() || t2->is_sink_type())
388 if (reason != NULL)
389 *reason = "invalid use of _";
390 return false;
393 // A named type is only identical to itself.
394 if (t1->named_type() != NULL || t2->named_type() != NULL)
395 return false;
397 // Check type shapes.
398 if (t1->classification() != t2->classification())
399 return false;
401 switch (t1->classification())
403 case TYPE_VOID:
404 case TYPE_BOOLEAN:
405 case TYPE_STRING:
406 case TYPE_NIL:
407 // These types are always identical.
408 return true;
410 case TYPE_INTEGER:
411 return t1->integer_type()->is_identical(t2->integer_type());
413 case TYPE_FLOAT:
414 return t1->float_type()->is_identical(t2->float_type());
416 case TYPE_COMPLEX:
417 return t1->complex_type()->is_identical(t2->complex_type());
419 case TYPE_FUNCTION:
420 return t1->function_type()->is_identical(t2->function_type(),
421 false,
422 cmp_tags,
423 errors_are_identical,
424 reason);
426 case TYPE_POINTER:
427 return Type::are_identical_cmp_tags(t1->points_to(), t2->points_to(),
428 cmp_tags, errors_are_identical,
429 reason);
431 case TYPE_STRUCT:
432 return t1->struct_type()->is_identical(t2->struct_type(), cmp_tags,
433 errors_are_identical);
435 case TYPE_ARRAY:
436 return t1->array_type()->is_identical(t2->array_type(), cmp_tags,
437 errors_are_identical);
439 case TYPE_MAP:
440 return t1->map_type()->is_identical(t2->map_type(), cmp_tags,
441 errors_are_identical);
443 case TYPE_CHANNEL:
444 return t1->channel_type()->is_identical(t2->channel_type(), cmp_tags,
445 errors_are_identical);
447 case TYPE_INTERFACE:
448 return t1->interface_type()->is_identical(t2->interface_type(), cmp_tags,
449 errors_are_identical);
451 case TYPE_CALL_MULTIPLE_RESULT:
452 if (reason != NULL)
453 *reason = "invalid use of multiple-value function call";
454 return false;
456 default:
457 go_unreachable();
461 // Return true if it's OK to have a binary operation with types LHS
462 // and RHS. This is not used for shifts or comparisons.
464 bool
465 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
467 if (Type::are_identical(lhs, rhs, true, NULL))
468 return true;
470 // A constant of abstract bool type may be mixed with any bool type.
471 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
472 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
473 return true;
475 // A constant of abstract string type may be mixed with any string
476 // type.
477 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
478 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
479 return true;
481 lhs = lhs->base();
482 rhs = rhs->base();
484 // A constant of abstract integer, float, or complex type may be
485 // mixed with an integer, float, or complex type.
486 if ((rhs->is_abstract()
487 && (rhs->integer_type() != NULL
488 || rhs->float_type() != NULL
489 || rhs->complex_type() != NULL)
490 && (lhs->integer_type() != NULL
491 || lhs->float_type() != NULL
492 || lhs->complex_type() != NULL))
493 || (lhs->is_abstract()
494 && (lhs->integer_type() != NULL
495 || lhs->float_type() != NULL
496 || lhs->complex_type() != NULL)
497 && (rhs->integer_type() != NULL
498 || rhs->float_type() != NULL
499 || rhs->complex_type() != NULL)))
500 return true;
502 // The nil type may be compared to a pointer, an interface type, a
503 // slice type, a channel type, a map type, or a function type.
504 if (lhs->is_nil_type()
505 && (rhs->points_to() != NULL
506 || rhs->interface_type() != NULL
507 || rhs->is_slice_type()
508 || rhs->map_type() != NULL
509 || rhs->channel_type() != NULL
510 || rhs->function_type() != NULL))
511 return true;
512 if (rhs->is_nil_type()
513 && (lhs->points_to() != NULL
514 || lhs->interface_type() != NULL
515 || lhs->is_slice_type()
516 || lhs->map_type() != NULL
517 || lhs->channel_type() != NULL
518 || lhs->function_type() != NULL))
519 return true;
521 return false;
524 // Return true if a value with type T1 may be compared with a value of
525 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
527 bool
528 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
529 const Type *t2, std::string *reason)
531 if (t1 != t2
532 && !Type::are_assignable(t1, t2, NULL)
533 && !Type::are_assignable(t2, t1, NULL))
535 if (reason != NULL)
536 *reason = "incompatible types in binary expression";
537 return false;
540 if (!is_equality_op)
542 if (t1->integer_type() == NULL
543 && t1->float_type() == NULL
544 && !t1->is_string_type())
546 if (reason != NULL)
547 *reason = _("invalid comparison of non-ordered type");
548 return false;
551 else if (t1->is_slice_type()
552 || t1->map_type() != NULL
553 || t1->function_type() != NULL
554 || t2->is_slice_type()
555 || t2->map_type() != NULL
556 || t2->function_type() != NULL)
558 if (!t1->is_nil_type() && !t2->is_nil_type())
560 if (reason != NULL)
562 if (t1->is_slice_type() || t2->is_slice_type())
563 *reason = _("slice can only be compared to nil");
564 else if (t1->map_type() != NULL || t2->map_type() != NULL)
565 *reason = _("map can only be compared to nil");
566 else
567 *reason = _("func can only be compared to nil");
569 // Match 6g error messages.
570 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
572 char buf[200];
573 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
574 reason->c_str());
575 *reason = buf;
578 return false;
581 else
583 if (!t1->is_boolean_type()
584 && t1->integer_type() == NULL
585 && t1->float_type() == NULL
586 && t1->complex_type() == NULL
587 && !t1->is_string_type()
588 && t1->points_to() == NULL
589 && t1->channel_type() == NULL
590 && t1->interface_type() == NULL
591 && t1->struct_type() == NULL
592 && t1->array_type() == NULL
593 && !t1->is_nil_type())
595 if (reason != NULL)
596 *reason = _("invalid comparison of non-comparable type");
597 return false;
600 if (t1->unalias()->named_type() != NULL)
601 return t1->unalias()->named_type()->named_type_is_comparable(reason);
602 else if (t2->unalias()->named_type() != NULL)
603 return t2->unalias()->named_type()->named_type_is_comparable(reason);
604 else if (t1->struct_type() != NULL)
606 if (t1->struct_type()->is_struct_incomparable())
608 if (reason != NULL)
609 *reason = _("invalid comparison of generated struct");
610 return false;
612 const Struct_field_list* fields = t1->struct_type()->fields();
613 for (Struct_field_list::const_iterator p = fields->begin();
614 p != fields->end();
615 ++p)
617 if (!p->type()->is_comparable())
619 if (reason != NULL)
620 *reason = _("invalid comparison of non-comparable struct");
621 return false;
625 else if (t1->array_type() != NULL)
627 if (t1->array_type()->is_array_incomparable())
629 if (reason != NULL)
630 *reason = _("invalid comparison of generated array");
631 return false;
633 if (t1->array_type()->length()->is_nil_expression()
634 || !t1->array_type()->element_type()->is_comparable())
636 if (reason != NULL)
637 *reason = _("invalid comparison of non-comparable array");
638 return false;
643 return true;
646 // Return true if a value with type RHS may be assigned to a variable
647 // with type LHS. If REASON is not NULL, set *REASON to the reason
648 // the types are not assignable.
650 bool
651 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
653 // Do some checks first. Make sure the types are defined.
654 if (rhs != NULL && !rhs->is_undefined())
656 if (rhs->is_void_type())
658 if (reason != NULL)
659 *reason = "non-value used as value";
660 return false;
662 if (rhs->is_call_multiple_result_type())
664 if (reason != NULL)
665 reason->assign(_("multiple-value function call in "
666 "single-value context"));
667 return false;
671 // Any value may be assigned to the blank identifier.
672 if (lhs != NULL
673 && !lhs->is_undefined()
674 && lhs->is_sink_type())
675 return true;
677 // Identical types are assignable.
678 if (Type::are_identical(lhs, rhs, true, reason))
679 return true;
681 // Ignore aliases, except for error messages.
682 const Type* lhs_orig = lhs;
683 const Type* rhs_orig = rhs;
684 lhs = lhs->unalias();
685 rhs = rhs->unalias();
687 // The types are assignable if they have identical underlying types
688 // and either LHS or RHS is not a named type.
689 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
690 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
691 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
692 return true;
694 // The types are assignable if LHS is an interface type and RHS
695 // implements the required methods.
696 const Interface_type* lhs_interface_type = lhs->interface_type();
697 if (lhs_interface_type != NULL)
699 if (lhs_interface_type->implements_interface(rhs, reason))
700 return true;
701 const Interface_type* rhs_interface_type = rhs->interface_type();
702 if (rhs_interface_type != NULL
703 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
704 reason))
705 return true;
708 // The type are assignable if RHS is a bidirectional channel type,
709 // LHS is a channel type, they have identical element types, and
710 // either LHS or RHS is not a named type.
711 if (lhs->channel_type() != NULL
712 && rhs->channel_type() != NULL
713 && rhs->channel_type()->may_send()
714 && rhs->channel_type()->may_receive()
715 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
716 && Type::are_identical(lhs->channel_type()->element_type(),
717 rhs->channel_type()->element_type(),
718 true,
719 reason))
720 return true;
722 // The nil type may be assigned to a pointer, function, slice, map,
723 // channel, or interface type.
724 if (rhs->is_nil_type()
725 && (lhs->points_to() != NULL
726 || lhs->function_type() != NULL
727 || lhs->is_slice_type()
728 || lhs->map_type() != NULL
729 || lhs->channel_type() != NULL
730 || lhs->interface_type() != NULL))
731 return true;
733 // An untyped numeric constant may be assigned to a numeric type if
734 // it is representable in that type.
735 if ((rhs->is_abstract()
736 && (rhs->integer_type() != NULL
737 || rhs->float_type() != NULL
738 || rhs->complex_type() != NULL))
739 && (lhs->integer_type() != NULL
740 || lhs->float_type() != NULL
741 || lhs->complex_type() != NULL))
742 return true;
744 // Give some better error messages.
745 if (reason != NULL && reason->empty())
747 if (rhs->interface_type() != NULL)
748 reason->assign(_("need explicit conversion"));
749 else if (lhs_orig->named_type() != NULL
750 && rhs_orig->named_type() != NULL)
752 size_t len = (lhs_orig->named_type()->name().length()
753 + rhs_orig->named_type()->name().length()
754 + 100);
755 char* buf = new char[len];
756 snprintf(buf, len, _("cannot use type %s as type %s"),
757 rhs_orig->named_type()->message_name().c_str(),
758 lhs_orig->named_type()->message_name().c_str());
759 reason->assign(buf);
760 delete[] buf;
764 return false;
767 // Return true if a value with type RHS may be converted to type LHS.
768 // If REASON is not NULL, set *REASON to the reason the types are not
769 // convertible.
771 bool
772 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
774 // The types are convertible if they are assignable.
775 if (Type::are_assignable(lhs, rhs, reason))
776 return true;
778 // Ignore aliases.
779 lhs = lhs->unalias();
780 rhs = rhs->unalias();
782 // A pointer to a regular type may not be converted to a pointer to
783 // a type that may not live in the heap, except when converting from
784 // unsafe.Pointer.
785 if (lhs->points_to() != NULL
786 && rhs->points_to() != NULL
787 && !lhs->points_to()->in_heap()
788 && rhs->points_to()->in_heap()
789 && !rhs->is_unsafe_pointer_type())
791 if (reason != NULL)
792 reason->assign(_("conversion from normal type to notinheap type"));
793 return false;
796 // The types are convertible if they have identical underlying
797 // types, ignoring struct field tags.
798 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
799 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
800 true, reason))
801 return true;
803 // The types are convertible if they are both unnamed pointer types
804 // and their pointer base types have identical underlying types,
805 // ignoring struct field tags.
806 if (lhs->named_type() == NULL
807 && rhs->named_type() == NULL
808 && lhs->points_to() != NULL
809 && rhs->points_to() != NULL
810 && (lhs->points_to()->named_type() != NULL
811 || rhs->points_to()->named_type() != NULL)
812 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
813 rhs->points_to()->base(),
814 IGNORE_TAGS,
815 true,
816 reason))
817 return true;
819 // Integer and floating point types are convertible to each other.
820 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
821 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
822 return true;
824 // Complex types are convertible to each other.
825 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
826 return true;
828 // An integer, or []byte, or []rune, may be converted to a string.
829 if (lhs->is_string_type())
831 if (rhs->integer_type() != NULL)
832 return true;
833 if (rhs->is_slice_type())
835 const Type* e = rhs->array_type()->element_type()->forwarded();
836 if (e->integer_type() != NULL
837 && (e->integer_type()->is_byte()
838 || e->integer_type()->is_rune()))
839 return true;
843 // A string may be converted to []byte or []rune.
844 if (rhs->is_string_type() && lhs->is_slice_type())
846 const Type* e = lhs->array_type()->element_type()->forwarded();
847 if (e->integer_type() != NULL
848 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
849 return true;
852 // An unsafe.Pointer type may be converted to any pointer type or to
853 // a type whose underlying type is uintptr, and vice-versa.
854 if (lhs->is_unsafe_pointer_type()
855 && (rhs->points_to() != NULL
856 || (rhs->integer_type() != NULL
857 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
858 return true;
859 if (rhs->is_unsafe_pointer_type()
860 && (lhs->points_to() != NULL
861 || (lhs->integer_type() != NULL
862 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
863 return true;
865 // Give a better error message.
866 if (reason != NULL)
868 if (reason->empty())
869 *reason = "invalid type conversion";
870 else
872 std::string s = "invalid type conversion (";
873 s += *reason;
874 s += ')';
875 *reason = s;
879 return false;
882 // Copy expressions if it may change the size.
884 // The only type that has an expression is an array type. The only
885 // types whose size can be changed by the size of an array type are an
886 // array type itself, or a struct type with an array field.
887 Type*
888 Type::copy_expressions()
890 // This is run during parsing, so types may not be valid yet.
891 // We only have to worry about array type literals.
892 switch (this->classification_)
894 default:
895 return this;
897 case TYPE_ARRAY:
899 Array_type* at = this->array_type();
900 if (at->length() == NULL)
901 return this;
902 Expression* len = at->length()->copy();
903 if (at->length() == len)
904 return this;
905 return Type::make_array_type(at->element_type(), len);
908 case TYPE_STRUCT:
910 Struct_type* st = this->struct_type();
911 const Struct_field_list* sfl = st->fields();
912 if (sfl == NULL)
913 return this;
914 bool changed = false;
915 Struct_field_list *nsfl = new Struct_field_list();
916 for (Struct_field_list::const_iterator pf = sfl->begin();
917 pf != sfl->end();
918 ++pf)
920 Type* ft = pf->type()->copy_expressions();
921 Struct_field nf(Typed_identifier((pf->is_anonymous()
922 ? ""
923 : pf->field_name()),
925 pf->location()));
926 if (pf->has_tag())
927 nf.set_tag(pf->tag());
928 nsfl->push_back(nf);
929 if (ft != pf->type())
930 changed = true;
932 if (!changed)
934 delete(nsfl);
935 return this;
937 return Type::make_struct_type(nsfl, st->location());
941 go_unreachable();
944 // Return a hash code for the type to be used for method lookup.
946 unsigned int
947 Type::hash_for_method(Gogo* gogo) const
949 if (this->named_type() != NULL && this->named_type()->is_alias())
950 return this->named_type()->real_type()->hash_for_method(gogo);
951 unsigned int ret = 0;
952 if (this->classification_ != TYPE_FORWARD)
953 ret += this->classification_;
954 return ret + this->do_hash_for_method(gogo);
957 // Default implementation of do_hash_for_method. This is appropriate
958 // for types with no subfields.
960 unsigned int
961 Type::do_hash_for_method(Gogo*) const
963 return 0;
966 // Return a hash code for a string, given a starting hash.
968 unsigned int
969 Type::hash_string(const std::string& s, unsigned int h)
971 const char* p = s.data();
972 size_t len = s.length();
973 for (; len > 0; --len)
975 h ^= *p++;
976 h*= 16777619;
978 return h;
981 // A hash table mapping unnamed types to the backend representation of
982 // those types.
984 Type::Type_btypes Type::type_btypes;
986 // Return the backend representation for this type.
988 Btype*
989 Type::get_backend(Gogo* gogo)
991 if (this->btype_ != NULL)
992 return this->btype_;
994 if (this->forward_declaration_type() != NULL
995 || this->named_type() != NULL)
996 return this->get_btype_without_hash(gogo);
998 if (this->is_error_type())
999 return gogo->backend()->error_type();
1001 // To avoid confusing the backend, translate all identical Go types
1002 // to the same backend representation. We use a hash table to do
1003 // that. There is no need to use the hash table for named types, as
1004 // named types are only identical to themselves.
1006 std::pair<Type*, Type_btype_entry> val;
1007 val.first = this;
1008 val.second.btype = NULL;
1009 val.second.is_placeholder = false;
1010 std::pair<Type_btypes::iterator, bool> ins =
1011 Type::type_btypes.insert(val);
1012 if (!ins.second && ins.first->second.btype != NULL)
1014 // Note that GOGO can be NULL here, but only when the GCC
1015 // middle-end is asking for a frontend type. That will only
1016 // happen for simple types, which should never require
1017 // placeholders.
1018 if (!ins.first->second.is_placeholder)
1019 this->btype_ = ins.first->second.btype;
1020 else if (gogo->named_types_are_converted())
1022 this->finish_backend(gogo, ins.first->second.btype);
1023 ins.first->second.is_placeholder = false;
1026 return ins.first->second.btype;
1029 Btype* bt = this->get_btype_without_hash(gogo);
1031 if (ins.first->second.btype == NULL)
1033 ins.first->second.btype = bt;
1034 ins.first->second.is_placeholder = false;
1036 else
1038 // We have already created a backend representation for this
1039 // type. This can happen when an unnamed type is defined using
1040 // a named type which in turns uses an identical unnamed type.
1041 // Use the representation we created earlier and ignore the one we just
1042 // built.
1043 if (this->btype_ == bt)
1044 this->btype_ = ins.first->second.btype;
1045 bt = ins.first->second.btype;
1048 return bt;
1051 // Return the backend representation for a type without looking in the
1052 // hash table for identical types. This is used for named types,
1053 // since a named type is never identical to any other type.
1055 Btype*
1056 Type::get_btype_without_hash(Gogo* gogo)
1058 if (this->btype_ == NULL)
1060 Btype* bt = this->do_get_backend(gogo);
1062 // For a recursive function or pointer type, we will temporarily
1063 // return a circular pointer type during the recursion. We
1064 // don't want to record that for a forwarding type, as it may
1065 // confuse us later.
1066 if (this->forward_declaration_type() != NULL
1067 && gogo->backend()->is_circular_pointer_type(bt))
1068 return bt;
1070 if (gogo == NULL || !gogo->named_types_are_converted())
1071 return bt;
1073 this->btype_ = bt;
1075 return this->btype_;
1078 // Get the backend representation of a type without forcing the
1079 // creation of the backend representation of all supporting types.
1080 // This will return a backend type that has the correct size but may
1081 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1082 // and will not contain the final representation of the type to which
1083 // it points. This is used while converting all named types to the
1084 // backend representation, to avoid problems with indirect references
1085 // to types which are not yet complete. When this is called, the
1086 // sizes of all direct references (e.g., a struct field) should be
1087 // known, but the sizes of indirect references (e.g., the type to
1088 // which a pointer points) may not.
1090 Btype*
1091 Type::get_backend_placeholder(Gogo* gogo)
1093 if (gogo->named_types_are_converted())
1094 return this->get_backend(gogo);
1095 if (this->btype_ != NULL)
1096 return this->btype_;
1098 Btype* bt;
1099 switch (this->classification_)
1101 case TYPE_ERROR:
1102 case TYPE_VOID:
1103 case TYPE_BOOLEAN:
1104 case TYPE_INTEGER:
1105 case TYPE_FLOAT:
1106 case TYPE_COMPLEX:
1107 case TYPE_STRING:
1108 case TYPE_NIL:
1109 // These are simple types that can just be created directly.
1110 return this->get_backend(gogo);
1112 case TYPE_MAP:
1113 case TYPE_CHANNEL:
1114 // All maps and channels have the same backend representation.
1115 return this->get_backend(gogo);
1117 case TYPE_NAMED:
1118 case TYPE_FORWARD:
1119 // Named types keep track of their own dependencies and manage
1120 // their own placeholders.
1121 return this->get_backend(gogo);
1123 case TYPE_INTERFACE:
1124 if (this->interface_type()->is_empty())
1125 return Interface_type::get_backend_empty_interface_type(gogo);
1126 break;
1128 default:
1129 break;
1132 std::pair<Type*, Type_btype_entry> val;
1133 val.first = this;
1134 val.second.btype = NULL;
1135 val.second.is_placeholder = false;
1136 std::pair<Type_btypes::iterator, bool> ins =
1137 Type::type_btypes.insert(val);
1138 if (!ins.second && ins.first->second.btype != NULL)
1139 return ins.first->second.btype;
1141 switch (this->classification_)
1143 case TYPE_FUNCTION:
1145 // A Go function type is a pointer to a struct type.
1146 Location loc = this->function_type()->location();
1147 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1149 break;
1151 case TYPE_POINTER:
1153 Location loc = Linemap::unknown_location();
1154 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1155 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1156 Type::placeholder_pointers.push_back(pt);
1158 break;
1160 case TYPE_STRUCT:
1161 // We don't have to make the struct itself be a placeholder. We
1162 // are promised that we know the sizes of the struct fields.
1163 // But we may have to use a placeholder for any particular
1164 // struct field.
1166 std::vector<Backend::Btyped_identifier> bfields;
1167 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1168 true, &bfields);
1169 bt = gogo->backend()->struct_type(bfields);
1171 break;
1173 case TYPE_ARRAY:
1174 if (this->is_slice_type())
1176 std::vector<Backend::Btyped_identifier> bfields;
1177 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1178 bt = gogo->backend()->struct_type(bfields);
1180 else
1182 Btype* element = this->array_type()->get_backend_element(gogo, true);
1183 Bexpression* len = this->array_type()->get_backend_length(gogo);
1184 bt = gogo->backend()->array_type(element, len);
1186 break;
1188 case TYPE_INTERFACE:
1190 go_assert(!this->interface_type()->is_empty());
1191 std::vector<Backend::Btyped_identifier> bfields;
1192 get_backend_interface_fields(gogo, this->interface_type(), true,
1193 &bfields);
1194 bt = gogo->backend()->struct_type(bfields);
1196 break;
1198 case TYPE_SINK:
1199 case TYPE_CALL_MULTIPLE_RESULT:
1200 /* Note that various classifications were handled in the earlier
1201 switch. */
1202 default:
1203 go_unreachable();
1206 if (ins.first->second.btype == NULL)
1208 ins.first->second.btype = bt;
1209 ins.first->second.is_placeholder = true;
1211 else
1213 // A placeholder for this type got created along the way. Use
1214 // that one and ignore the one we just built.
1215 bt = ins.first->second.btype;
1218 return bt;
1221 // Complete the backend representation. This is called for a type
1222 // using a placeholder type.
1224 void
1225 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1227 switch (this->classification_)
1229 case TYPE_ERROR:
1230 case TYPE_VOID:
1231 case TYPE_BOOLEAN:
1232 case TYPE_INTEGER:
1233 case TYPE_FLOAT:
1234 case TYPE_COMPLEX:
1235 case TYPE_STRING:
1236 case TYPE_NIL:
1237 go_unreachable();
1239 case TYPE_FUNCTION:
1241 Btype* bt = this->do_get_backend(gogo);
1242 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1243 go_assert(saw_errors());
1245 break;
1247 case TYPE_POINTER:
1249 Btype* bt = this->do_get_backend(gogo);
1250 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1251 go_assert(saw_errors());
1253 break;
1255 case TYPE_STRUCT:
1256 // The struct type itself is done, but we have to make sure that
1257 // all the field types are converted.
1258 this->struct_type()->finish_backend_fields(gogo);
1259 break;
1261 case TYPE_ARRAY:
1262 // The array type itself is done, but make sure the element type
1263 // is converted.
1264 this->array_type()->finish_backend_element(gogo);
1265 break;
1267 case TYPE_MAP:
1268 case TYPE_CHANNEL:
1269 go_unreachable();
1271 case TYPE_INTERFACE:
1272 // The interface type itself is done, but make sure the method
1273 // types are converted.
1274 this->interface_type()->finish_backend_methods(gogo);
1275 break;
1277 case TYPE_NAMED:
1278 case TYPE_FORWARD:
1279 go_unreachable();
1281 case TYPE_SINK:
1282 case TYPE_CALL_MULTIPLE_RESULT:
1283 default:
1284 go_unreachable();
1287 this->btype_ = placeholder;
1290 // Return a pointer to the type descriptor for this type.
1292 Bexpression*
1293 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1295 Type* t = this->unalias();
1296 if (t->type_descriptor_var_ == NULL)
1298 t->make_type_descriptor_var(gogo);
1299 go_assert(t->type_descriptor_var_ != NULL);
1301 Bexpression* var_expr =
1302 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1303 Bexpression* var_addr =
1304 gogo->backend()->address_expression(var_expr, location);
1305 Type* td_type = Type::make_type_descriptor_type();
1306 Btype* td_btype = td_type->get_backend(gogo);
1307 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1308 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1311 // A mapping from unnamed types to type descriptor variables.
1313 Type::Type_descriptor_vars Type::type_descriptor_vars;
1315 // Build the type descriptor for this type.
1317 void
1318 Type::make_type_descriptor_var(Gogo* gogo)
1320 go_assert(this->type_descriptor_var_ == NULL);
1322 Named_type* nt = this->named_type();
1324 // We can have multiple instances of unnamed types, but we only want
1325 // to emit the type descriptor once. We use a hash table. This is
1326 // not necessary for named types, as they are unique, and we store
1327 // the type descriptor in the type itself.
1328 Bvariable** phash = NULL;
1329 if (nt == NULL)
1331 Bvariable* bvnull = NULL;
1332 std::pair<Type_descriptor_vars::iterator, bool> ins =
1333 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1334 if (!ins.second)
1336 // We've already built a type descriptor for this type.
1337 this->type_descriptor_var_ = ins.first->second;
1338 return;
1340 phash = &ins.first->second;
1343 // The type descriptor symbol for the unsafe.Pointer type is defined in
1344 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1345 // symbol if necessary.
1346 if (this->is_unsafe_pointer_type())
1348 Location bloc = Linemap::predeclared_location();
1350 Type* td_type = Type::make_type_descriptor_type();
1351 Btype* td_btype = td_type->get_backend(gogo);
1352 std::string name = gogo->type_descriptor_name(this, nt);
1353 std::string asm_name(go_selectively_encode_id(name));
1354 this->type_descriptor_var_ =
1355 gogo->backend()->immutable_struct_reference(name, asm_name,
1356 td_btype,
1357 bloc);
1359 if (phash != NULL)
1360 *phash = this->type_descriptor_var_;
1361 return;
1364 std::string var_name = gogo->type_descriptor_name(this, nt);
1366 // Build the contents of the type descriptor.
1367 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1369 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1371 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1373 const Package* dummy;
1374 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1376 std::string asm_name(go_selectively_encode_id(var_name));
1377 this->type_descriptor_var_ =
1378 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1379 initializer_btype,
1380 loc);
1381 if (phash != NULL)
1382 *phash = this->type_descriptor_var_;
1383 return;
1386 // See if this type descriptor can appear in multiple packages.
1387 bool is_common = false;
1388 if (nt != NULL)
1390 // We create the descriptor for a builtin type whenever we need
1391 // it.
1392 is_common = nt->is_builtin();
1394 else
1396 // This is an unnamed type. The descriptor could be defined in
1397 // any package where it is needed, and the linker will pick one
1398 // descriptor to keep.
1399 is_common = true;
1402 // We are going to build the type descriptor in this package. We
1403 // must create the variable before we convert the initializer to the
1404 // backend representation, because the initializer may refer to the
1405 // type descriptor of this type. By setting type_descriptor_var_ we
1406 // ensure that type_descriptor_pointer will work if called while
1407 // converting INITIALIZER.
1409 std::string asm_name(go_selectively_encode_id(var_name));
1410 this->type_descriptor_var_ =
1411 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1412 initializer_btype, loc);
1413 if (phash != NULL)
1414 *phash = this->type_descriptor_var_;
1416 Translate_context context(gogo, NULL, NULL, NULL);
1417 context.set_is_const();
1418 Bexpression* binitializer = initializer->get_backend(&context);
1420 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1421 var_name, false, is_common,
1422 initializer_btype, loc,
1423 binitializer);
1426 // Return true if this type descriptor is defined in a different
1427 // package. If this returns true it sets *PACKAGE to the package.
1429 bool
1430 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1431 const Package** package)
1433 if (nt != NULL)
1435 if (nt->named_object()->package() != NULL)
1437 // This is a named type defined in a different package. The
1438 // type descriptor should be defined in that package.
1439 *package = nt->named_object()->package();
1440 return true;
1443 else
1445 if (this->points_to() != NULL
1446 && this->points_to()->named_type() != NULL
1447 && this->points_to()->named_type()->named_object()->package() != NULL)
1449 // This is an unnamed pointer to a named type defined in a
1450 // different package. The descriptor should be defined in
1451 // that package.
1452 *package = this->points_to()->named_type()->named_object()->package();
1453 return true;
1456 return false;
1459 // Return a composite literal for a type descriptor.
1461 Expression*
1462 Type::type_descriptor(Gogo* gogo, Type* type)
1464 return type->do_type_descriptor(gogo, NULL);
1467 // Return a composite literal for a type descriptor with a name.
1469 Expression*
1470 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1472 go_assert(name != NULL && type->named_type() != name);
1473 return type->do_type_descriptor(gogo, name);
1476 // Make a builtin struct type from a list of fields. The fields are
1477 // pairs of a name and a type.
1479 Struct_type*
1480 Type::make_builtin_struct_type(int nfields, ...)
1482 va_list ap;
1483 va_start(ap, nfields);
1485 Location bloc = Linemap::predeclared_location();
1486 Struct_field_list* sfl = new Struct_field_list();
1487 for (int i = 0; i < nfields; i++)
1489 const char* field_name = va_arg(ap, const char *);
1490 Type* type = va_arg(ap, Type*);
1491 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1494 va_end(ap);
1496 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1497 ret->set_is_struct_incomparable();
1498 return ret;
1501 // A list of builtin named types.
1503 std::vector<Named_type*> Type::named_builtin_types;
1505 // Make a builtin named type.
1507 Named_type*
1508 Type::make_builtin_named_type(const char* name, Type* type)
1510 Location bloc = Linemap::predeclared_location();
1511 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1512 Named_type* ret = no->type_value();
1513 Type::named_builtin_types.push_back(ret);
1514 return ret;
1517 // Convert the named builtin types.
1519 void
1520 Type::convert_builtin_named_types(Gogo* gogo)
1522 for (std::vector<Named_type*>::const_iterator p =
1523 Type::named_builtin_types.begin();
1524 p != Type::named_builtin_types.end();
1525 ++p)
1527 bool r = (*p)->verify();
1528 go_assert(r);
1529 (*p)->convert(gogo);
1533 // Return the type of a type descriptor. We should really tie this to
1534 // runtime.Type rather than copying it. This must match the struct "_type"
1535 // declared in libgo/go/runtime/type.go.
1537 Type*
1538 Type::make_type_descriptor_type()
1540 static Type* ret;
1541 if (ret == NULL)
1543 Location bloc = Linemap::predeclared_location();
1545 Type* uint8_type = Type::lookup_integer_type("uint8");
1546 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1547 Type* uint32_type = Type::lookup_integer_type("uint32");
1548 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1549 Type* string_type = Type::lookup_string_type();
1550 Type* pointer_string_type = Type::make_pointer_type(string_type);
1552 // This is an unnamed version of unsafe.Pointer. Perhaps we
1553 // should use the named version instead, although that would
1554 // require us to create the unsafe package if it has not been
1555 // imported. It probably doesn't matter.
1556 Type* void_type = Type::make_void_type();
1557 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1559 Typed_identifier_list *params = new Typed_identifier_list();
1560 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1561 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1563 Typed_identifier_list* results = new Typed_identifier_list();
1564 results->push_back(Typed_identifier("", uintptr_type, bloc));
1566 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1567 bloc);
1569 params = new Typed_identifier_list();
1570 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1571 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1573 results = new Typed_identifier_list();
1574 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1576 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1577 bloc);
1579 // Forward declaration for the type descriptor type.
1580 Named_object* named_type_descriptor_type =
1581 Named_object::make_type_declaration("_type", NULL, bloc);
1582 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1583 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1585 // The type of a method on a concrete type.
1586 Struct_type* method_type =
1587 Type::make_builtin_struct_type(5,
1588 "name", pointer_string_type,
1589 "pkgPath", pointer_string_type,
1590 "mtyp", pointer_type_descriptor_type,
1591 "typ", pointer_type_descriptor_type,
1592 "tfn", unsafe_pointer_type);
1593 Named_type* named_method_type =
1594 Type::make_builtin_named_type("method", method_type);
1596 // Information for types with a name or methods.
1597 Type* slice_named_method_type =
1598 Type::make_array_type(named_method_type, NULL);
1599 Struct_type* uncommon_type =
1600 Type::make_builtin_struct_type(3,
1601 "name", pointer_string_type,
1602 "pkgPath", pointer_string_type,
1603 "methods", slice_named_method_type);
1604 Named_type* named_uncommon_type =
1605 Type::make_builtin_named_type("uncommonType", uncommon_type);
1607 Type* pointer_uncommon_type =
1608 Type::make_pointer_type(named_uncommon_type);
1610 // The type descriptor type.
1612 Struct_type* type_descriptor_type =
1613 Type::make_builtin_struct_type(12,
1614 "size", uintptr_type,
1615 "ptrdata", uintptr_type,
1616 "hash", uint32_type,
1617 "kind", uint8_type,
1618 "align", uint8_type,
1619 "fieldAlign", uint8_type,
1620 "hashfn", hash_fntype,
1621 "equalfn", equal_fntype,
1622 "gcdata", pointer_uint8_type,
1623 "string", pointer_string_type,
1624 "", pointer_uncommon_type,
1625 "ptrToThis",
1626 pointer_type_descriptor_type);
1628 Named_type* named = Type::make_builtin_named_type("_type",
1629 type_descriptor_type);
1631 named_type_descriptor_type->set_type_value(named);
1633 ret = named;
1636 return ret;
1639 // Make the type of a pointer to a type descriptor as represented in
1640 // Go.
1642 Type*
1643 Type::make_type_descriptor_ptr_type()
1645 static Type* ret;
1646 if (ret == NULL)
1647 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1648 return ret;
1651 // Return the alignment required by the memequalN function. N is a
1652 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1653 // in libgo/go/runtime/alg.go.
1655 int64_t
1656 Type::memequal_align(Gogo* gogo, int size)
1658 const char* tn;
1659 switch (size)
1661 case 16:
1662 tn = "int16";
1663 break;
1664 case 32:
1665 tn = "int32";
1666 break;
1667 case 64:
1668 tn = "int64";
1669 break;
1670 case 128:
1671 // The code uses [2]int64, which must have the same alignment as
1672 // int64.
1673 tn = "int64";
1674 break;
1675 default:
1676 go_unreachable();
1679 Type* t = Type::lookup_integer_type(tn);
1681 int64_t ret;
1682 if (!t->backend_type_align(gogo, &ret))
1683 go_unreachable();
1684 return ret;
1687 // Return whether this type needs specially built type functions.
1688 // This returns true for types that are comparable and either can not
1689 // use an identity comparison, or are a non-standard size.
1691 bool
1692 Type::needs_specific_type_functions(Gogo* gogo)
1694 Named_type* nt = this->named_type();
1695 if (nt != NULL && nt->is_alias())
1696 return false;
1697 if (!this->is_comparable())
1698 return false;
1699 if (!this->compare_is_identity(gogo))
1700 return true;
1702 // We create a few predeclared types for type descriptors; they are
1703 // really just for the backend and don't need hash or equality
1704 // functions.
1705 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1706 return false;
1708 int64_t size, align;
1709 if (!this->backend_type_size(gogo, &size)
1710 || !this->backend_type_align(gogo, &align))
1712 go_assert(saw_errors());
1713 return false;
1715 // This switch matches the one in Type::type_functions.
1716 switch (size)
1718 case 0:
1719 case 1:
1720 case 2:
1721 return align < Type::memequal_align(gogo, 16);
1722 case 4:
1723 return align < Type::memequal_align(gogo, 32);
1724 case 8:
1725 return align < Type::memequal_align(gogo, 64);
1726 case 16:
1727 return align < Type::memequal_align(gogo, 128);
1728 default:
1729 return true;
1733 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1734 // hash code for this type and which compare whether two values of
1735 // this type are equal. If NAME is not NULL it is the name of this
1736 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1737 // functions, for convenience; they may be NULL.
1739 void
1740 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1741 Function_type* equal_fntype, Named_object** hash_fn,
1742 Named_object** equal_fn)
1744 // If the unaliased type is not a named type, then the type does not
1745 // have a name after all.
1746 if (name != NULL)
1747 name = name->unalias()->named_type();
1749 if (!this->is_comparable())
1751 *hash_fn = NULL;
1752 *equal_fn = NULL;
1753 return;
1756 if (hash_fntype == NULL || equal_fntype == NULL)
1758 Location bloc = Linemap::predeclared_location();
1760 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1761 Type* void_type = Type::make_void_type();
1762 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1764 if (hash_fntype == NULL)
1766 Typed_identifier_list* params = new Typed_identifier_list();
1767 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1768 bloc));
1769 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1771 Typed_identifier_list* results = new Typed_identifier_list();
1772 results->push_back(Typed_identifier("", uintptr_type, bloc));
1774 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1776 if (equal_fntype == NULL)
1778 Typed_identifier_list* params = new Typed_identifier_list();
1779 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1780 bloc));
1781 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1782 bloc));
1784 Typed_identifier_list* results = new Typed_identifier_list();
1785 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1786 bloc));
1788 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1792 const char* hash_fnname;
1793 const char* equal_fnname;
1794 if (this->compare_is_identity(gogo))
1796 int64_t size, align;
1797 if (!this->backend_type_size(gogo, &size)
1798 || !this->backend_type_align(gogo, &align))
1800 go_assert(saw_errors());
1801 return;
1803 bool build_functions = false;
1804 // This switch matches the one in Type::needs_specific_type_functions.
1805 // The alignment tests are because of the memequal functions,
1806 // which assume that the values are aligned as required for an
1807 // integer of that size.
1808 switch (size)
1810 case 0:
1811 hash_fnname = "runtime.memhash0";
1812 equal_fnname = "runtime.memequal0";
1813 break;
1814 case 1:
1815 hash_fnname = "runtime.memhash8";
1816 equal_fnname = "runtime.memequal8";
1817 break;
1818 case 2:
1819 if (align < Type::memequal_align(gogo, 16))
1820 build_functions = true;
1821 else
1823 hash_fnname = "runtime.memhash16";
1824 equal_fnname = "runtime.memequal16";
1826 break;
1827 case 4:
1828 if (align < Type::memequal_align(gogo, 32))
1829 build_functions = true;
1830 else
1832 hash_fnname = "runtime.memhash32";
1833 equal_fnname = "runtime.memequal32";
1835 break;
1836 case 8:
1837 if (align < Type::memequal_align(gogo, 64))
1838 build_functions = true;
1839 else
1841 hash_fnname = "runtime.memhash64";
1842 equal_fnname = "runtime.memequal64";
1844 break;
1845 case 16:
1846 if (align < Type::memequal_align(gogo, 128))
1847 build_functions = true;
1848 else
1850 hash_fnname = "runtime.memhash128";
1851 equal_fnname = "runtime.memequal128";
1853 break;
1854 default:
1855 build_functions = true;
1856 break;
1858 if (build_functions)
1860 // We don't have a built-in function for a type of this size
1861 // and alignment. Build a function to use that calls the
1862 // generic hash/equality functions for identity, passing the size.
1863 this->specific_type_functions(gogo, name, size, hash_fntype,
1864 equal_fntype, hash_fn, equal_fn);
1865 return;
1868 else
1870 switch (this->base()->classification())
1872 case Type::TYPE_ERROR:
1873 case Type::TYPE_VOID:
1874 case Type::TYPE_NIL:
1875 case Type::TYPE_FUNCTION:
1876 case Type::TYPE_MAP:
1877 // For these types is_comparable should have returned false.
1878 go_unreachable();
1880 case Type::TYPE_BOOLEAN:
1881 case Type::TYPE_INTEGER:
1882 case Type::TYPE_POINTER:
1883 case Type::TYPE_CHANNEL:
1884 // For these types compare_is_identity should have returned true.
1885 go_unreachable();
1887 case Type::TYPE_FLOAT:
1888 switch (this->float_type()->bits())
1890 case 32:
1891 hash_fnname = "runtime.f32hash";
1892 equal_fnname = "runtime.f32equal";
1893 break;
1894 case 64:
1895 hash_fnname = "runtime.f64hash";
1896 equal_fnname = "runtime.f64equal";
1897 break;
1898 default:
1899 go_unreachable();
1901 break;
1903 case Type::TYPE_COMPLEX:
1904 switch (this->complex_type()->bits())
1906 case 64:
1907 hash_fnname = "runtime.c64hash";
1908 equal_fnname = "runtime.c64equal";
1909 break;
1910 case 128:
1911 hash_fnname = "runtime.c128hash";
1912 equal_fnname = "runtime.c128equal";
1913 break;
1914 default:
1915 go_unreachable();
1917 break;
1919 case Type::TYPE_STRING:
1920 hash_fnname = "runtime.strhash";
1921 equal_fnname = "runtime.strequal";
1922 break;
1924 case Type::TYPE_STRUCT:
1926 // This is a struct which can not be compared using a
1927 // simple identity function. We need to build a function
1928 // for comparison.
1929 this->specific_type_functions(gogo, name, -1, hash_fntype,
1930 equal_fntype, hash_fn, equal_fn);
1931 return;
1934 case Type::TYPE_ARRAY:
1935 if (this->is_slice_type())
1937 // Type::is_compatible_for_comparison should have
1938 // returned false.
1939 go_unreachable();
1941 else
1943 // This is an array which can not be compared using a
1944 // simple identity function. We need to build a
1945 // function for comparison.
1946 this->specific_type_functions(gogo, name, -1, hash_fntype,
1947 equal_fntype, hash_fn, equal_fn);
1948 return;
1950 break;
1952 case Type::TYPE_INTERFACE:
1953 if (this->interface_type()->is_empty())
1955 hash_fnname = "runtime.nilinterhash";
1956 equal_fnname = "runtime.nilinterequal";
1958 else
1960 hash_fnname = "runtime.interhash";
1961 equal_fnname = "runtime.interequal";
1963 break;
1965 case Type::TYPE_NAMED:
1966 case Type::TYPE_FORWARD:
1967 go_unreachable();
1969 default:
1970 go_unreachable();
1975 Location bloc = Linemap::predeclared_location();
1976 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1977 hash_fntype, bloc);
1978 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1979 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1980 equal_fntype, bloc);
1981 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1984 // A hash table mapping types to the specific hash functions.
1986 Type::Type_functions Type::type_functions_table;
1988 // Handle a type function which is specific to a type: if SIZE == -1,
1989 // this is a struct or array that can not use an identity comparison.
1990 // Otherwise, it is a type that uses an identity comparison but is not
1991 // one of the standard supported sizes.
1993 void
1994 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1995 Function_type* hash_fntype,
1996 Function_type* equal_fntype,
1997 Named_object** hash_fn,
1998 Named_object** equal_fn)
2000 Hash_equal_fn fnull(NULL, NULL);
2001 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
2002 std::pair<Type_functions::iterator, bool> ins =
2003 Type::type_functions_table.insert(val);
2004 if (!ins.second)
2006 // We already have functions for this type
2007 *hash_fn = ins.first->second.first;
2008 *equal_fn = ins.first->second.second;
2009 return;
2012 std::string hash_name;
2013 std::string equal_name;
2014 gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
2016 Location bloc = Linemap::predeclared_location();
2018 const Package* package = NULL;
2019 bool is_defined_elsewhere =
2020 this->type_descriptor_defined_elsewhere(name, &package);
2021 if (is_defined_elsewhere)
2023 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2024 hash_fntype, bloc);
2025 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2026 equal_fntype, bloc);
2028 else
2030 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2031 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2032 bloc);
2035 ins.first->second.first = *hash_fn;
2036 ins.first->second.second = *equal_fn;
2038 if (!is_defined_elsewhere)
2040 if (gogo->in_global_scope())
2041 this->write_specific_type_functions(gogo, name, size, hash_name,
2042 hash_fntype, equal_name,
2043 equal_fntype);
2044 else
2045 gogo->queue_specific_type_function(this, name, size, hash_name,
2046 hash_fntype, equal_name,
2047 equal_fntype);
2051 // Write the hash and equality functions for a type which needs to be
2052 // written specially.
2054 void
2055 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2056 const std::string& hash_name,
2057 Function_type* hash_fntype,
2058 const std::string& equal_name,
2059 Function_type* equal_fntype)
2061 Location bloc = Linemap::predeclared_location();
2063 if (gogo->specific_type_functions_are_written())
2065 go_assert(saw_errors());
2066 return;
2069 go_assert(this->is_comparable());
2071 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2072 bloc);
2073 hash_fn->func_value()->set_is_type_specific_function();
2074 gogo->start_block(bloc);
2076 if (size != -1)
2077 this->write_identity_hash(gogo, size);
2078 else if (name != NULL && name->real_type()->named_type() != NULL)
2079 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2080 else if (this->struct_type() != NULL)
2081 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2082 equal_fntype);
2083 else if (this->array_type() != NULL)
2084 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2085 equal_fntype);
2086 else
2087 go_unreachable();
2089 Block* b = gogo->finish_block(bloc);
2090 gogo->add_block(b, bloc);
2091 gogo->lower_block(hash_fn, b);
2092 gogo->finish_function(bloc);
2094 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2095 false, bloc);
2096 equal_fn->func_value()->set_is_type_specific_function();
2097 gogo->start_block(bloc);
2099 if (size != -1)
2100 this->write_identity_equal(gogo, size);
2101 else if (name != NULL && name->real_type()->named_type() != NULL)
2102 this->write_named_equal(gogo, name);
2103 else if (this->struct_type() != NULL)
2104 this->struct_type()->write_equal_function(gogo, name);
2105 else if (this->array_type() != NULL)
2106 this->array_type()->write_equal_function(gogo, name);
2107 else
2108 go_unreachable();
2110 b = gogo->finish_block(bloc);
2111 gogo->add_block(b, bloc);
2112 gogo->lower_block(equal_fn, b);
2113 gogo->finish_function(bloc);
2115 // Build the function descriptors for the type descriptor to refer to.
2116 hash_fn->func_value()->descriptor(gogo, hash_fn);
2117 equal_fn->func_value()->descriptor(gogo, equal_fn);
2120 // Write a hash function for a type that can use an identity hash but
2121 // is not one of the standard supported sizes. For example, this
2122 // would be used for the type [3]byte. This builds a return statement
2123 // that returns a call to the memhash function, passing the key and
2124 // seed from the function arguments (already constructed before this
2125 // is called), and the constant size.
2127 void
2128 Type::write_identity_hash(Gogo* gogo, int64_t size)
2130 Location bloc = Linemap::predeclared_location();
2132 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2133 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2135 Typed_identifier_list* params = new Typed_identifier_list();
2136 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2137 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2138 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2140 Typed_identifier_list* results = new Typed_identifier_list();
2141 results->push_back(Typed_identifier("", uintptr_type, bloc));
2143 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2144 results, bloc);
2146 Named_object* memhash =
2147 Named_object::make_function_declaration("runtime.memhash", NULL,
2148 memhash_fntype, bloc);
2149 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2151 Named_object* key_arg = gogo->lookup("key", NULL);
2152 go_assert(key_arg != NULL);
2153 Named_object* seed_arg = gogo->lookup("seed", NULL);
2154 go_assert(seed_arg != NULL);
2156 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2157 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2158 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2159 bloc);
2160 Expression_list* args = new Expression_list();
2161 args->push_back(key_ref);
2162 args->push_back(seed_ref);
2163 args->push_back(size_arg);
2164 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2165 Expression* call = Expression::make_call(func, args, false, bloc);
2167 Expression_list* vals = new Expression_list();
2168 vals->push_back(call);
2169 Statement* s = Statement::make_return_statement(vals, bloc);
2170 gogo->add_statement(s);
2173 // Write an equality function for a type that can use an identity
2174 // equality comparison but is not one of the standard supported sizes.
2175 // For example, this would be used for the type [3]byte. This builds
2176 // a return statement that returns a call to the memequal function,
2177 // passing the two keys from the function arguments (already
2178 // constructed before this is called), and the constant size.
2180 void
2181 Type::write_identity_equal(Gogo* gogo, int64_t size)
2183 Location bloc = Linemap::predeclared_location();
2185 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2186 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2188 Typed_identifier_list* params = new Typed_identifier_list();
2189 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2190 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2191 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2193 Typed_identifier_list* results = new Typed_identifier_list();
2194 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2196 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2197 results, bloc);
2199 Named_object* memequal =
2200 Named_object::make_function_declaration("runtime.memequal", NULL,
2201 memequal_fntype, bloc);
2202 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2204 Named_object* key1_arg = gogo->lookup("key1", NULL);
2205 go_assert(key1_arg != NULL);
2206 Named_object* key2_arg = gogo->lookup("key2", NULL);
2207 go_assert(key2_arg != NULL);
2209 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2210 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2211 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2212 bloc);
2213 Expression_list* args = new Expression_list();
2214 args->push_back(key1_ref);
2215 args->push_back(key2_ref);
2216 args->push_back(size_arg);
2217 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2218 Expression* call = Expression::make_call(func, args, false, bloc);
2220 Expression_list* vals = new Expression_list();
2221 vals->push_back(call);
2222 Statement* s = Statement::make_return_statement(vals, bloc);
2223 gogo->add_statement(s);
2226 // Write a hash function that simply calls the hash function for a
2227 // named type. This is used when one named type is defined as
2228 // another. This ensures that this case works when the other named
2229 // type is defined in another package and relies on calling hash
2230 // functions defined only in that package.
2232 void
2233 Type::write_named_hash(Gogo* gogo, Named_type* name,
2234 Function_type* hash_fntype, Function_type* equal_fntype)
2236 Location bloc = Linemap::predeclared_location();
2238 Named_type* base_type = name->real_type()->named_type();
2239 while (base_type->is_alias())
2241 base_type = base_type->real_type()->named_type();
2242 go_assert(base_type != NULL);
2244 go_assert(base_type != NULL);
2246 // The pointer to the type we are going to hash. This is an
2247 // unsafe.Pointer.
2248 Named_object* key_arg = gogo->lookup("key", NULL);
2249 go_assert(key_arg != NULL);
2251 // The seed argument to the hash function.
2252 Named_object* seed_arg = gogo->lookup("seed", NULL);
2253 go_assert(seed_arg != NULL);
2255 Named_object* hash_fn;
2256 Named_object* equal_fn;
2257 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2258 &hash_fn, &equal_fn);
2260 // Call the hash function for the base type.
2261 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2262 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2263 Expression_list* args = new Expression_list();
2264 args->push_back(key_ref);
2265 args->push_back(seed_ref);
2266 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2267 Expression* call = Expression::make_call(func, args, false, bloc);
2269 // Return the hash of the base type.
2270 Expression_list* vals = new Expression_list();
2271 vals->push_back(call);
2272 Statement* s = Statement::make_return_statement(vals, bloc);
2273 gogo->add_statement(s);
2276 // Write an equality function that simply calls the equality function
2277 // for a named type. This is used when one named type is defined as
2278 // another. This ensures that this case works when the other named
2279 // type is defined in another package and relies on calling equality
2280 // functions defined only in that package.
2282 void
2283 Type::write_named_equal(Gogo* gogo, Named_type* name)
2285 Location bloc = Linemap::predeclared_location();
2287 // The pointers to the types we are going to compare. These have
2288 // type unsafe.Pointer.
2289 Named_object* key1_arg = gogo->lookup("key1", NULL);
2290 Named_object* key2_arg = gogo->lookup("key2", NULL);
2291 go_assert(key1_arg != NULL && key2_arg != NULL);
2293 Named_type* base_type = name->real_type()->named_type();
2294 go_assert(base_type != NULL);
2296 // Build temporaries with the base type.
2297 Type* pt = Type::make_pointer_type(base_type);
2299 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2300 ref = Expression::make_cast(pt, ref, bloc);
2301 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2302 gogo->add_statement(p1);
2304 ref = Expression::make_var_reference(key2_arg, bloc);
2305 ref = Expression::make_cast(pt, ref, bloc);
2306 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2307 gogo->add_statement(p2);
2309 // Compare the values for equality.
2310 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2311 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2313 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2314 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2316 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2318 // Return the equality comparison.
2319 Expression_list* vals = new Expression_list();
2320 vals->push_back(cond);
2321 Statement* s = Statement::make_return_statement(vals, bloc);
2322 gogo->add_statement(s);
2325 // Return a composite literal for the type descriptor for a plain type
2326 // of kind RUNTIME_TYPE_KIND named NAME.
2328 Expression*
2329 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2330 Named_type* name, const Methods* methods,
2331 bool only_value_methods)
2333 Location bloc = Linemap::predeclared_location();
2335 Type* td_type = Type::make_type_descriptor_type();
2336 const Struct_field_list* fields = td_type->struct_type()->fields();
2338 Expression_list* vals = new Expression_list();
2339 vals->reserve(12);
2341 if (!this->has_pointer())
2342 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2343 if (this->points_to() != NULL)
2344 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2345 int64_t ptrsize;
2346 int64_t ptrdata;
2347 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2348 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2350 Struct_field_list::const_iterator p = fields->begin();
2351 go_assert(p->is_field_name("size"));
2352 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2353 vals->push_back(Expression::make_type_info(this, type_info));
2355 ++p;
2356 go_assert(p->is_field_name("ptrdata"));
2357 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2358 vals->push_back(Expression::make_type_info(this, type_info));
2360 ++p;
2361 go_assert(p->is_field_name("hash"));
2362 unsigned int h;
2363 if (name != NULL)
2364 h = name->hash_for_method(gogo);
2365 else
2366 h = this->hash_for_method(gogo);
2367 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2369 ++p;
2370 go_assert(p->is_field_name("kind"));
2371 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2372 bloc));
2374 ++p;
2375 go_assert(p->is_field_name("align"));
2376 type_info = Expression::TYPE_INFO_ALIGNMENT;
2377 vals->push_back(Expression::make_type_info(this, type_info));
2379 ++p;
2380 go_assert(p->is_field_name("fieldAlign"));
2381 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2382 vals->push_back(Expression::make_type_info(this, type_info));
2384 ++p;
2385 go_assert(p->is_field_name("hashfn"));
2386 Function_type* hash_fntype = p->type()->function_type();
2388 ++p;
2389 go_assert(p->is_field_name("equalfn"));
2390 Function_type* equal_fntype = p->type()->function_type();
2392 Named_object* hash_fn;
2393 Named_object* equal_fn;
2394 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2395 &equal_fn);
2396 if (hash_fn == NULL)
2397 vals->push_back(Expression::make_cast(hash_fntype,
2398 Expression::make_nil(bloc),
2399 bloc));
2400 else
2401 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2402 if (equal_fn == NULL)
2403 vals->push_back(Expression::make_cast(equal_fntype,
2404 Expression::make_nil(bloc),
2405 bloc));
2406 else
2407 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2409 ++p;
2410 go_assert(p->is_field_name("gcdata"));
2411 vals->push_back(Expression::make_gc_symbol(this));
2413 ++p;
2414 go_assert(p->is_field_name("string"));
2415 Expression* s = Expression::make_string((name != NULL
2416 ? name->reflection(gogo)
2417 : this->reflection(gogo)),
2418 bloc);
2419 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2421 ++p;
2422 go_assert(p->is_field_name("uncommonType"));
2423 if (name == NULL && methods == NULL)
2424 vals->push_back(Expression::make_nil(bloc));
2425 else
2427 if (methods == NULL)
2428 methods = name->methods();
2429 vals->push_back(this->uncommon_type_constructor(gogo,
2430 p->type()->deref(),
2431 name, methods,
2432 only_value_methods));
2435 ++p;
2436 go_assert(p->is_field_name("ptrToThis"));
2437 if (name == NULL && methods == NULL)
2438 vals->push_back(Expression::make_nil(bloc));
2439 else
2441 Type* pt;
2442 if (name != NULL)
2443 pt = Type::make_pointer_type(name);
2444 else
2445 pt = Type::make_pointer_type(this);
2446 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2449 ++p;
2450 go_assert(p == fields->end());
2452 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2455 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2456 // length used by the gc toolchain, and also appears in
2457 // libgo/go/reflect/type.go.
2459 static const int64_t max_ptrmask_bytes = 2048;
2461 // Return a pointer to the Garbage Collection information for this type.
2463 Bexpression*
2464 Type::gc_symbol_pointer(Gogo* gogo)
2466 Type* t = this->unalias();
2468 if (!t->has_pointer())
2469 return gogo->backend()->nil_pointer_expression();
2471 if (t->gc_symbol_var_ == NULL)
2473 t->make_gc_symbol_var(gogo);
2474 go_assert(t->gc_symbol_var_ != NULL);
2476 Location bloc = Linemap::predeclared_location();
2477 Bexpression* var_expr =
2478 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2479 Bexpression* addr_expr =
2480 gogo->backend()->address_expression(var_expr, bloc);
2482 Type* uint8_type = Type::lookup_integer_type("uint8");
2483 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2484 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2485 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2488 // A mapping from unnamed types to GC symbol variables.
2490 Type::GC_symbol_vars Type::gc_symbol_vars;
2492 // Build the GC symbol for this type.
2494 void
2495 Type::make_gc_symbol_var(Gogo* gogo)
2497 go_assert(this->gc_symbol_var_ == NULL);
2499 Named_type* nt = this->named_type();
2501 // We can have multiple instances of unnamed types and similar to type
2502 // descriptors, we only want to the emit the GC data once, so we use a
2503 // hash table.
2504 Bvariable** phash = NULL;
2505 if (nt == NULL)
2507 Bvariable* bvnull = NULL;
2508 std::pair<GC_symbol_vars::iterator, bool> ins =
2509 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2510 if (!ins.second)
2512 // We've already built a gc symbol for this type.
2513 this->gc_symbol_var_ = ins.first->second;
2514 return;
2516 phash = &ins.first->second;
2519 int64_t ptrsize;
2520 int64_t ptrdata;
2521 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2523 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2524 if (phash != NULL)
2525 *phash = this->gc_symbol_var_;
2526 return;
2529 std::string sym_name = gogo->gc_symbol_name(this);
2531 // Build the contents of the gc symbol.
2532 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2533 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2535 // If the type descriptor for this type is defined somewhere else, so is the
2536 // GC symbol.
2537 const Package* dummy;
2538 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2540 std::string asm_name(go_selectively_encode_id(sym_name));
2541 this->gc_symbol_var_ =
2542 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2543 sym_btype);
2544 if (phash != NULL)
2545 *phash = this->gc_symbol_var_;
2546 return;
2549 // See if this gc symbol can appear in multiple packages.
2550 bool is_common = false;
2551 if (nt != NULL)
2553 // We create the symbol for a builtin type whenever we need
2554 // it.
2555 is_common = nt->is_builtin();
2557 else
2559 // This is an unnamed type. The descriptor could be defined in
2560 // any package where it is needed, and the linker will pick one
2561 // descriptor to keep.
2562 is_common = true;
2565 // Since we are building the GC symbol in this package, we must create the
2566 // variable before converting the initializer to its backend representation
2567 // because the initializer may refer to the GC symbol for this type.
2568 std::string asm_name(go_selectively_encode_id(sym_name));
2569 this->gc_symbol_var_ =
2570 gogo->backend()->implicit_variable(sym_name, asm_name,
2571 sym_btype, false, true, is_common, 0);
2572 if (phash != NULL)
2573 *phash = this->gc_symbol_var_;
2575 Translate_context context(gogo, NULL, NULL, NULL);
2576 context.set_is_const();
2577 Bexpression* sym_binit = sym_init->get_backend(&context);
2578 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2579 sym_btype, false, true, is_common,
2580 sym_binit);
2583 // Return whether this type needs a GC program, and set *PTRDATA to
2584 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2585 // pointer.
2587 bool
2588 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2590 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2591 if (!voidptr->backend_type_size(gogo, ptrsize))
2592 go_unreachable();
2594 if (!this->backend_type_ptrdata(gogo, ptrdata))
2596 go_assert(saw_errors());
2597 return false;
2600 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2603 // A simple class used to build a GC ptrmask for a type.
2605 class Ptrmask
2607 public:
2608 Ptrmask(size_t count)
2609 : bits_((count + 7) / 8, 0)
2612 void
2613 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2615 std::string
2616 symname() const;
2618 Expression*
2619 constructor(Gogo* gogo) const;
2621 private:
2622 void
2623 set(size_t index)
2624 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2626 // The actual bits.
2627 std::vector<unsigned char> bits_;
2630 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2631 // counts in bytes. PTRSIZE is the size of a pointer on the target
2632 // system.
2634 void
2635 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2637 switch (type->base()->classification())
2639 default:
2640 case Type::TYPE_NIL:
2641 case Type::TYPE_CALL_MULTIPLE_RESULT:
2642 case Type::TYPE_NAMED:
2643 case Type::TYPE_FORWARD:
2644 go_unreachable();
2646 case Type::TYPE_ERROR:
2647 case Type::TYPE_VOID:
2648 case Type::TYPE_BOOLEAN:
2649 case Type::TYPE_INTEGER:
2650 case Type::TYPE_FLOAT:
2651 case Type::TYPE_COMPLEX:
2652 case Type::TYPE_SINK:
2653 break;
2655 case Type::TYPE_FUNCTION:
2656 case Type::TYPE_POINTER:
2657 case Type::TYPE_MAP:
2658 case Type::TYPE_CHANNEL:
2659 // These types are all a single pointer.
2660 go_assert((offset % ptrsize) == 0);
2661 this->set(offset / ptrsize);
2662 break;
2664 case Type::TYPE_STRING:
2665 // A string starts with a single pointer.
2666 go_assert((offset % ptrsize) == 0);
2667 this->set(offset / ptrsize);
2668 break;
2670 case Type::TYPE_INTERFACE:
2671 // An interface is two pointers.
2672 go_assert((offset % ptrsize) == 0);
2673 this->set(offset / ptrsize);
2674 this->set((offset / ptrsize) + 1);
2675 break;
2677 case Type::TYPE_STRUCT:
2679 if (!type->has_pointer())
2680 return;
2682 const Struct_field_list* fields = type->struct_type()->fields();
2683 int64_t soffset = 0;
2684 for (Struct_field_list::const_iterator pf = fields->begin();
2685 pf != fields->end();
2686 ++pf)
2688 int64_t field_align;
2689 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2691 go_assert(saw_errors());
2692 return;
2694 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2696 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2698 int64_t field_size;
2699 if (!pf->type()->backend_type_size(gogo, &field_size))
2701 go_assert(saw_errors());
2702 return;
2704 soffset += field_size;
2707 break;
2709 case Type::TYPE_ARRAY:
2710 if (type->is_slice_type())
2712 // A slice starts with a single pointer.
2713 go_assert((offset % ptrsize) == 0);
2714 this->set(offset / ptrsize);
2715 break;
2717 else
2719 if (!type->has_pointer())
2720 return;
2722 int64_t len;
2723 if (!type->array_type()->int_length(&len))
2725 go_assert(saw_errors());
2726 return;
2729 Type* element_type = type->array_type()->element_type();
2730 int64_t ele_size;
2731 if (!element_type->backend_type_size(gogo, &ele_size))
2733 go_assert(saw_errors());
2734 return;
2737 int64_t eoffset = 0;
2738 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2739 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2740 break;
2745 // Return a symbol name for this ptrmask. This is used to coalesce
2746 // identical ptrmasks, which are common. The symbol name must use
2747 // only characters that are valid in symbols. It's nice if it's
2748 // short. We convert it to a string that uses only 32 characters,
2749 // avoiding digits and u and U.
2751 std::string
2752 Ptrmask::symname() const
2754 const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2755 go_assert(chars[32] == '\0');
2756 std::string ret;
2757 unsigned int b = 0;
2758 int remaining = 0;
2759 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2760 p != this->bits_.end();
2761 ++p)
2763 b |= *p << remaining;
2764 remaining += 8;
2765 while (remaining >= 5)
2767 ret += chars[b & 0x1f];
2768 b >>= 5;
2769 remaining -= 5;
2772 while (remaining > 0)
2774 ret += chars[b & 0x1f];
2775 b >>= 5;
2776 remaining -= 5;
2778 return ret;
2781 // Return a constructor for this ptrmask. This will be used to
2782 // initialize the runtime ptrmask value.
2784 Expression*
2785 Ptrmask::constructor(Gogo* gogo) const
2787 Location bloc = Linemap::predeclared_location();
2788 Type* byte_type = gogo->lookup_global("byte")->type_value();
2789 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2790 bloc);
2791 Array_type* at = Type::make_array_type(byte_type, len);
2792 Expression_list* vals = new Expression_list();
2793 vals->reserve(this->bits_.size());
2794 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2795 p != this->bits_.end();
2796 ++p)
2797 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2798 return Expression::make_array_composite_literal(at, vals, bloc);
2801 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2802 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2804 // Return a ptrmask variable for a type. For a type descriptor this
2805 // is only used for variables that are small enough to not need a
2806 // gcprog, but for a global variable this is used for a variable of
2807 // any size. PTRDATA is the number of bytes of the type that contain
2808 // pointer data. PTRSIZE is the size of a pointer on the target
2809 // system.
2811 Bvariable*
2812 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2814 Ptrmask ptrmask(ptrdata / ptrsize);
2815 if (ptrdata >= ptrsize)
2816 ptrmask.set_from(gogo, this, ptrsize, 0);
2817 else
2819 // This can happen in error cases. Just build an empty gcbits.
2820 go_assert(saw_errors());
2823 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2824 Bvariable* bvnull = NULL;
2825 std::pair<GC_gcbits_vars::iterator, bool> ins =
2826 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2827 if (!ins.second)
2829 // We've already built a GC symbol for this set of gcbits.
2830 return ins.first->second;
2833 Expression* val = ptrmask.constructor(gogo);
2834 Translate_context context(gogo, NULL, NULL, NULL);
2835 context.set_is_const();
2836 Bexpression* bval = val->get_backend(&context);
2838 std::string asm_name(go_selectively_encode_id(sym_name));
2839 Btype *btype = val->type()->get_backend(gogo);
2840 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2841 btype, false, true,
2842 true, 0);
2843 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2844 true, true, bval);
2845 ins.first->second = ret;
2846 return ret;
2849 // A GCProg is used to build a program for the garbage collector.
2850 // This is used for types with a lot of pointer data, to reduce the
2851 // size of the data in the compiled program. The program is expanded
2852 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2854 class GCProg
2856 public:
2857 GCProg()
2858 : bytes_(), index_(0), nb_(0)
2861 // The number of bits described so far.
2862 int64_t
2863 bit_index() const
2864 { return this->index_; }
2866 void
2867 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2869 void
2870 end();
2872 Expression*
2873 constructor(Gogo* gogo) const;
2875 private:
2876 void
2877 ptr(int64_t);
2879 bool
2880 should_repeat(int64_t, int64_t);
2882 void
2883 repeat(int64_t, int64_t);
2885 void
2886 zero_until(int64_t);
2888 void
2889 lit(unsigned char);
2891 void
2892 varint(int64_t);
2894 void
2895 flushlit();
2897 // Add a byte to the program.
2898 void
2899 byte(unsigned char x)
2900 { this->bytes_.push_back(x); }
2902 // The maximum number of bytes of literal bits.
2903 static const int max_literal = 127;
2905 // The program.
2906 std::vector<unsigned char> bytes_;
2907 // The index of the last bit described.
2908 int64_t index_;
2909 // The current set of literal bits.
2910 unsigned char b_[max_literal];
2911 // The current number of literal bits.
2912 int nb_;
2915 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2916 // counts in bytes. PTRSIZE is the size of a pointer on the target
2917 // system.
2919 void
2920 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2922 switch (type->base()->classification())
2924 default:
2925 case Type::TYPE_NIL:
2926 case Type::TYPE_CALL_MULTIPLE_RESULT:
2927 case Type::TYPE_NAMED:
2928 case Type::TYPE_FORWARD:
2929 go_unreachable();
2931 case Type::TYPE_ERROR:
2932 case Type::TYPE_VOID:
2933 case Type::TYPE_BOOLEAN:
2934 case Type::TYPE_INTEGER:
2935 case Type::TYPE_FLOAT:
2936 case Type::TYPE_COMPLEX:
2937 case Type::TYPE_SINK:
2938 break;
2940 case Type::TYPE_FUNCTION:
2941 case Type::TYPE_POINTER:
2942 case Type::TYPE_MAP:
2943 case Type::TYPE_CHANNEL:
2944 // These types are all a single pointer.
2945 go_assert((offset % ptrsize) == 0);
2946 this->ptr(offset / ptrsize);
2947 break;
2949 case Type::TYPE_STRING:
2950 // A string starts with a single pointer.
2951 go_assert((offset % ptrsize) == 0);
2952 this->ptr(offset / ptrsize);
2953 break;
2955 case Type::TYPE_INTERFACE:
2956 // An interface is two pointers.
2957 go_assert((offset % ptrsize) == 0);
2958 this->ptr(offset / ptrsize);
2959 this->ptr((offset / ptrsize) + 1);
2960 break;
2962 case Type::TYPE_STRUCT:
2964 if (!type->has_pointer())
2965 return;
2967 const Struct_field_list* fields = type->struct_type()->fields();
2968 int64_t soffset = 0;
2969 for (Struct_field_list::const_iterator pf = fields->begin();
2970 pf != fields->end();
2971 ++pf)
2973 int64_t field_align;
2974 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2976 go_assert(saw_errors());
2977 return;
2979 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2981 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2983 int64_t field_size;
2984 if (!pf->type()->backend_type_size(gogo, &field_size))
2986 go_assert(saw_errors());
2987 return;
2989 soffset += field_size;
2992 break;
2994 case Type::TYPE_ARRAY:
2995 if (type->is_slice_type())
2997 // A slice starts with a single pointer.
2998 go_assert((offset % ptrsize) == 0);
2999 this->ptr(offset / ptrsize);
3000 break;
3002 else
3004 if (!type->has_pointer())
3005 return;
3007 int64_t len;
3008 if (!type->array_type()->int_length(&len))
3010 go_assert(saw_errors());
3011 return;
3014 Type* element_type = type->array_type()->element_type();
3016 // Flatten array of array to a big array by multiplying counts.
3017 while (element_type->array_type() != NULL
3018 && !element_type->is_slice_type())
3020 int64_t ele_len;
3021 if (!element_type->array_type()->int_length(&ele_len))
3023 go_assert(saw_errors());
3024 return;
3027 len *= ele_len;
3028 element_type = element_type->array_type()->element_type();
3031 int64_t ele_size;
3032 if (!element_type->backend_type_size(gogo, &ele_size))
3034 go_assert(saw_errors());
3035 return;
3038 go_assert(len > 0 && ele_size > 0);
3040 if (!this->should_repeat(ele_size / ptrsize, len))
3042 // Cheaper to just emit the bits.
3043 int64_t eoffset = 0;
3044 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3045 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3047 else
3049 go_assert((offset % ptrsize) == 0);
3050 go_assert((ele_size % ptrsize) == 0);
3051 this->set_from(gogo, element_type, ptrsize, offset);
3052 this->zero_until((offset + ele_size) / ptrsize);
3053 this->repeat(ele_size / ptrsize, len - 1);
3056 break;
3061 // Emit a 1 into the bit stream of a GC program at the given bit index.
3063 void
3064 GCProg::ptr(int64_t index)
3066 go_assert(index >= this->index_);
3067 this->zero_until(index);
3068 this->lit(1);
3071 // Return whether it is worthwhile to use a repeat to describe c
3072 // elements of n bits each, compared to just emitting c copies of the
3073 // n-bit description.
3075 bool
3076 GCProg::should_repeat(int64_t n, int64_t c)
3078 // Repeat if there is more than 1 item and if the total data doesn't
3079 // fit into four bytes.
3080 return c > 1 && c * n > 4 * 8;
3083 // Emit an instruction to repeat the description of the last n words c
3084 // times (including the initial description, so c + 1 times in total).
3086 void
3087 GCProg::repeat(int64_t n, int64_t c)
3089 if (n == 0 || c == 0)
3090 return;
3091 this->flushlit();
3092 if (n < 128)
3093 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3094 else
3096 this->byte(0x80);
3097 this->varint(n);
3099 this->varint(c);
3100 this->index_ += n * c;
3103 // Add zeros to the bit stream up to the given index.
3105 void
3106 GCProg::zero_until(int64_t index)
3108 go_assert(index >= this->index_);
3109 int64_t skip = index - this->index_;
3110 if (skip == 0)
3111 return;
3112 if (skip < 4 * 8)
3114 for (int64_t i = 0; i < skip; ++i)
3115 this->lit(0);
3116 return;
3118 this->lit(0);
3119 this->flushlit();
3120 this->repeat(1, skip - 1);
3123 // Add a single literal bit to the program.
3125 void
3126 GCProg::lit(unsigned char x)
3128 if (this->nb_ == GCProg::max_literal)
3129 this->flushlit();
3130 this->b_[this->nb_] = x;
3131 ++this->nb_;
3132 ++this->index_;
3135 // Emit the varint encoding of x.
3137 void
3138 GCProg::varint(int64_t x)
3140 go_assert(x >= 0);
3141 while (x >= 0x80)
3143 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3144 x >>= 7;
3146 this->byte(static_cast<unsigned char>(x & 0x7f));
3149 // Flush any pending literal bits.
3151 void
3152 GCProg::flushlit()
3154 if (this->nb_ == 0)
3155 return;
3156 this->byte(static_cast<unsigned char>(this->nb_));
3157 unsigned char bits = 0;
3158 for (int i = 0; i < this->nb_; ++i)
3160 bits |= this->b_[i] << (i % 8);
3161 if ((i + 1) % 8 == 0)
3163 this->byte(bits);
3164 bits = 0;
3167 if (this->nb_ % 8 != 0)
3168 this->byte(bits);
3169 this->nb_ = 0;
3172 // Mark the end of a GC program.
3174 void
3175 GCProg::end()
3177 this->flushlit();
3178 this->byte(0);
3181 // Return an Expression for the bytes in a GC program.
3183 Expression*
3184 GCProg::constructor(Gogo* gogo) const
3186 Location bloc = Linemap::predeclared_location();
3188 // The first four bytes are the length of the program in target byte
3189 // order. Build a struct whose first type is uint32 to make this
3190 // work.
3192 Type* uint32_type = Type::lookup_integer_type("uint32");
3194 Type* byte_type = gogo->lookup_global("byte")->type_value();
3195 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3196 bloc);
3197 Array_type* at = Type::make_array_type(byte_type, len);
3199 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3200 "bytes", at);
3202 Expression_list* vals = new Expression_list();
3203 vals->reserve(this->bytes_.size());
3204 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3205 p != this->bytes_.end();
3206 ++p)
3207 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3208 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3210 vals = new Expression_list();
3211 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3212 bloc));
3213 vals->push_back(bytes);
3215 return Expression::make_struct_composite_literal(st, vals, bloc);
3218 // Return a composite literal for the garbage collection program for
3219 // this type. This is only used for types that are too large to use a
3220 // ptrmask.
3222 Expression*
3223 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3225 Location bloc = Linemap::predeclared_location();
3227 GCProg prog;
3228 prog.set_from(gogo, this, ptrsize, 0);
3229 int64_t offset = prog.bit_index() * ptrsize;
3230 prog.end();
3232 int64_t type_size;
3233 if (!this->backend_type_size(gogo, &type_size))
3235 go_assert(saw_errors());
3236 return Expression::make_error(bloc);
3239 go_assert(offset >= ptrdata && offset <= type_size);
3241 return prog.constructor(gogo);
3244 // Return a composite literal for the uncommon type information for
3245 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3246 // struct. If name is not NULL, it is the name of the type. If
3247 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3248 // is true if only value methods should be included. At least one of
3249 // NAME and METHODS must not be NULL.
3251 Expression*
3252 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3253 Named_type* name, const Methods* methods,
3254 bool only_value_methods) const
3256 Location bloc = Linemap::predeclared_location();
3258 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3260 Expression_list* vals = new Expression_list();
3261 vals->reserve(3);
3263 Struct_field_list::const_iterator p = fields->begin();
3264 go_assert(p->is_field_name("name"));
3266 ++p;
3267 go_assert(p->is_field_name("pkgPath"));
3269 if (name == NULL)
3271 vals->push_back(Expression::make_nil(bloc));
3272 vals->push_back(Expression::make_nil(bloc));
3274 else
3276 Named_object* no = name->named_object();
3277 std::string n = Gogo::unpack_hidden_name(no->name());
3278 Expression* s = Expression::make_string(n, bloc);
3279 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3281 if (name->is_builtin())
3282 vals->push_back(Expression::make_nil(bloc));
3283 else
3285 const Package* package = no->package();
3286 const std::string& pkgpath(package == NULL
3287 ? gogo->pkgpath()
3288 : package->pkgpath());
3289 s = Expression::make_string(pkgpath, bloc);
3290 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3294 ++p;
3295 go_assert(p->is_field_name("methods"));
3296 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3297 only_value_methods));
3299 ++p;
3300 go_assert(p == fields->end());
3302 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3303 vals, bloc);
3304 return Expression::make_unary(OPERATOR_AND, r, bloc);
3307 // Sort methods by name.
3309 class Sort_methods
3311 public:
3312 bool
3313 operator()(const std::pair<std::string, const Method*>& m1,
3314 const std::pair<std::string, const Method*>& m2) const
3316 return (Gogo::unpack_hidden_name(m1.first)
3317 < Gogo::unpack_hidden_name(m2.first));
3321 // Return a composite literal for the type method table for this type.
3322 // METHODS_TYPE is the type of the table, and is a slice type.
3323 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3324 // then only value methods are used.
3326 Expression*
3327 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3328 const Methods* methods,
3329 bool only_value_methods) const
3331 Location bloc = Linemap::predeclared_location();
3333 std::vector<std::pair<std::string, const Method*> > smethods;
3334 if (methods != NULL)
3336 smethods.reserve(methods->count());
3337 for (Methods::const_iterator p = methods->begin();
3338 p != methods->end();
3339 ++p)
3341 if (p->second->is_ambiguous())
3342 continue;
3343 if (only_value_methods && !p->second->is_value_method())
3344 continue;
3346 // This is where we implement the magic //go:nointerface
3347 // comment. If we saw that comment, we don't add this
3348 // method to the type descriptor.
3349 if (p->second->nointerface())
3350 continue;
3352 smethods.push_back(std::make_pair(p->first, p->second));
3356 if (smethods.empty())
3357 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3359 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3361 Type* method_type = methods_type->array_type()->element_type();
3363 Expression_list* vals = new Expression_list();
3364 vals->reserve(smethods.size());
3365 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3366 = smethods.begin();
3367 p != smethods.end();
3368 ++p)
3369 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3370 p->second, only_value_methods));
3372 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3375 // Return a composite literal for a single method. METHOD_TYPE is the
3376 // type of the entry. METHOD_NAME is the name of the method and M is
3377 // the method information.
3379 Expression*
3380 Type::method_constructor(Gogo*, Type* method_type,
3381 const std::string& method_name,
3382 const Method* m,
3383 bool only_value_methods) const
3385 Location bloc = Linemap::predeclared_location();
3387 const Struct_field_list* fields = method_type->struct_type()->fields();
3389 Expression_list* vals = new Expression_list();
3390 vals->reserve(5);
3392 Struct_field_list::const_iterator p = fields->begin();
3393 go_assert(p->is_field_name("name"));
3394 const std::string n = Gogo::unpack_hidden_name(method_name);
3395 Expression* s = Expression::make_string(n, bloc);
3396 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3398 ++p;
3399 go_assert(p->is_field_name("pkgPath"));
3400 if (!Gogo::is_hidden_name(method_name))
3401 vals->push_back(Expression::make_nil(bloc));
3402 else
3404 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3405 bloc);
3406 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3409 Named_object* no = (m->needs_stub_method()
3410 ? m->stub_object()
3411 : m->named_object());
3413 Function_type* mtype;
3414 if (no->is_function())
3415 mtype = no->func_value()->type();
3416 else
3417 mtype = no->func_declaration_value()->type();
3418 go_assert(mtype->is_method());
3419 Type* nonmethod_type = mtype->copy_without_receiver();
3421 ++p;
3422 go_assert(p->is_field_name("mtyp"));
3423 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3425 ++p;
3426 go_assert(p->is_field_name("typ"));
3427 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3428 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3429 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3431 ++p;
3432 go_assert(p->is_field_name("tfn"));
3433 vals->push_back(Expression::make_func_code_reference(no, bloc));
3435 ++p;
3436 go_assert(p == fields->end());
3438 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3441 // Return a composite literal for the type descriptor of a plain type.
3442 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3443 // NULL, it is the name to use as well as the list of methods.
3445 Expression*
3446 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3447 Named_type* name)
3449 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3450 name, NULL, true);
3453 // Return the type reflection string for this type.
3455 std::string
3456 Type::reflection(Gogo* gogo) const
3458 std::string ret;
3460 // The do_reflection virtual function should set RET to the
3461 // reflection string.
3462 this->do_reflection(gogo, &ret);
3464 return ret;
3467 // Return whether the backend size of the type is known.
3469 bool
3470 Type::is_backend_type_size_known(Gogo* gogo)
3472 switch (this->classification_)
3474 case TYPE_ERROR:
3475 case TYPE_VOID:
3476 case TYPE_BOOLEAN:
3477 case TYPE_INTEGER:
3478 case TYPE_FLOAT:
3479 case TYPE_COMPLEX:
3480 case TYPE_STRING:
3481 case TYPE_FUNCTION:
3482 case TYPE_POINTER:
3483 case TYPE_NIL:
3484 case TYPE_MAP:
3485 case TYPE_CHANNEL:
3486 case TYPE_INTERFACE:
3487 return true;
3489 case TYPE_STRUCT:
3491 const Struct_field_list* fields = this->struct_type()->fields();
3492 for (Struct_field_list::const_iterator pf = fields->begin();
3493 pf != fields->end();
3494 ++pf)
3495 if (!pf->type()->is_backend_type_size_known(gogo))
3496 return false;
3497 return true;
3500 case TYPE_ARRAY:
3502 const Array_type* at = this->array_type();
3503 if (at->length() == NULL)
3504 return true;
3505 else
3507 Numeric_constant nc;
3508 if (!at->length()->numeric_constant_value(&nc))
3509 return false;
3510 mpz_t ival;
3511 if (!nc.to_int(&ival))
3512 return false;
3513 mpz_clear(ival);
3514 return at->element_type()->is_backend_type_size_known(gogo);
3518 case TYPE_NAMED:
3519 this->named_type()->convert(gogo);
3520 return this->named_type()->is_named_backend_type_size_known();
3522 case TYPE_FORWARD:
3524 Forward_declaration_type* fdt = this->forward_declaration_type();
3525 return fdt->real_type()->is_backend_type_size_known(gogo);
3528 case TYPE_SINK:
3529 case TYPE_CALL_MULTIPLE_RESULT:
3530 go_unreachable();
3532 default:
3533 go_unreachable();
3537 // If the size of the type can be determined, set *PSIZE to the size
3538 // in bytes and return true. Otherwise, return false. This queries
3539 // the backend.
3541 bool
3542 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3544 if (!this->is_backend_type_size_known(gogo))
3545 return false;
3546 if (this->is_error_type())
3547 return false;
3548 Btype* bt = this->get_backend_placeholder(gogo);
3549 *psize = gogo->backend()->type_size(bt);
3550 if (*psize == -1)
3552 if (this->named_type() != NULL)
3553 go_error_at(this->named_type()->location(),
3554 "type %s larger than address space",
3555 Gogo::message_name(this->named_type()->name()).c_str());
3556 else
3557 go_error_at(Linemap::unknown_location(),
3558 "type %s larger than address space",
3559 this->reflection(gogo).c_str());
3561 // Make this an error type to avoid knock-on errors.
3562 this->classification_ = TYPE_ERROR;
3563 return false;
3565 return true;
3568 // If the alignment of the type can be determined, set *PALIGN to
3569 // the alignment in bytes and return true. Otherwise, return false.
3571 bool
3572 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3574 if (!this->is_backend_type_size_known(gogo))
3575 return false;
3576 Btype* bt = this->get_backend_placeholder(gogo);
3577 *palign = gogo->backend()->type_alignment(bt);
3578 return true;
3581 // Like backend_type_align, but return the alignment when used as a
3582 // field.
3584 bool
3585 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3587 if (!this->is_backend_type_size_known(gogo))
3588 return false;
3589 Btype* bt = this->get_backend_placeholder(gogo);
3590 *palign = gogo->backend()->type_field_alignment(bt);
3591 return true;
3594 // Get the ptrdata value for a type. This is the size of the prefix
3595 // of the type that contains all pointers. Store the ptrdata in
3596 // *PPTRDATA and return whether we found it.
3598 bool
3599 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3601 *pptrdata = 0;
3603 if (!this->has_pointer())
3604 return true;
3606 if (!this->is_backend_type_size_known(gogo))
3607 return false;
3609 switch (this->classification_)
3611 case TYPE_ERROR:
3612 return true;
3614 case TYPE_FUNCTION:
3615 case TYPE_POINTER:
3616 case TYPE_MAP:
3617 case TYPE_CHANNEL:
3618 // These types are nothing but a pointer.
3619 return this->backend_type_size(gogo, pptrdata);
3621 case TYPE_INTERFACE:
3622 // An interface is a struct of two pointers.
3623 return this->backend_type_size(gogo, pptrdata);
3625 case TYPE_STRING:
3627 // A string is a struct whose first field is a pointer, and
3628 // whose second field is not.
3629 Type* uint8_type = Type::lookup_integer_type("uint8");
3630 Type* ptr = Type::make_pointer_type(uint8_type);
3631 return ptr->backend_type_size(gogo, pptrdata);
3634 case TYPE_NAMED:
3635 case TYPE_FORWARD:
3636 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3638 case TYPE_STRUCT:
3640 const Struct_field_list* fields = this->struct_type()->fields();
3641 int64_t offset = 0;
3642 const Struct_field *ptr = NULL;
3643 int64_t ptr_offset = 0;
3644 for (Struct_field_list::const_iterator pf = fields->begin();
3645 pf != fields->end();
3646 ++pf)
3648 int64_t field_align;
3649 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3650 return false;
3651 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3653 if (pf->type()->has_pointer())
3655 ptr = &*pf;
3656 ptr_offset = offset;
3659 int64_t field_size;
3660 if (!pf->type()->backend_type_size(gogo, &field_size))
3661 return false;
3662 offset += field_size;
3665 if (ptr != NULL)
3667 int64_t ptr_ptrdata;
3668 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3669 return false;
3670 *pptrdata = ptr_offset + ptr_ptrdata;
3672 return true;
3675 case TYPE_ARRAY:
3676 if (this->is_slice_type())
3678 // A slice is a struct whose first field is a pointer, and
3679 // whose remaining fields are not.
3680 Type* element_type = this->array_type()->element_type();
3681 Type* ptr = Type::make_pointer_type(element_type);
3682 return ptr->backend_type_size(gogo, pptrdata);
3684 else
3686 Numeric_constant nc;
3687 if (!this->array_type()->length()->numeric_constant_value(&nc))
3688 return false;
3689 int64_t len;
3690 if (!nc.to_memory_size(&len))
3691 return false;
3693 Type* element_type = this->array_type()->element_type();
3694 int64_t ele_size;
3695 int64_t ele_ptrdata;
3696 if (!element_type->backend_type_size(gogo, &ele_size)
3697 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3698 return false;
3699 go_assert(ele_size > 0 && ele_ptrdata > 0);
3701 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3702 return true;
3705 default:
3706 case TYPE_VOID:
3707 case TYPE_BOOLEAN:
3708 case TYPE_INTEGER:
3709 case TYPE_FLOAT:
3710 case TYPE_COMPLEX:
3711 case TYPE_SINK:
3712 case TYPE_NIL:
3713 case TYPE_CALL_MULTIPLE_RESULT:
3714 go_unreachable();
3718 // Get the ptrdata value to store in a type descriptor. This is
3719 // normally the same as backend_type_ptrdata, but for a type that is
3720 // large enough to use a gcprog we may need to store a different value
3721 // if it ends with an array. If the gcprog uses a repeat descriptor
3722 // for the array, and if the array element ends with non-pointer data,
3723 // then the gcprog will produce a value that describes the complete
3724 // array where the backend ptrdata will omit the non-pointer elements
3725 // of the final array element. This is a subtle difference but the
3726 // run time code checks it to verify that it has expanded a gcprog as
3727 // expected.
3729 bool
3730 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3732 int64_t backend_ptrdata;
3733 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3734 return false;
3736 int64_t ptrsize;
3737 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3739 *pptrdata = backend_ptrdata;
3740 return true;
3743 GCProg prog;
3744 prog.set_from(gogo, this, ptrsize, 0);
3745 int64_t offset = prog.bit_index() * ptrsize;
3747 go_assert(offset >= backend_ptrdata);
3748 *pptrdata = offset;
3749 return true;
3752 // Default function to export a type.
3754 void
3755 Type::do_export(Export*) const
3757 go_unreachable();
3760 // Import a type.
3762 Type*
3763 Type::import_type(Import* imp)
3765 if (imp->match_c_string("("))
3766 return Function_type::do_import(imp);
3767 else if (imp->match_c_string("*"))
3768 return Pointer_type::do_import(imp);
3769 else if (imp->match_c_string("struct "))
3770 return Struct_type::do_import(imp);
3771 else if (imp->match_c_string("["))
3772 return Array_type::do_import(imp);
3773 else if (imp->match_c_string("map "))
3774 return Map_type::do_import(imp);
3775 else if (imp->match_c_string("chan "))
3776 return Channel_type::do_import(imp);
3777 else if (imp->match_c_string("interface"))
3778 return Interface_type::do_import(imp);
3779 else
3781 go_error_at(imp->location(), "import error: expected type");
3782 return Type::make_error_type();
3786 // Class Error_type.
3788 // Return the backend representation of an Error type.
3790 Btype*
3791 Error_type::do_get_backend(Gogo* gogo)
3793 return gogo->backend()->error_type();
3796 // Return an expression for the type descriptor for an error type.
3799 Expression*
3800 Error_type::do_type_descriptor(Gogo*, Named_type*)
3802 return Expression::make_error(Linemap::predeclared_location());
3805 // We should not be asked for the reflection string for an error type.
3807 void
3808 Error_type::do_reflection(Gogo*, std::string*) const
3810 go_assert(saw_errors());
3813 Type*
3814 Type::make_error_type()
3816 static Error_type singleton_error_type;
3817 return &singleton_error_type;
3820 // Class Void_type.
3822 // Get the backend representation of a void type.
3824 Btype*
3825 Void_type::do_get_backend(Gogo* gogo)
3827 return gogo->backend()->void_type();
3830 Type*
3831 Type::make_void_type()
3833 static Void_type singleton_void_type;
3834 return &singleton_void_type;
3837 // Class Boolean_type.
3839 // Return the backend representation of the boolean type.
3841 Btype*
3842 Boolean_type::do_get_backend(Gogo* gogo)
3844 return gogo->backend()->bool_type();
3847 // Make the type descriptor.
3849 Expression*
3850 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3852 if (name != NULL)
3853 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3854 else
3856 Named_object* no = gogo->lookup_global("bool");
3857 go_assert(no != NULL);
3858 return Type::type_descriptor(gogo, no->type_value());
3862 Type*
3863 Type::make_boolean_type()
3865 static Boolean_type boolean_type;
3866 return &boolean_type;
3869 // The named type "bool".
3871 static Named_type* named_bool_type;
3873 // Get the named type "bool".
3875 Named_type*
3876 Type::lookup_bool_type()
3878 return named_bool_type;
3881 // Make the named type "bool".
3883 Named_type*
3884 Type::make_named_bool_type()
3886 Type* bool_type = Type::make_boolean_type();
3887 Named_object* named_object =
3888 Named_object::make_type("bool", NULL, bool_type,
3889 Linemap::predeclared_location());
3890 Named_type* named_type = named_object->type_value();
3891 named_bool_type = named_type;
3892 return named_type;
3895 // Class Integer_type.
3897 Integer_type::Named_integer_types Integer_type::named_integer_types;
3899 // Create a new integer type. Non-abstract integer types always have
3900 // names.
3902 Named_type*
3903 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3904 int bits, int runtime_type_kind)
3906 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3907 runtime_type_kind);
3908 std::string sname(name);
3909 Named_object* named_object =
3910 Named_object::make_type(sname, NULL, integer_type,
3911 Linemap::predeclared_location());
3912 Named_type* named_type = named_object->type_value();
3913 std::pair<Named_integer_types::iterator, bool> ins =
3914 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3915 go_assert(ins.second);
3916 return named_type;
3919 // Look up an existing integer type.
3921 Named_type*
3922 Integer_type::lookup_integer_type(const char* name)
3924 Named_integer_types::const_iterator p =
3925 Integer_type::named_integer_types.find(name);
3926 go_assert(p != Integer_type::named_integer_types.end());
3927 return p->second;
3930 // Create a new abstract integer type.
3932 Integer_type*
3933 Integer_type::create_abstract_integer_type()
3935 static Integer_type* abstract_type;
3936 if (abstract_type == NULL)
3938 Type* int_type = Type::lookup_integer_type("int");
3939 abstract_type = new Integer_type(true, false,
3940 int_type->integer_type()->bits(),
3941 RUNTIME_TYPE_KIND_INT);
3943 return abstract_type;
3946 // Create a new abstract character type.
3948 Integer_type*
3949 Integer_type::create_abstract_character_type()
3951 static Integer_type* abstract_type;
3952 if (abstract_type == NULL)
3954 abstract_type = new Integer_type(true, false, 32,
3955 RUNTIME_TYPE_KIND_INT32);
3956 abstract_type->set_is_rune();
3958 return abstract_type;
3961 // Integer type compatibility.
3963 bool
3964 Integer_type::is_identical(const Integer_type* t) const
3966 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3967 return false;
3968 return this->is_abstract_ == t->is_abstract_;
3971 // Hash code.
3973 unsigned int
3974 Integer_type::do_hash_for_method(Gogo*) const
3976 return ((this->bits_ << 4)
3977 + ((this->is_unsigned_ ? 1 : 0) << 8)
3978 + ((this->is_abstract_ ? 1 : 0) << 9));
3981 // Convert an Integer_type to the backend representation.
3983 Btype*
3984 Integer_type::do_get_backend(Gogo* gogo)
3986 if (this->is_abstract_)
3988 go_assert(saw_errors());
3989 return gogo->backend()->error_type();
3991 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
3994 // The type descriptor for an integer type. Integer types are always
3995 // named.
3997 Expression*
3998 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4000 go_assert(name != NULL || saw_errors());
4001 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4004 // We should not be asked for the reflection string of a basic type.
4006 void
4007 Integer_type::do_reflection(Gogo*, std::string*) const
4009 go_assert(saw_errors());
4012 // Make an integer type.
4014 Named_type*
4015 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4016 int runtime_type_kind)
4018 return Integer_type::create_integer_type(name, is_unsigned, bits,
4019 runtime_type_kind);
4022 // Make an abstract integer type.
4024 Integer_type*
4025 Type::make_abstract_integer_type()
4027 return Integer_type::create_abstract_integer_type();
4030 // Make an abstract character type.
4032 Integer_type*
4033 Type::make_abstract_character_type()
4035 return Integer_type::create_abstract_character_type();
4038 // Look up an integer type.
4040 Named_type*
4041 Type::lookup_integer_type(const char* name)
4043 return Integer_type::lookup_integer_type(name);
4046 // Class Float_type.
4048 Float_type::Named_float_types Float_type::named_float_types;
4050 // Create a new float type. Non-abstract float types always have
4051 // names.
4053 Named_type*
4054 Float_type::create_float_type(const char* name, int bits,
4055 int runtime_type_kind)
4057 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4058 std::string sname(name);
4059 Named_object* named_object =
4060 Named_object::make_type(sname, NULL, float_type,
4061 Linemap::predeclared_location());
4062 Named_type* named_type = named_object->type_value();
4063 std::pair<Named_float_types::iterator, bool> ins =
4064 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4065 go_assert(ins.second);
4066 return named_type;
4069 // Look up an existing float type.
4071 Named_type*
4072 Float_type::lookup_float_type(const char* name)
4074 Named_float_types::const_iterator p =
4075 Float_type::named_float_types.find(name);
4076 go_assert(p != Float_type::named_float_types.end());
4077 return p->second;
4080 // Create a new abstract float type.
4082 Float_type*
4083 Float_type::create_abstract_float_type()
4085 static Float_type* abstract_type;
4086 if (abstract_type == NULL)
4087 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4088 return abstract_type;
4091 // Whether this type is identical with T.
4093 bool
4094 Float_type::is_identical(const Float_type* t) const
4096 if (this->bits_ != t->bits_)
4097 return false;
4098 return this->is_abstract_ == t->is_abstract_;
4101 // Hash code.
4103 unsigned int
4104 Float_type::do_hash_for_method(Gogo*) const
4106 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4109 // Convert to the backend representation.
4111 Btype*
4112 Float_type::do_get_backend(Gogo* gogo)
4114 return gogo->backend()->float_type(this->bits_);
4117 // The type descriptor for a float type. Float types are always named.
4119 Expression*
4120 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4122 go_assert(name != NULL || saw_errors());
4123 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4126 // We should not be asked for the reflection string of a basic type.
4128 void
4129 Float_type::do_reflection(Gogo*, std::string*) const
4131 go_assert(saw_errors());
4134 // Make a floating point type.
4136 Named_type*
4137 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4139 return Float_type::create_float_type(name, bits, runtime_type_kind);
4142 // Make an abstract float type.
4144 Float_type*
4145 Type::make_abstract_float_type()
4147 return Float_type::create_abstract_float_type();
4150 // Look up a float type.
4152 Named_type*
4153 Type::lookup_float_type(const char* name)
4155 return Float_type::lookup_float_type(name);
4158 // Class Complex_type.
4160 Complex_type::Named_complex_types Complex_type::named_complex_types;
4162 // Create a new complex type. Non-abstract complex types always have
4163 // names.
4165 Named_type*
4166 Complex_type::create_complex_type(const char* name, int bits,
4167 int runtime_type_kind)
4169 Complex_type* complex_type = new Complex_type(false, bits,
4170 runtime_type_kind);
4171 std::string sname(name);
4172 Named_object* named_object =
4173 Named_object::make_type(sname, NULL, complex_type,
4174 Linemap::predeclared_location());
4175 Named_type* named_type = named_object->type_value();
4176 std::pair<Named_complex_types::iterator, bool> ins =
4177 Complex_type::named_complex_types.insert(std::make_pair(sname,
4178 named_type));
4179 go_assert(ins.second);
4180 return named_type;
4183 // Look up an existing complex type.
4185 Named_type*
4186 Complex_type::lookup_complex_type(const char* name)
4188 Named_complex_types::const_iterator p =
4189 Complex_type::named_complex_types.find(name);
4190 go_assert(p != Complex_type::named_complex_types.end());
4191 return p->second;
4194 // Create a new abstract complex type.
4196 Complex_type*
4197 Complex_type::create_abstract_complex_type()
4199 static Complex_type* abstract_type;
4200 if (abstract_type == NULL)
4201 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4202 return abstract_type;
4205 // Whether this type is identical with T.
4207 bool
4208 Complex_type::is_identical(const Complex_type *t) const
4210 if (this->bits_ != t->bits_)
4211 return false;
4212 return this->is_abstract_ == t->is_abstract_;
4215 // Hash code.
4217 unsigned int
4218 Complex_type::do_hash_for_method(Gogo*) const
4220 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4223 // Convert to the backend representation.
4225 Btype*
4226 Complex_type::do_get_backend(Gogo* gogo)
4228 return gogo->backend()->complex_type(this->bits_);
4231 // The type descriptor for a complex type. Complex types are always
4232 // named.
4234 Expression*
4235 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4237 go_assert(name != NULL || saw_errors());
4238 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4241 // We should not be asked for the reflection string of a basic type.
4243 void
4244 Complex_type::do_reflection(Gogo*, std::string*) const
4246 go_assert(saw_errors());
4249 // Make a complex type.
4251 Named_type*
4252 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4254 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4257 // Make an abstract complex type.
4259 Complex_type*
4260 Type::make_abstract_complex_type()
4262 return Complex_type::create_abstract_complex_type();
4265 // Look up a complex type.
4267 Named_type*
4268 Type::lookup_complex_type(const char* name)
4270 return Complex_type::lookup_complex_type(name);
4273 // Class String_type.
4275 // Convert String_type to the backend representation. A string is a
4276 // struct with two fields: a pointer to the characters and a length.
4278 Btype*
4279 String_type::do_get_backend(Gogo* gogo)
4281 static Btype* backend_string_type;
4282 if (backend_string_type == NULL)
4284 std::vector<Backend::Btyped_identifier> fields(2);
4286 Type* b = gogo->lookup_global("byte")->type_value();
4287 Type* pb = Type::make_pointer_type(b);
4289 // We aren't going to get back to this field to finish the
4290 // backend representation, so force it to be finished now.
4291 if (!gogo->named_types_are_converted())
4293 Btype* bt = pb->get_backend_placeholder(gogo);
4294 pb->finish_backend(gogo, bt);
4297 fields[0].name = "__data";
4298 fields[0].btype = pb->get_backend(gogo);
4299 fields[0].location = Linemap::predeclared_location();
4301 Type* int_type = Type::lookup_integer_type("int");
4302 fields[1].name = "__length";
4303 fields[1].btype = int_type->get_backend(gogo);
4304 fields[1].location = fields[0].location;
4306 backend_string_type = gogo->backend()->struct_type(fields);
4308 return backend_string_type;
4311 // The type descriptor for the string type.
4313 Expression*
4314 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4316 if (name != NULL)
4317 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4318 else
4320 Named_object* no = gogo->lookup_global("string");
4321 go_assert(no != NULL);
4322 return Type::type_descriptor(gogo, no->type_value());
4326 // We should not be asked for the reflection string of a basic type.
4328 void
4329 String_type::do_reflection(Gogo*, std::string* ret) const
4331 ret->append("string");
4334 // Make a string type.
4336 Type*
4337 Type::make_string_type()
4339 static String_type string_type;
4340 return &string_type;
4343 // The named type "string".
4345 static Named_type* named_string_type;
4347 // Get the named type "string".
4349 Named_type*
4350 Type::lookup_string_type()
4352 return named_string_type;
4355 // Make the named type string.
4357 Named_type*
4358 Type::make_named_string_type()
4360 Type* string_type = Type::make_string_type();
4361 Named_object* named_object =
4362 Named_object::make_type("string", NULL, string_type,
4363 Linemap::predeclared_location());
4364 Named_type* named_type = named_object->type_value();
4365 named_string_type = named_type;
4366 return named_type;
4369 // The sink type. This is the type of the blank identifier _. Any
4370 // type may be assigned to it.
4372 class Sink_type : public Type
4374 public:
4375 Sink_type()
4376 : Type(TYPE_SINK)
4379 protected:
4380 bool
4381 do_compare_is_identity(Gogo*)
4382 { return false; }
4384 Btype*
4385 do_get_backend(Gogo*)
4386 { go_unreachable(); }
4388 Expression*
4389 do_type_descriptor(Gogo*, Named_type*)
4390 { go_unreachable(); }
4392 void
4393 do_reflection(Gogo*, std::string*) const
4394 { go_unreachable(); }
4396 void
4397 do_mangled_name(Gogo*, std::string*) const
4398 { go_unreachable(); }
4401 // Make the sink type.
4403 Type*
4404 Type::make_sink_type()
4406 static Sink_type sink_type;
4407 return &sink_type;
4410 // Class Function_type.
4412 // Traversal.
4415 Function_type::do_traverse(Traverse* traverse)
4417 if (this->receiver_ != NULL
4418 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4419 return TRAVERSE_EXIT;
4420 if (this->parameters_ != NULL
4421 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4422 return TRAVERSE_EXIT;
4423 if (this->results_ != NULL
4424 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4425 return TRAVERSE_EXIT;
4426 return TRAVERSE_CONTINUE;
4429 // Returns whether T is a valid redeclaration of this type. If this
4430 // returns false, and REASON is not NULL, *REASON may be set to a
4431 // brief explanation of why it returned false.
4433 bool
4434 Function_type::is_valid_redeclaration(const Function_type* t,
4435 std::string* reason) const
4437 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4438 return false;
4440 // A redeclaration of a function is required to use the same names
4441 // for the receiver and parameters.
4442 if (this->receiver() != NULL
4443 && this->receiver()->name() != t->receiver()->name())
4445 if (reason != NULL)
4446 *reason = "receiver name changed";
4447 return false;
4450 const Typed_identifier_list* parms1 = this->parameters();
4451 const Typed_identifier_list* parms2 = t->parameters();
4452 if (parms1 != NULL)
4454 Typed_identifier_list::const_iterator p1 = parms1->begin();
4455 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4456 p2 != parms2->end();
4457 ++p2, ++p1)
4459 if (p1->name() != p2->name())
4461 if (reason != NULL)
4462 *reason = "parameter name changed";
4463 return false;
4466 // This is called at parse time, so we may have unknown
4467 // types.
4468 Type* t1 = p1->type()->forwarded();
4469 Type* t2 = p2->type()->forwarded();
4470 if (t1 != t2
4471 && t1->forward_declaration_type() != NULL
4472 && (t2->forward_declaration_type() == NULL
4473 || (t1->forward_declaration_type()->named_object()
4474 != t2->forward_declaration_type()->named_object())))
4475 return false;
4479 const Typed_identifier_list* results1 = this->results();
4480 const Typed_identifier_list* results2 = t->results();
4481 if (results1 != NULL)
4483 Typed_identifier_list::const_iterator res1 = results1->begin();
4484 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4485 res2 != results2->end();
4486 ++res2, ++res1)
4488 if (res1->name() != res2->name())
4490 if (reason != NULL)
4491 *reason = "result name changed";
4492 return false;
4495 // This is called at parse time, so we may have unknown
4496 // types.
4497 Type* t1 = res1->type()->forwarded();
4498 Type* t2 = res2->type()->forwarded();
4499 if (t1 != t2
4500 && t1->forward_declaration_type() != NULL
4501 && (t2->forward_declaration_type() == NULL
4502 || (t1->forward_declaration_type()->named_object()
4503 != t2->forward_declaration_type()->named_object())))
4504 return false;
4508 return true;
4511 // Check whether T is the same as this type.
4513 bool
4514 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4515 Cmp_tags cmp_tags, bool errors_are_identical,
4516 std::string* reason) const
4518 if (this->is_backend_function_type() != t->is_backend_function_type())
4519 return false;
4521 if (!ignore_receiver)
4523 const Typed_identifier* r1 = this->receiver();
4524 const Typed_identifier* r2 = t->receiver();
4525 if ((r1 != NULL) != (r2 != NULL))
4527 if (reason != NULL)
4528 *reason = _("different receiver types");
4529 return false;
4531 if (r1 != NULL)
4533 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4534 errors_are_identical, reason))
4536 if (reason != NULL && !reason->empty())
4537 *reason = "receiver: " + *reason;
4538 return false;
4543 const Typed_identifier_list* parms1 = this->parameters();
4544 if (parms1 != NULL && parms1->empty())
4545 parms1 = NULL;
4546 const Typed_identifier_list* parms2 = t->parameters();
4547 if (parms2 != NULL && parms2->empty())
4548 parms2 = NULL;
4549 if ((parms1 != NULL) != (parms2 != NULL))
4551 if (reason != NULL)
4552 *reason = _("different number of parameters");
4553 return false;
4555 if (parms1 != NULL)
4557 Typed_identifier_list::const_iterator p1 = parms1->begin();
4558 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4559 p2 != parms2->end();
4560 ++p2, ++p1)
4562 if (p1 == parms1->end())
4564 if (reason != NULL)
4565 *reason = _("different number of parameters");
4566 return false;
4569 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4570 errors_are_identical, NULL))
4572 if (reason != NULL)
4573 *reason = _("different parameter types");
4574 return false;
4577 if (p1 != parms1->end())
4579 if (reason != NULL)
4580 *reason = _("different number of parameters");
4581 return false;
4585 if (this->is_varargs() != t->is_varargs())
4587 if (reason != NULL)
4588 *reason = _("different varargs");
4589 return false;
4592 const Typed_identifier_list* results1 = this->results();
4593 if (results1 != NULL && results1->empty())
4594 results1 = NULL;
4595 const Typed_identifier_list* results2 = t->results();
4596 if (results2 != NULL && results2->empty())
4597 results2 = NULL;
4598 if ((results1 != NULL) != (results2 != NULL))
4600 if (reason != NULL)
4601 *reason = _("different number of results");
4602 return false;
4604 if (results1 != NULL)
4606 Typed_identifier_list::const_iterator res1 = results1->begin();
4607 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4608 res2 != results2->end();
4609 ++res2, ++res1)
4611 if (res1 == results1->end())
4613 if (reason != NULL)
4614 *reason = _("different number of results");
4615 return false;
4618 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4619 cmp_tags, errors_are_identical,
4620 NULL))
4622 if (reason != NULL)
4623 *reason = _("different result types");
4624 return false;
4627 if (res1 != results1->end())
4629 if (reason != NULL)
4630 *reason = _("different number of results");
4631 return false;
4635 return true;
4638 // Hash code.
4640 unsigned int
4641 Function_type::do_hash_for_method(Gogo* gogo) const
4643 unsigned int ret = 0;
4644 // We ignore the receiver type for hash codes, because we need to
4645 // get the same hash code for a method in an interface and a method
4646 // declared for a type. The former will not have a receiver.
4647 if (this->parameters_ != NULL)
4649 int shift = 1;
4650 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4651 p != this->parameters_->end();
4652 ++p, ++shift)
4653 ret += p->type()->hash_for_method(gogo) << shift;
4655 if (this->results_ != NULL)
4657 int shift = 2;
4658 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4659 p != this->results_->end();
4660 ++p, ++shift)
4661 ret += p->type()->hash_for_method(gogo) << shift;
4663 if (this->is_varargs_)
4664 ret += 1;
4665 ret <<= 4;
4666 return ret;
4669 // Hash result parameters.
4671 unsigned int
4672 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4674 unsigned int hash = 0;
4675 for (Typed_identifier_list::const_iterator p = t->begin();
4676 p != t->end();
4677 ++p)
4679 hash <<= 2;
4680 hash = Type::hash_string(p->name(), hash);
4681 hash += p->type()->hash_for_method(NULL);
4683 return hash;
4686 // Compare result parameters so that can map identical result
4687 // parameters to a single struct type.
4689 bool
4690 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4691 const Typed_identifier_list* b) const
4693 if (a->size() != b->size())
4694 return false;
4695 Typed_identifier_list::const_iterator pa = a->begin();
4696 for (Typed_identifier_list::const_iterator pb = b->begin();
4697 pb != b->end();
4698 ++pa, ++pb)
4700 if (pa->name() != pb->name()
4701 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4702 return false;
4704 return true;
4707 // Hash from results to a backend struct type.
4709 Function_type::Results_structs Function_type::results_structs;
4711 // Get the backend representation for a function type.
4713 Btype*
4714 Function_type::get_backend_fntype(Gogo* gogo)
4716 if (this->fnbtype_ == NULL)
4718 Backend::Btyped_identifier breceiver;
4719 if (this->receiver_ != NULL)
4721 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4723 // We always pass the address of the receiver parameter, in
4724 // order to make interface calls work with unknown types.
4725 Type* rtype = this->receiver_->type();
4726 if (rtype->points_to() == NULL)
4727 rtype = Type::make_pointer_type(rtype);
4728 breceiver.btype = rtype->get_backend(gogo);
4729 breceiver.location = this->receiver_->location();
4732 std::vector<Backend::Btyped_identifier> bparameters;
4733 if (this->parameters_ != NULL)
4735 bparameters.resize(this->parameters_->size());
4736 size_t i = 0;
4737 for (Typed_identifier_list::const_iterator p =
4738 this->parameters_->begin(); p != this->parameters_->end();
4739 ++p, ++i)
4741 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4742 bparameters[i].btype = p->type()->get_backend(gogo);
4743 bparameters[i].location = p->location();
4745 go_assert(i == bparameters.size());
4748 std::vector<Backend::Btyped_identifier> bresults;
4749 Btype* bresult_struct = NULL;
4750 if (this->results_ != NULL)
4752 bresults.resize(this->results_->size());
4753 size_t i = 0;
4754 for (Typed_identifier_list::const_iterator p =
4755 this->results_->begin();
4756 p != this->results_->end();
4757 ++p, ++i)
4759 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4760 bresults[i].btype = p->type()->get_backend(gogo);
4761 bresults[i].location = p->location();
4763 go_assert(i == bresults.size());
4765 if (this->results_->size() > 1)
4767 // Use the same results struct for all functions that
4768 // return the same set of results. This is useful to
4769 // unify calls to interface methods with other calls.
4770 std::pair<Typed_identifier_list*, Btype*> val;
4771 val.first = this->results_;
4772 val.second = NULL;
4773 std::pair<Results_structs::iterator, bool> ins =
4774 Function_type::results_structs.insert(val);
4775 if (ins.second)
4777 // Build a new struct type.
4778 Struct_field_list* sfl = new Struct_field_list;
4779 for (Typed_identifier_list::const_iterator p =
4780 this->results_->begin();
4781 p != this->results_->end();
4782 ++p)
4784 Typed_identifier tid = *p;
4785 if (tid.name().empty())
4786 tid = Typed_identifier("UNNAMED", tid.type(),
4787 tid.location());
4788 sfl->push_back(Struct_field(tid));
4790 Struct_type* st = Type::make_struct_type(sfl,
4791 this->location());
4792 st->set_is_struct_incomparable();
4793 ins.first->second = st->get_backend(gogo);
4795 bresult_struct = ins.first->second;
4799 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4800 bresults, bresult_struct,
4801 this->location());
4805 return this->fnbtype_;
4808 // Get the backend representation for a Go function type.
4810 Btype*
4811 Function_type::do_get_backend(Gogo* gogo)
4813 // When we do anything with a function value other than call it, it
4814 // is represented as a pointer to a struct whose first field is the
4815 // actual function. So that is what we return as the type of a Go
4816 // function.
4818 Location loc = this->location();
4819 Btype* struct_type =
4820 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4821 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4823 std::vector<Backend::Btyped_identifier> fields(1);
4824 fields[0].name = "code";
4825 fields[0].btype = this->get_backend_fntype(gogo);
4826 fields[0].location = loc;
4827 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4828 return gogo->backend()->error_type();
4829 return ptr_struct_type;
4832 // The type of a function type descriptor.
4834 Type*
4835 Function_type::make_function_type_descriptor_type()
4837 static Type* ret;
4838 if (ret == NULL)
4840 Type* tdt = Type::make_type_descriptor_type();
4841 Type* ptdt = Type::make_type_descriptor_ptr_type();
4843 Type* bool_type = Type::lookup_bool_type();
4845 Type* slice_type = Type::make_array_type(ptdt, NULL);
4847 Struct_type* s = Type::make_builtin_struct_type(4,
4848 "", tdt,
4849 "dotdotdot", bool_type,
4850 "in", slice_type,
4851 "out", slice_type);
4853 ret = Type::make_builtin_named_type("FuncType", s);
4856 return ret;
4859 // The type descriptor for a function type.
4861 Expression*
4862 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4864 Location bloc = Linemap::predeclared_location();
4866 Type* ftdt = Function_type::make_function_type_descriptor_type();
4868 const Struct_field_list* fields = ftdt->struct_type()->fields();
4870 Expression_list* vals = new Expression_list();
4871 vals->reserve(4);
4873 Struct_field_list::const_iterator p = fields->begin();
4874 go_assert(p->is_field_name("_type"));
4875 vals->push_back(this->type_descriptor_constructor(gogo,
4876 RUNTIME_TYPE_KIND_FUNC,
4877 name, NULL, true));
4879 ++p;
4880 go_assert(p->is_field_name("dotdotdot"));
4881 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4883 ++p;
4884 go_assert(p->is_field_name("in"));
4885 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4886 this->parameters()));
4888 ++p;
4889 go_assert(p->is_field_name("out"));
4890 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4891 this->results()));
4893 ++p;
4894 go_assert(p == fields->end());
4896 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4899 // Return a composite literal for the parameters or results of a type
4900 // descriptor.
4902 Expression*
4903 Function_type::type_descriptor_params(Type* params_type,
4904 const Typed_identifier* receiver,
4905 const Typed_identifier_list* params)
4907 Location bloc = Linemap::predeclared_location();
4909 if (receiver == NULL && params == NULL)
4910 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4912 Expression_list* vals = new Expression_list();
4913 vals->reserve((params == NULL ? 0 : params->size())
4914 + (receiver != NULL ? 1 : 0));
4916 if (receiver != NULL)
4917 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4919 if (params != NULL)
4921 for (Typed_identifier_list::const_iterator p = params->begin();
4922 p != params->end();
4923 ++p)
4924 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4927 return Expression::make_slice_composite_literal(params_type, vals, bloc);
4930 // The reflection string.
4932 void
4933 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4935 // FIXME: Turn this off until we straighten out the type of the
4936 // struct field used in a go statement which calls a method.
4937 // go_assert(this->receiver_ == NULL);
4939 ret->append("func");
4941 if (this->receiver_ != NULL)
4943 ret->push_back('(');
4944 this->append_reflection(this->receiver_->type(), gogo, ret);
4945 ret->push_back(')');
4948 ret->push_back('(');
4949 const Typed_identifier_list* params = this->parameters();
4950 if (params != NULL)
4952 bool is_varargs = this->is_varargs_;
4953 for (Typed_identifier_list::const_iterator p = params->begin();
4954 p != params->end();
4955 ++p)
4957 if (p != params->begin())
4958 ret->append(", ");
4959 if (!is_varargs || p + 1 != params->end())
4960 this->append_reflection(p->type(), gogo, ret);
4961 else
4963 ret->append("...");
4964 this->append_reflection(p->type()->array_type()->element_type(),
4965 gogo, ret);
4969 ret->push_back(')');
4971 const Typed_identifier_list* results = this->results();
4972 if (results != NULL && !results->empty())
4974 if (results->size() == 1)
4975 ret->push_back(' ');
4976 else
4977 ret->append(" (");
4978 for (Typed_identifier_list::const_iterator p = results->begin();
4979 p != results->end();
4980 ++p)
4982 if (p != results->begin())
4983 ret->append(", ");
4984 this->append_reflection(p->type(), gogo, ret);
4986 if (results->size() > 1)
4987 ret->push_back(')');
4991 // Export a function type.
4993 void
4994 Function_type::do_export(Export* exp) const
4996 // We don't write out the receiver. The only function types which
4997 // should have a receiver are the ones associated with explicitly
4998 // defined methods. For those the receiver type is written out by
4999 // Function::export_func.
5001 exp->write_c_string("(");
5002 bool first = true;
5003 if (this->parameters_ != NULL)
5005 bool is_varargs = this->is_varargs_;
5006 for (Typed_identifier_list::const_iterator p =
5007 this->parameters_->begin();
5008 p != this->parameters_->end();
5009 ++p)
5011 if (first)
5012 first = false;
5013 else
5014 exp->write_c_string(", ");
5015 exp->write_name(p->name());
5016 exp->write_c_string(" ");
5017 if (!is_varargs || p + 1 != this->parameters_->end())
5018 exp->write_type(p->type());
5019 else
5021 exp->write_c_string("...");
5022 exp->write_type(p->type()->array_type()->element_type());
5026 exp->write_c_string(")");
5028 const Typed_identifier_list* results = this->results_;
5029 if (results != NULL)
5031 exp->write_c_string(" ");
5032 if (results->size() == 1 && results->begin()->name().empty())
5033 exp->write_type(results->begin()->type());
5034 else
5036 first = true;
5037 exp->write_c_string("(");
5038 for (Typed_identifier_list::const_iterator p = results->begin();
5039 p != results->end();
5040 ++p)
5042 if (first)
5043 first = false;
5044 else
5045 exp->write_c_string(", ");
5046 exp->write_name(p->name());
5047 exp->write_c_string(" ");
5048 exp->write_type(p->type());
5050 exp->write_c_string(")");
5055 // Import a function type.
5057 Function_type*
5058 Function_type::do_import(Import* imp)
5060 imp->require_c_string("(");
5061 Typed_identifier_list* parameters;
5062 bool is_varargs = false;
5063 if (imp->peek_char() == ')')
5064 parameters = NULL;
5065 else
5067 parameters = new Typed_identifier_list();
5068 while (true)
5070 std::string name = imp->read_name();
5071 imp->require_c_string(" ");
5073 if (imp->match_c_string("..."))
5075 imp->advance(3);
5076 is_varargs = true;
5079 Type* ptype = imp->read_type();
5080 if (is_varargs)
5081 ptype = Type::make_array_type(ptype, NULL);
5082 parameters->push_back(Typed_identifier(name, ptype,
5083 imp->location()));
5084 if (imp->peek_char() != ',')
5085 break;
5086 go_assert(!is_varargs);
5087 imp->require_c_string(", ");
5090 imp->require_c_string(")");
5092 Typed_identifier_list* results;
5093 if (imp->peek_char() != ' ')
5094 results = NULL;
5095 else
5097 imp->advance(1);
5098 results = new Typed_identifier_list;
5099 if (imp->peek_char() != '(')
5101 Type* rtype = imp->read_type();
5102 results->push_back(Typed_identifier("", rtype, imp->location()));
5104 else
5106 imp->advance(1);
5107 while (true)
5109 std::string name = imp->read_name();
5110 imp->require_c_string(" ");
5111 Type* rtype = imp->read_type();
5112 results->push_back(Typed_identifier(name, rtype,
5113 imp->location()));
5114 if (imp->peek_char() != ',')
5115 break;
5116 imp->require_c_string(", ");
5118 imp->require_c_string(")");
5122 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5123 imp->location());
5124 if (is_varargs)
5125 ret->set_is_varargs();
5126 return ret;
5129 // Make a copy of a function type without a receiver.
5131 Function_type*
5132 Function_type::copy_without_receiver() const
5134 go_assert(this->is_method());
5135 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5136 this->results_,
5137 this->location_);
5138 if (this->is_varargs())
5139 ret->set_is_varargs();
5140 if (this->is_builtin())
5141 ret->set_is_builtin();
5142 return ret;
5145 // Make a copy of a function type with a receiver.
5147 Function_type*
5148 Function_type::copy_with_receiver(Type* receiver_type) const
5150 go_assert(!this->is_method());
5151 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5152 this->location_);
5153 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5154 this->results_,
5155 this->location_);
5156 if (this->is_varargs_)
5157 ret->set_is_varargs();
5158 return ret;
5161 // Make a copy of a function type with the receiver as the first
5162 // parameter.
5164 Function_type*
5165 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5167 go_assert(this->is_method());
5168 Typed_identifier_list* new_params = new Typed_identifier_list();
5169 Type* rtype = this->receiver_->type();
5170 if (want_pointer_receiver)
5171 rtype = Type::make_pointer_type(rtype);
5172 Typed_identifier receiver(this->receiver_->name(), rtype,
5173 this->receiver_->location());
5174 new_params->push_back(receiver);
5175 const Typed_identifier_list* orig_params = this->parameters_;
5176 if (orig_params != NULL && !orig_params->empty())
5178 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5179 p != orig_params->end();
5180 ++p)
5181 new_params->push_back(*p);
5183 return Type::make_function_type(NULL, new_params, this->results_,
5184 this->location_);
5187 // Make a copy of a function type ignoring any receiver and adding a
5188 // closure parameter.
5190 Function_type*
5191 Function_type::copy_with_names() const
5193 Typed_identifier_list* new_params = new Typed_identifier_list();
5194 const Typed_identifier_list* orig_params = this->parameters_;
5195 if (orig_params != NULL && !orig_params->empty())
5197 static int count;
5198 char buf[50];
5199 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5200 p != orig_params->end();
5201 ++p)
5203 snprintf(buf, sizeof buf, "pt.%u", count);
5204 ++count;
5205 new_params->push_back(Typed_identifier(buf, p->type(),
5206 p->location()));
5210 const Typed_identifier_list* orig_results = this->results_;
5211 Typed_identifier_list* new_results;
5212 if (orig_results == NULL || orig_results->empty())
5213 new_results = NULL;
5214 else
5216 new_results = new Typed_identifier_list();
5217 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5218 p != orig_results->end();
5219 ++p)
5220 new_results->push_back(Typed_identifier("", p->type(),
5221 p->location()));
5224 return Type::make_function_type(NULL, new_params, new_results,
5225 this->location());
5228 // Make a function type.
5230 Function_type*
5231 Type::make_function_type(Typed_identifier* receiver,
5232 Typed_identifier_list* parameters,
5233 Typed_identifier_list* results,
5234 Location location)
5236 return new Function_type(receiver, parameters, results, location);
5239 // Make a backend function type.
5241 Backend_function_type*
5242 Type::make_backend_function_type(Typed_identifier* receiver,
5243 Typed_identifier_list* parameters,
5244 Typed_identifier_list* results,
5245 Location location)
5247 return new Backend_function_type(receiver, parameters, results, location);
5250 // Class Pointer_type.
5252 // Traversal.
5255 Pointer_type::do_traverse(Traverse* traverse)
5257 return Type::traverse(this->to_type_, traverse);
5260 // Hash code.
5262 unsigned int
5263 Pointer_type::do_hash_for_method(Gogo* gogo) const
5265 return this->to_type_->hash_for_method(gogo) << 4;
5268 // Get the backend representation for a pointer type.
5270 Btype*
5271 Pointer_type::do_get_backend(Gogo* gogo)
5273 Btype* to_btype = this->to_type_->get_backend(gogo);
5274 return gogo->backend()->pointer_type(to_btype);
5277 // The type of a pointer type descriptor.
5279 Type*
5280 Pointer_type::make_pointer_type_descriptor_type()
5282 static Type* ret;
5283 if (ret == NULL)
5285 Type* tdt = Type::make_type_descriptor_type();
5286 Type* ptdt = Type::make_type_descriptor_ptr_type();
5288 Struct_type* s = Type::make_builtin_struct_type(2,
5289 "", tdt,
5290 "elem", ptdt);
5292 ret = Type::make_builtin_named_type("PtrType", s);
5295 return ret;
5298 // The type descriptor for a pointer type.
5300 Expression*
5301 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5303 if (this->is_unsafe_pointer_type())
5305 go_assert(name != NULL);
5306 return this->plain_type_descriptor(gogo,
5307 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5308 name);
5310 else
5312 Location bloc = Linemap::predeclared_location();
5314 const Methods* methods;
5315 Type* deref = this->points_to();
5316 if (deref->named_type() != NULL)
5317 methods = deref->named_type()->methods();
5318 else if (deref->struct_type() != NULL)
5319 methods = deref->struct_type()->methods();
5320 else
5321 methods = NULL;
5323 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5325 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5327 Expression_list* vals = new Expression_list();
5328 vals->reserve(2);
5330 Struct_field_list::const_iterator p = fields->begin();
5331 go_assert(p->is_field_name("_type"));
5332 vals->push_back(this->type_descriptor_constructor(gogo,
5333 RUNTIME_TYPE_KIND_PTR,
5334 name, methods, false));
5336 ++p;
5337 go_assert(p->is_field_name("elem"));
5338 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5340 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5344 // Reflection string.
5346 void
5347 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5349 ret->push_back('*');
5350 this->append_reflection(this->to_type_, gogo, ret);
5353 // Export.
5355 void
5356 Pointer_type::do_export(Export* exp) const
5358 exp->write_c_string("*");
5359 if (this->is_unsafe_pointer_type())
5360 exp->write_c_string("any");
5361 else
5362 exp->write_type(this->to_type_);
5365 // Import.
5367 Pointer_type*
5368 Pointer_type::do_import(Import* imp)
5370 imp->require_c_string("*");
5371 if (imp->match_c_string("any"))
5373 imp->advance(3);
5374 return Type::make_pointer_type(Type::make_void_type());
5376 Type* to = imp->read_type();
5377 return Type::make_pointer_type(to);
5380 // Cache of pointer types. Key is "to" type, value is pointer type
5381 // that points to key.
5383 Type::Pointer_type_table Type::pointer_types;
5385 // A list of placeholder pointer types. We keep this so we can ensure
5386 // they are finalized.
5388 std::vector<Pointer_type*> Type::placeholder_pointers;
5390 // Make a pointer type.
5392 Pointer_type*
5393 Type::make_pointer_type(Type* to_type)
5395 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5396 if (p != pointer_types.end())
5397 return p->second;
5398 Pointer_type* ret = new Pointer_type(to_type);
5399 pointer_types[to_type] = ret;
5400 return ret;
5403 // This helper is invoked immediately after named types have been
5404 // converted, to clean up any unresolved pointer types remaining in
5405 // the pointer type cache.
5407 // The motivation for this routine: occasionally the compiler creates
5408 // some specific pointer type as part of a lowering operation (ex:
5409 // pointer-to-void), then Type::backend_type_size() is invoked on the
5410 // type (which creates a Btype placeholder for it), that placeholder
5411 // passed somewhere along the line to the back end, but since there is
5412 // no reference to the type in user code, there is never a call to
5413 // Type::finish_backend for the type (hence the Btype remains as an
5414 // unresolved placeholder). Calling this routine will clean up such
5415 // instances.
5417 void
5418 Type::finish_pointer_types(Gogo* gogo)
5420 // We don't use begin() and end() because it is possible to add new
5421 // placeholder pointer types as we finalized existing ones.
5422 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5424 Pointer_type* pt = Type::placeholder_pointers[i];
5425 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5426 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5428 pt->finish_backend(gogo, tbti->second.btype);
5429 tbti->second.is_placeholder = false;
5434 // Class Nil_type.
5436 // Get the backend representation of a nil type. FIXME: Is this ever
5437 // actually called?
5439 Btype*
5440 Nil_type::do_get_backend(Gogo* gogo)
5442 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5445 // Make the nil type.
5447 Type*
5448 Type::make_nil_type()
5450 static Nil_type singleton_nil_type;
5451 return &singleton_nil_type;
5454 // The type of a function call which returns multiple values. This is
5455 // really a struct, but we don't want to confuse a function call which
5456 // returns a struct with a function call which returns multiple
5457 // values.
5459 class Call_multiple_result_type : public Type
5461 public:
5462 Call_multiple_result_type(Call_expression* call)
5463 : Type(TYPE_CALL_MULTIPLE_RESULT),
5464 call_(call)
5467 protected:
5468 bool
5469 do_has_pointer() const
5470 { return false; }
5472 bool
5473 do_compare_is_identity(Gogo*)
5474 { return false; }
5476 Btype*
5477 do_get_backend(Gogo* gogo)
5479 go_assert(saw_errors());
5480 return gogo->backend()->error_type();
5483 Expression*
5484 do_type_descriptor(Gogo*, Named_type*)
5486 go_assert(saw_errors());
5487 return Expression::make_error(Linemap::unknown_location());
5490 void
5491 do_reflection(Gogo*, std::string*) const
5492 { go_assert(saw_errors()); }
5494 void
5495 do_mangled_name(Gogo*, std::string*) const
5496 { go_assert(saw_errors()); }
5498 private:
5499 // The expression being called.
5500 Call_expression* call_;
5503 // Make a call result type.
5505 Type*
5506 Type::make_call_multiple_result_type(Call_expression* call)
5508 return new Call_multiple_result_type(call);
5511 // Class Struct_field.
5513 // Get the name of a field.
5515 const std::string&
5516 Struct_field::field_name() const
5518 const std::string& name(this->typed_identifier_.name());
5519 if (!name.empty())
5520 return name;
5521 else
5523 // This is called during parsing, before anything is lowered, so
5524 // we have to be pretty careful to avoid dereferencing an
5525 // unknown type name.
5526 Type* t = this->typed_identifier_.type();
5527 Type* dt = t;
5528 if (t->classification() == Type::TYPE_POINTER)
5530 // Very ugly.
5531 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5532 dt = ptype->points_to();
5534 if (dt->forward_declaration_type() != NULL)
5535 return dt->forward_declaration_type()->name();
5536 else if (dt->named_type() != NULL)
5538 // Note that this can be an alias name.
5539 return dt->named_type()->name();
5541 else if (t->is_error_type() || dt->is_error_type())
5543 static const std::string error_string = "*error*";
5544 return error_string;
5546 else
5548 // Avoid crashing in the erroneous case where T is named but
5549 // DT is not.
5550 go_assert(t != dt);
5551 if (t->forward_declaration_type() != NULL)
5552 return t->forward_declaration_type()->name();
5553 else if (t->named_type() != NULL)
5554 return t->named_type()->name();
5555 else
5556 go_unreachable();
5561 // Return whether this field is named NAME.
5563 bool
5564 Struct_field::is_field_name(const std::string& name) const
5566 const std::string& me(this->typed_identifier_.name());
5567 if (!me.empty())
5568 return me == name;
5569 else
5571 Type* t = this->typed_identifier_.type();
5572 if (t->points_to() != NULL)
5573 t = t->points_to();
5574 Named_type* nt = t->named_type();
5575 if (nt != NULL && nt->name() == name)
5576 return true;
5578 // This is a horrible hack caused by the fact that we don't pack
5579 // the names of builtin types. FIXME.
5580 if (!this->is_imported_
5581 && nt != NULL
5582 && nt->is_builtin()
5583 && nt->name() == Gogo::unpack_hidden_name(name))
5584 return true;
5586 return false;
5590 // Return whether this field is an unexported field named NAME.
5592 bool
5593 Struct_field::is_unexported_field_name(Gogo* gogo,
5594 const std::string& name) const
5596 const std::string& field_name(this->field_name());
5597 if (Gogo::is_hidden_name(field_name)
5598 && name == Gogo::unpack_hidden_name(field_name)
5599 && gogo->pack_hidden_name(name, false) != field_name)
5600 return true;
5602 // Check for the name of a builtin type. This is like the test in
5603 // is_field_name, only there we return false if this->is_imported_,
5604 // and here we return true.
5605 if (this->is_imported_ && this->is_anonymous())
5607 Type* t = this->typed_identifier_.type();
5608 if (t->points_to() != NULL)
5609 t = t->points_to();
5610 Named_type* nt = t->named_type();
5611 if (nt != NULL
5612 && nt->is_builtin()
5613 && nt->name() == Gogo::unpack_hidden_name(name))
5614 return true;
5617 return false;
5620 // Return whether this field is an embedded built-in type.
5622 bool
5623 Struct_field::is_embedded_builtin(Gogo* gogo) const
5625 const std::string& name(this->field_name());
5626 // We know that a field is an embedded type if it is anonymous.
5627 // We can decide if it is a built-in type by checking to see if it is
5628 // registered globally under the field's name.
5629 // This allows us to distinguish between embedded built-in types and
5630 // embedded types that are aliases to built-in types.
5631 return (this->is_anonymous()
5632 && !Gogo::is_hidden_name(name)
5633 && gogo->lookup_global(name.c_str()) != NULL);
5636 // Class Struct_type.
5638 // A hash table used to find identical unnamed structs so that they
5639 // share method tables.
5641 Struct_type::Identical_structs Struct_type::identical_structs;
5643 // A hash table used to merge method sets for identical unnamed
5644 // structs.
5646 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5648 // Traversal.
5651 Struct_type::do_traverse(Traverse* traverse)
5653 Struct_field_list* fields = this->fields_;
5654 if (fields != NULL)
5656 for (Struct_field_list::iterator p = fields->begin();
5657 p != fields->end();
5658 ++p)
5660 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5661 return TRAVERSE_EXIT;
5664 return TRAVERSE_CONTINUE;
5667 // Verify that the struct type is complete and valid.
5669 bool
5670 Struct_type::do_verify()
5672 Struct_field_list* fields = this->fields_;
5673 if (fields == NULL)
5674 return true;
5675 for (Struct_field_list::iterator p = fields->begin();
5676 p != fields->end();
5677 ++p)
5679 Type* t = p->type();
5680 if (p->is_anonymous())
5682 if ((t->named_type() != NULL && t->points_to() != NULL)
5683 || (t->named_type() == NULL && t->points_to() != NULL
5684 && t->points_to()->points_to() != NULL))
5686 go_error_at(p->location(), "embedded type may not be a pointer");
5687 p->set_type(Type::make_error_type());
5689 else if (t->points_to() != NULL
5690 && t->points_to()->interface_type() != NULL)
5692 go_error_at(p->location(),
5693 "embedded type may not be pointer to interface");
5694 p->set_type(Type::make_error_type());
5698 return true;
5701 // Whether this contains a pointer.
5703 bool
5704 Struct_type::do_has_pointer() const
5706 const Struct_field_list* fields = this->fields();
5707 if (fields == NULL)
5708 return false;
5709 for (Struct_field_list::const_iterator p = fields->begin();
5710 p != fields->end();
5711 ++p)
5713 if (p->type()->has_pointer())
5714 return true;
5716 return false;
5719 // Whether this type is identical to T.
5721 bool
5722 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5723 bool errors_are_identical) const
5725 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5726 return false;
5727 const Struct_field_list* fields1 = this->fields();
5728 const Struct_field_list* fields2 = t->fields();
5729 if (fields1 == NULL || fields2 == NULL)
5730 return fields1 == fields2;
5731 Struct_field_list::const_iterator pf2 = fields2->begin();
5732 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5733 pf1 != fields1->end();
5734 ++pf1, ++pf2)
5736 if (pf2 == fields2->end())
5737 return false;
5738 if (pf1->field_name() != pf2->field_name())
5739 return false;
5740 if (pf1->is_anonymous() != pf2->is_anonymous()
5741 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5742 errors_are_identical, NULL))
5743 return false;
5744 if (cmp_tags == COMPARE_TAGS)
5746 if (!pf1->has_tag())
5748 if (pf2->has_tag())
5749 return false;
5751 else
5753 if (!pf2->has_tag())
5754 return false;
5755 if (pf1->tag() != pf2->tag())
5756 return false;
5760 if (pf2 != fields2->end())
5761 return false;
5762 return true;
5765 // Whether comparisons of this struct type are simple identity
5766 // comparisons.
5768 bool
5769 Struct_type::do_compare_is_identity(Gogo* gogo)
5771 const Struct_field_list* fields = this->fields_;
5772 if (fields == NULL)
5773 return true;
5774 int64_t offset = 0;
5775 for (Struct_field_list::const_iterator pf = fields->begin();
5776 pf != fields->end();
5777 ++pf)
5779 if (Gogo::is_sink_name(pf->field_name()))
5780 return false;
5782 if (!pf->type()->compare_is_identity(gogo))
5783 return false;
5785 int64_t field_align;
5786 if (!pf->type()->backend_type_align(gogo, &field_align))
5787 return false;
5788 if ((offset & (field_align - 1)) != 0)
5790 // This struct has padding. We don't guarantee that that
5791 // padding is zero-initialized for a stack variable, so we
5792 // can't use memcmp to compare struct values.
5793 return false;
5796 int64_t field_size;
5797 if (!pf->type()->backend_type_size(gogo, &field_size))
5798 return false;
5799 offset += field_size;
5802 int64_t struct_size;
5803 if (!this->backend_type_size(gogo, &struct_size))
5804 return false;
5805 if (offset != struct_size)
5807 // Trailing padding may not be zero when on the stack.
5808 return false;
5811 return true;
5814 // Return whether this struct type is reflexive--whether a value of
5815 // this type is always equal to itself.
5817 bool
5818 Struct_type::do_is_reflexive()
5820 const Struct_field_list* fields = this->fields_;
5821 if (fields == NULL)
5822 return true;
5823 for (Struct_field_list::const_iterator pf = fields->begin();
5824 pf != fields->end();
5825 ++pf)
5827 if (!pf->type()->is_reflexive())
5828 return false;
5830 return true;
5833 // Return whether this struct type needs a key update when used as a
5834 // map key.
5836 bool
5837 Struct_type::do_needs_key_update()
5839 const Struct_field_list* fields = this->fields_;
5840 if (fields == NULL)
5841 return false;
5842 for (Struct_field_list::const_iterator pf = fields->begin();
5843 pf != fields->end();
5844 ++pf)
5846 if (pf->type()->needs_key_update())
5847 return true;
5849 return false;
5852 // Return whether this struct type is permitted to be in the heap.
5854 bool
5855 Struct_type::do_in_heap()
5857 const Struct_field_list* fields = this->fields_;
5858 if (fields == NULL)
5859 return true;
5860 for (Struct_field_list::const_iterator pf = fields->begin();
5861 pf != fields->end();
5862 ++pf)
5864 if (!pf->type()->in_heap())
5865 return false;
5867 return true;
5870 // Build identity and hash functions for this struct.
5872 // Hash code.
5874 unsigned int
5875 Struct_type::do_hash_for_method(Gogo* gogo) const
5877 unsigned int ret = 0;
5878 if (this->fields() != NULL)
5880 for (Struct_field_list::const_iterator pf = this->fields()->begin();
5881 pf != this->fields()->end();
5882 ++pf)
5883 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5885 ret <<= 2;
5886 if (this->is_struct_incomparable_)
5887 ret <<= 1;
5888 return ret;
5891 // Find the local field NAME.
5893 const Struct_field*
5894 Struct_type::find_local_field(const std::string& name,
5895 unsigned int *pindex) const
5897 const Struct_field_list* fields = this->fields_;
5898 if (fields == NULL)
5899 return NULL;
5900 unsigned int i = 0;
5901 for (Struct_field_list::const_iterator pf = fields->begin();
5902 pf != fields->end();
5903 ++pf, ++i)
5905 if (pf->is_field_name(name))
5907 if (pindex != NULL)
5908 *pindex = i;
5909 return &*pf;
5912 return NULL;
5915 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5917 Field_reference_expression*
5918 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5919 Location location) const
5921 unsigned int depth;
5922 return this->field_reference_depth(struct_expr, name, location, NULL,
5923 &depth);
5926 // Return an expression for a field, along with the depth at which it
5927 // was found.
5929 Field_reference_expression*
5930 Struct_type::field_reference_depth(Expression* struct_expr,
5931 const std::string& name,
5932 Location location,
5933 Saw_named_type* saw,
5934 unsigned int* depth) const
5936 const Struct_field_list* fields = this->fields_;
5937 if (fields == NULL)
5938 return NULL;
5940 // Look for a field with this name.
5941 unsigned int i = 0;
5942 for (Struct_field_list::const_iterator pf = fields->begin();
5943 pf != fields->end();
5944 ++pf, ++i)
5946 if (pf->is_field_name(name))
5948 *depth = 0;
5949 return Expression::make_field_reference(struct_expr, i, location);
5953 // Look for an anonymous field which contains a field with this
5954 // name.
5955 unsigned int found_depth = 0;
5956 Field_reference_expression* ret = NULL;
5957 i = 0;
5958 for (Struct_field_list::const_iterator pf = fields->begin();
5959 pf != fields->end();
5960 ++pf, ++i)
5962 if (!pf->is_anonymous())
5963 continue;
5965 Struct_type* st = pf->type()->deref()->struct_type();
5966 if (st == NULL)
5967 continue;
5969 Saw_named_type* hold_saw = saw;
5970 Saw_named_type saw_here;
5971 Named_type* nt = pf->type()->named_type();
5972 if (nt == NULL)
5973 nt = pf->type()->deref()->named_type();
5974 if (nt != NULL)
5976 Saw_named_type* q;
5977 for (q = saw; q != NULL; q = q->next)
5979 if (q->nt == nt)
5981 // If this is an error, it will be reported
5982 // elsewhere.
5983 break;
5986 if (q != NULL)
5987 continue;
5988 saw_here.next = saw;
5989 saw_here.nt = nt;
5990 saw = &saw_here;
5993 // Look for a reference using a NULL struct expression. If we
5994 // find one, fill in the struct expression with a reference to
5995 // this field.
5996 unsigned int subdepth;
5997 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5998 location,
5999 saw,
6000 &subdepth);
6002 saw = hold_saw;
6004 if (sub == NULL)
6005 continue;
6007 if (ret == NULL || subdepth < found_depth)
6009 if (ret != NULL)
6010 delete ret;
6011 ret = sub;
6012 found_depth = subdepth;
6013 Expression* here = Expression::make_field_reference(struct_expr, i,
6014 location);
6015 if (pf->type()->points_to() != NULL)
6016 here = Expression::make_dereference(here,
6017 Expression::NIL_CHECK_DEFAULT,
6018 location);
6019 while (sub->expr() != NULL)
6021 sub = sub->expr()->deref()->field_reference_expression();
6022 go_assert(sub != NULL);
6024 sub->set_struct_expression(here);
6025 sub->set_implicit(true);
6027 else if (subdepth > found_depth)
6028 delete sub;
6029 else
6031 // We do not handle ambiguity here--it should be handled by
6032 // Type::bind_field_or_method.
6033 delete sub;
6034 found_depth = 0;
6035 ret = NULL;
6039 if (ret != NULL)
6040 *depth = found_depth + 1;
6042 return ret;
6045 // Return the total number of fields, including embedded fields.
6047 unsigned int
6048 Struct_type::total_field_count() const
6050 if (this->fields_ == NULL)
6051 return 0;
6052 unsigned int ret = 0;
6053 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6054 pf != this->fields_->end();
6055 ++pf)
6057 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6058 ++ret;
6059 else
6060 ret += pf->type()->struct_type()->total_field_count();
6062 return ret;
6065 // Return whether NAME is an unexported field, for better error reporting.
6067 bool
6068 Struct_type::is_unexported_local_field(Gogo* gogo,
6069 const std::string& name) const
6071 const Struct_field_list* fields = this->fields_;
6072 if (fields != NULL)
6074 for (Struct_field_list::const_iterator pf = fields->begin();
6075 pf != fields->end();
6076 ++pf)
6077 if (pf->is_unexported_field_name(gogo, name))
6078 return true;
6080 return false;
6083 // Finalize the methods of an unnamed struct.
6085 void
6086 Struct_type::finalize_methods(Gogo* gogo)
6088 if (this->all_methods_ != NULL)
6089 return;
6091 // It is possible to have multiple identical structs that have
6092 // methods. We want them to share method tables. Otherwise we will
6093 // emit identical methods more than once, which is bad since they
6094 // will even have the same names.
6095 std::pair<Identical_structs::iterator, bool> ins =
6096 Struct_type::identical_structs.insert(std::make_pair(this, this));
6097 if (!ins.second)
6099 // An identical struct was already entered into the hash table.
6100 // Note that finalize_methods is, fortunately, not recursive.
6101 this->all_methods_ = ins.first->second->all_methods_;
6102 return;
6105 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6108 // Return the method NAME, or NULL if there isn't one or if it is
6109 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6110 // ambiguous.
6112 Method*
6113 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6115 return Type::method_function(this->all_methods_, name, is_ambiguous);
6118 // Return a pointer to the interface method table for this type for
6119 // the interface INTERFACE. IS_POINTER is true if this is for a
6120 // pointer to THIS.
6122 Expression*
6123 Struct_type::interface_method_table(Interface_type* interface,
6124 bool is_pointer)
6126 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6127 val(this, NULL);
6128 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6129 Struct_type::struct_method_tables.insert(val);
6131 Struct_method_table_pair* smtp;
6132 if (!ins.second)
6133 smtp = ins.first->second;
6134 else
6136 smtp = new Struct_method_table_pair();
6137 smtp->first = NULL;
6138 smtp->second = NULL;
6139 ins.first->second = smtp;
6142 return Type::interface_method_table(this, interface, is_pointer,
6143 &smtp->first, &smtp->second);
6146 // Convert struct fields to the backend representation. This is not
6147 // declared in types.h so that types.h doesn't have to #include
6148 // backend.h.
6150 static void
6151 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6152 bool use_placeholder,
6153 std::vector<Backend::Btyped_identifier>* bfields)
6155 bfields->resize(fields->size());
6156 size_t i = 0;
6157 for (Struct_field_list::const_iterator p = fields->begin();
6158 p != fields->end();
6159 ++p, ++i)
6161 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6162 (*bfields)[i].btype = (use_placeholder
6163 ? p->type()->get_backend_placeholder(gogo)
6164 : p->type()->get_backend(gogo));
6165 (*bfields)[i].location = p->location();
6167 go_assert(i == fields->size());
6170 // Get the backend representation for a struct type.
6172 Btype*
6173 Struct_type::do_get_backend(Gogo* gogo)
6175 std::vector<Backend::Btyped_identifier> bfields;
6176 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6177 return gogo->backend()->struct_type(bfields);
6180 // Finish the backend representation of the fields of a struct.
6182 void
6183 Struct_type::finish_backend_fields(Gogo* gogo)
6185 const Struct_field_list* fields = this->fields_;
6186 if (fields != NULL)
6188 for (Struct_field_list::const_iterator p = fields->begin();
6189 p != fields->end();
6190 ++p)
6191 p->type()->get_backend(gogo);
6195 // The type of a struct type descriptor.
6197 Type*
6198 Struct_type::make_struct_type_descriptor_type()
6200 static Type* ret;
6201 if (ret == NULL)
6203 Type* tdt = Type::make_type_descriptor_type();
6204 Type* ptdt = Type::make_type_descriptor_ptr_type();
6206 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6207 Type* string_type = Type::lookup_string_type();
6208 Type* pointer_string_type = Type::make_pointer_type(string_type);
6210 Struct_type* sf =
6211 Type::make_builtin_struct_type(5,
6212 "name", pointer_string_type,
6213 "pkgPath", pointer_string_type,
6214 "typ", ptdt,
6215 "tag", pointer_string_type,
6216 "offsetAnon", uintptr_type);
6217 Type* nsf = Type::make_builtin_named_type("structField", sf);
6219 Type* slice_type = Type::make_array_type(nsf, NULL);
6221 Struct_type* s = Type::make_builtin_struct_type(2,
6222 "", tdt,
6223 "fields", slice_type);
6225 ret = Type::make_builtin_named_type("StructType", s);
6228 return ret;
6231 // Build a type descriptor for a struct type.
6233 Expression*
6234 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6236 Location bloc = Linemap::predeclared_location();
6238 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6240 const Struct_field_list* fields = stdt->struct_type()->fields();
6242 Expression_list* vals = new Expression_list();
6243 vals->reserve(2);
6245 const Methods* methods = this->methods();
6246 // A named struct should not have methods--the methods should attach
6247 // to the named type.
6248 go_assert(methods == NULL || name == NULL);
6250 Struct_field_list::const_iterator ps = fields->begin();
6251 go_assert(ps->is_field_name("_type"));
6252 vals->push_back(this->type_descriptor_constructor(gogo,
6253 RUNTIME_TYPE_KIND_STRUCT,
6254 name, methods, true));
6256 ++ps;
6257 go_assert(ps->is_field_name("fields"));
6259 Expression_list* elements = new Expression_list();
6260 elements->reserve(this->fields_->size());
6261 Type* element_type = ps->type()->array_type()->element_type();
6262 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6263 pf != this->fields_->end();
6264 ++pf)
6266 const Struct_field_list* f = element_type->struct_type()->fields();
6268 Expression_list* fvals = new Expression_list();
6269 fvals->reserve(5);
6271 Struct_field_list::const_iterator q = f->begin();
6272 go_assert(q->is_field_name("name"));
6273 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6274 Expression* s = Expression::make_string(n, bloc);
6275 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6277 ++q;
6278 go_assert(q->is_field_name("pkgPath"));
6279 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6280 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6281 fvals->push_back(Expression::make_nil(bloc));
6282 else
6284 std::string n;
6285 if (is_embedded_builtin)
6286 n = gogo->package_name();
6287 else
6288 n = Gogo::hidden_name_pkgpath(pf->field_name());
6289 Expression* s = Expression::make_string(n, bloc);
6290 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6293 ++q;
6294 go_assert(q->is_field_name("typ"));
6295 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6297 ++q;
6298 go_assert(q->is_field_name("tag"));
6299 if (!pf->has_tag())
6300 fvals->push_back(Expression::make_nil(bloc));
6301 else
6303 Expression* s = Expression::make_string(pf->tag(), bloc);
6304 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6307 ++q;
6308 go_assert(q->is_field_name("offsetAnon"));
6309 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6310 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6311 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6312 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6313 int av = pf->is_anonymous() ? 1 : 0;
6314 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6315 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6316 fvals->push_back(o);
6318 Expression* v = Expression::make_struct_composite_literal(element_type,
6319 fvals, bloc);
6320 elements->push_back(v);
6323 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6324 elements, bloc));
6326 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6329 // Write the hash function for a struct which can not use the identity
6330 // function.
6332 void
6333 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6334 Function_type* hash_fntype,
6335 Function_type* equal_fntype)
6337 Location bloc = Linemap::predeclared_location();
6339 // The pointer to the struct that we are going to hash. This is an
6340 // argument to the hash function we are implementing here.
6341 Named_object* key_arg = gogo->lookup("key", NULL);
6342 go_assert(key_arg != NULL);
6343 Type* key_arg_type = key_arg->var_value()->type();
6345 // The seed argument to the hash function.
6346 Named_object* seed_arg = gogo->lookup("seed", NULL);
6347 go_assert(seed_arg != NULL);
6349 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6351 // Make a temporary to hold the return value, initialized to the seed.
6352 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6353 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6354 bloc);
6355 gogo->add_statement(retval);
6357 // Make a temporary to hold the key as a uintptr.
6358 ref = Expression::make_var_reference(key_arg, bloc);
6359 ref = Expression::make_cast(uintptr_type, ref, bloc);
6360 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6361 bloc);
6362 gogo->add_statement(key);
6364 // Loop over the struct fields.
6365 const Struct_field_list* fields = this->fields_;
6366 for (Struct_field_list::const_iterator pf = fields->begin();
6367 pf != fields->end();
6368 ++pf)
6370 if (Gogo::is_sink_name(pf->field_name()))
6371 continue;
6373 // Get a pointer to the value of this field.
6374 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6375 ref = Expression::make_temporary_reference(key, bloc);
6376 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6377 bloc);
6378 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6380 // Get the hash function to use for the type of this field.
6381 Named_object* hash_fn;
6382 Named_object* equal_fn;
6383 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6384 equal_fntype, &hash_fn, &equal_fn);
6386 // Call the hash function for the field, passing retval as the seed.
6387 ref = Expression::make_temporary_reference(retval, bloc);
6388 Expression_list* args = new Expression_list();
6389 args->push_back(subkey);
6390 args->push_back(ref);
6391 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6392 Expression* call = Expression::make_call(func, args, false, bloc);
6394 // Set retval to the result.
6395 Temporary_reference_expression* tref =
6396 Expression::make_temporary_reference(retval, bloc);
6397 tref->set_is_lvalue();
6398 Statement* s = Statement::make_assignment(tref, call, bloc);
6399 gogo->add_statement(s);
6402 // Return retval to the caller of the hash function.
6403 Expression_list* vals = new Expression_list();
6404 ref = Expression::make_temporary_reference(retval, bloc);
6405 vals->push_back(ref);
6406 Statement* s = Statement::make_return_statement(vals, bloc);
6407 gogo->add_statement(s);
6410 // Write the equality function for a struct which can not use the
6411 // identity function.
6413 void
6414 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6416 Location bloc = Linemap::predeclared_location();
6418 // The pointers to the structs we are going to compare.
6419 Named_object* key1_arg = gogo->lookup("key1", NULL);
6420 Named_object* key2_arg = gogo->lookup("key2", NULL);
6421 go_assert(key1_arg != NULL && key2_arg != NULL);
6423 // Build temporaries with the right types.
6424 Type* pt = Type::make_pointer_type(name != NULL
6425 ? static_cast<Type*>(name)
6426 : static_cast<Type*>(this));
6428 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6429 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6430 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6431 gogo->add_statement(p1);
6433 ref = Expression::make_var_reference(key2_arg, bloc);
6434 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6435 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6436 gogo->add_statement(p2);
6438 const Struct_field_list* fields = this->fields_;
6439 unsigned int field_index = 0;
6440 for (Struct_field_list::const_iterator pf = fields->begin();
6441 pf != fields->end();
6442 ++pf, ++field_index)
6444 if (Gogo::is_sink_name(pf->field_name()))
6445 continue;
6447 // Compare one field in both P1 and P2.
6448 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6449 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6450 bloc);
6451 f1 = Expression::make_field_reference(f1, field_index, bloc);
6453 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6454 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6455 bloc);
6456 f2 = Expression::make_field_reference(f2, field_index, bloc);
6458 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6460 // If the values are not equal, return false.
6461 gogo->start_block(bloc);
6462 Expression_list* vals = new Expression_list();
6463 vals->push_back(Expression::make_boolean(false, bloc));
6464 Statement* s = Statement::make_return_statement(vals, bloc);
6465 gogo->add_statement(s);
6466 Block* then_block = gogo->finish_block(bloc);
6468 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6469 gogo->add_statement(s);
6472 // All the fields are equal, so return true.
6473 Expression_list* vals = new Expression_list();
6474 vals->push_back(Expression::make_boolean(true, bloc));
6475 Statement* s = Statement::make_return_statement(vals, bloc);
6476 gogo->add_statement(s);
6479 // Reflection string.
6481 void
6482 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6484 ret->append("struct {");
6486 for (Struct_field_list::const_iterator p = this->fields_->begin();
6487 p != this->fields_->end();
6488 ++p)
6490 if (p != this->fields_->begin())
6491 ret->push_back(';');
6492 ret->push_back(' ');
6493 if (!p->is_anonymous())
6495 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6496 ret->push_back(' ');
6498 if (p->is_anonymous()
6499 && p->type()->named_type() != NULL
6500 && p->type()->named_type()->is_alias())
6501 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6502 else
6503 this->append_reflection(p->type(), gogo, ret);
6505 if (p->has_tag())
6507 const std::string& tag(p->tag());
6508 ret->append(" \"");
6509 for (std::string::const_iterator p = tag.begin();
6510 p != tag.end();
6511 ++p)
6513 if (*p == '\0')
6514 ret->append("\\x00");
6515 else if (*p == '\n')
6516 ret->append("\\n");
6517 else if (*p == '\t')
6518 ret->append("\\t");
6519 else if (*p == '"')
6520 ret->append("\\\"");
6521 else if (*p == '\\')
6522 ret->append("\\\\");
6523 else
6524 ret->push_back(*p);
6526 ret->push_back('"');
6530 if (!this->fields_->empty())
6531 ret->push_back(' ');
6533 ret->push_back('}');
6536 // If the offset of field INDEX in the backend implementation can be
6537 // determined, set *POFFSET to the offset in bytes and return true.
6538 // Otherwise, return false.
6540 bool
6541 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6542 int64_t* poffset)
6544 if (!this->is_backend_type_size_known(gogo))
6545 return false;
6546 Btype* bt = this->get_backend_placeholder(gogo);
6547 *poffset = gogo->backend()->type_field_offset(bt, index);
6548 return true;
6551 // Export.
6553 void
6554 Struct_type::do_export(Export* exp) const
6556 exp->write_c_string("struct { ");
6557 const Struct_field_list* fields = this->fields_;
6558 go_assert(fields != NULL);
6559 for (Struct_field_list::const_iterator p = fields->begin();
6560 p != fields->end();
6561 ++p)
6563 if (p->is_anonymous())
6564 exp->write_string("? ");
6565 else
6567 exp->write_string(p->field_name());
6568 exp->write_c_string(" ");
6570 exp->write_type(p->type());
6572 if (p->has_tag())
6574 exp->write_c_string(" ");
6575 Expression* expr =
6576 Expression::make_string(p->tag(), Linemap::predeclared_location());
6577 expr->export_expression(exp);
6578 delete expr;
6581 exp->write_c_string("; ");
6583 exp->write_c_string("}");
6586 // Import.
6588 Struct_type*
6589 Struct_type::do_import(Import* imp)
6591 imp->require_c_string("struct { ");
6592 Struct_field_list* fields = new Struct_field_list;
6593 if (imp->peek_char() != '}')
6595 while (true)
6597 std::string name;
6598 if (imp->match_c_string("? "))
6599 imp->advance(2);
6600 else
6602 name = imp->read_identifier();
6603 imp->require_c_string(" ");
6605 Type* ftype = imp->read_type();
6607 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6608 sf.set_is_imported();
6610 if (imp->peek_char() == ' ')
6612 imp->advance(1);
6613 Expression* expr = Expression::import_expression(imp);
6614 String_expression* sexpr = expr->string_expression();
6615 go_assert(sexpr != NULL);
6616 sf.set_tag(sexpr->val());
6617 delete sexpr;
6620 imp->require_c_string("; ");
6621 fields->push_back(sf);
6622 if (imp->peek_char() == '}')
6623 break;
6626 imp->require_c_string("}");
6628 return Type::make_struct_type(fields, imp->location());
6631 // Whether we can write this struct type to a C header file.
6632 // We can't if any of the fields are structs defined in a different package.
6634 bool
6635 Struct_type::can_write_to_c_header(
6636 std::vector<const Named_object*>* requires,
6637 std::vector<const Named_object*>* declare) const
6639 const Struct_field_list* fields = this->fields_;
6640 if (fields == NULL || fields->empty())
6641 return false;
6642 int sinks = 0;
6643 for (Struct_field_list::const_iterator p = fields->begin();
6644 p != fields->end();
6645 ++p)
6647 if (p->is_anonymous())
6648 return false;
6649 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6650 return false;
6651 if (Gogo::message_name(p->field_name()) == "_")
6652 sinks++;
6654 if (sinks > 1)
6655 return false;
6656 return true;
6659 // Whether we can write the type T to a C header file.
6661 bool
6662 Struct_type::can_write_type_to_c_header(
6663 const Type* t,
6664 std::vector<const Named_object*>* requires,
6665 std::vector<const Named_object*>* declare) const
6667 t = t->forwarded();
6668 switch (t->classification())
6670 case TYPE_ERROR:
6671 case TYPE_FORWARD:
6672 return false;
6674 case TYPE_VOID:
6675 case TYPE_BOOLEAN:
6676 case TYPE_INTEGER:
6677 case TYPE_FLOAT:
6678 case TYPE_COMPLEX:
6679 case TYPE_STRING:
6680 case TYPE_FUNCTION:
6681 case TYPE_MAP:
6682 case TYPE_CHANNEL:
6683 case TYPE_INTERFACE:
6684 return true;
6686 case TYPE_POINTER:
6687 // Don't try to handle a pointer to an array.
6688 if (t->points_to()->array_type() != NULL
6689 && !t->points_to()->is_slice_type())
6690 return false;
6692 if (t->points_to()->named_type() != NULL
6693 && t->points_to()->struct_type() != NULL)
6694 declare->push_back(t->points_to()->named_type()->named_object());
6695 return true;
6697 case TYPE_STRUCT:
6698 return t->struct_type()->can_write_to_c_header(requires, declare);
6700 case TYPE_ARRAY:
6701 if (t->is_slice_type())
6702 return true;
6703 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6704 requires, declare);
6706 case TYPE_NAMED:
6708 const Named_object* no = t->named_type()->named_object();
6709 if (no->package() != NULL)
6711 if (t->is_unsafe_pointer_type())
6712 return true;
6713 return false;
6715 if (t->struct_type() != NULL)
6717 requires->push_back(no);
6718 return t->struct_type()->can_write_to_c_header(requires, declare);
6720 return this->can_write_type_to_c_header(t->base(), requires, declare);
6723 case TYPE_CALL_MULTIPLE_RESULT:
6724 case TYPE_NIL:
6725 case TYPE_SINK:
6726 default:
6727 go_unreachable();
6731 // Write this struct to a C header file.
6733 void
6734 Struct_type::write_to_c_header(std::ostream& os) const
6736 const Struct_field_list* fields = this->fields_;
6737 for (Struct_field_list::const_iterator p = fields->begin();
6738 p != fields->end();
6739 ++p)
6741 os << '\t';
6742 this->write_field_to_c_header(os, p->field_name(), p->type());
6743 os << ';' << std::endl;
6747 // Write the type of a struct field to a C header file.
6749 void
6750 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6751 const Type *t) const
6753 bool print_name = true;
6754 t = t->forwarded();
6755 switch (t->classification())
6757 case TYPE_VOID:
6758 os << "void";
6759 break;
6761 case TYPE_BOOLEAN:
6762 os << "_Bool";
6763 break;
6765 case TYPE_INTEGER:
6767 const Integer_type* it = t->integer_type();
6768 if (it->is_unsigned())
6769 os << 'u';
6770 os << "int" << it->bits() << "_t";
6772 break;
6774 case TYPE_FLOAT:
6775 switch (t->float_type()->bits())
6777 case 32:
6778 os << "float";
6779 break;
6780 case 64:
6781 os << "double";
6782 break;
6783 default:
6784 go_unreachable();
6786 break;
6788 case TYPE_COMPLEX:
6789 switch (t->complex_type()->bits())
6791 case 64:
6792 os << "float _Complex";
6793 break;
6794 case 128:
6795 os << "double _Complex";
6796 break;
6797 default:
6798 go_unreachable();
6800 break;
6802 case TYPE_STRING:
6803 os << "String";
6804 break;
6806 case TYPE_FUNCTION:
6807 os << "FuncVal*";
6808 break;
6810 case TYPE_POINTER:
6812 std::vector<const Named_object*> requires;
6813 std::vector<const Named_object*> declare;
6814 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6815 &declare))
6816 os << "void*";
6817 else
6819 this->write_field_to_c_header(os, "", t->points_to());
6820 os << '*';
6823 break;
6825 case TYPE_MAP:
6826 os << "Map*";
6827 break;
6829 case TYPE_CHANNEL:
6830 os << "Chan*";
6831 break;
6833 case TYPE_INTERFACE:
6834 if (t->interface_type()->is_empty())
6835 os << "Eface";
6836 else
6837 os << "Iface";
6838 break;
6840 case TYPE_STRUCT:
6841 os << "struct {" << std::endl;
6842 t->struct_type()->write_to_c_header(os);
6843 os << "\t}";
6844 break;
6846 case TYPE_ARRAY:
6847 if (t->is_slice_type())
6848 os << "Slice";
6849 else
6851 const Type *ele = t;
6852 std::vector<const Type*> array_types;
6853 while (ele->array_type() != NULL && !ele->is_slice_type())
6855 array_types.push_back(ele);
6856 ele = ele->array_type()->element_type();
6858 this->write_field_to_c_header(os, "", ele);
6859 os << ' ' << Gogo::message_name(name);
6860 print_name = false;
6861 while (!array_types.empty())
6863 ele = array_types.back();
6864 array_types.pop_back();
6865 os << '[';
6866 Numeric_constant nc;
6867 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6868 go_unreachable();
6869 mpz_t val;
6870 if (!nc.to_int(&val))
6871 go_unreachable();
6872 char* s = mpz_get_str(NULL, 10, val);
6873 os << s;
6874 free(s);
6875 mpz_clear(val);
6876 os << ']';
6879 break;
6881 case TYPE_NAMED:
6883 const Named_object* no = t->named_type()->named_object();
6884 if (t->struct_type() != NULL)
6885 os << "struct " << no->message_name();
6886 else if (t->is_unsafe_pointer_type())
6887 os << "void*";
6888 else if (t == Type::lookup_integer_type("uintptr"))
6889 os << "uintptr_t";
6890 else
6892 this->write_field_to_c_header(os, name, t->base());
6893 print_name = false;
6896 break;
6898 case TYPE_ERROR:
6899 case TYPE_FORWARD:
6900 case TYPE_CALL_MULTIPLE_RESULT:
6901 case TYPE_NIL:
6902 case TYPE_SINK:
6903 default:
6904 go_unreachable();
6907 if (print_name && !name.empty())
6908 os << ' ' << Gogo::message_name(name);
6911 // Make a struct type.
6913 Struct_type*
6914 Type::make_struct_type(Struct_field_list* fields,
6915 Location location)
6917 return new Struct_type(fields, location);
6920 // Class Array_type.
6922 // Store the length of an array as an int64_t into *PLEN. Return
6923 // false if the length can not be determined. This will assert if
6924 // called for a slice.
6926 bool
6927 Array_type::int_length(int64_t* plen)
6929 go_assert(this->length_ != NULL);
6930 Numeric_constant nc;
6931 if (!this->length_->numeric_constant_value(&nc))
6932 return false;
6933 return nc.to_memory_size(plen);
6936 // Whether two array types are identical.
6938 bool
6939 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6940 bool errors_are_identical) const
6942 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6943 cmp_tags, errors_are_identical, NULL))
6944 return false;
6946 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6947 return false;
6949 Expression* l1 = this->length();
6950 Expression* l2 = t->length();
6952 // Slices of the same element type are identical.
6953 if (l1 == NULL && l2 == NULL)
6954 return true;
6956 // Arrays of the same element type are identical if they have the
6957 // same length.
6958 if (l1 != NULL && l2 != NULL)
6960 if (l1 == l2)
6961 return true;
6963 // Try to determine the lengths. If we can't, assume the arrays
6964 // are not identical.
6965 bool ret = false;
6966 Numeric_constant nc1, nc2;
6967 if (l1->numeric_constant_value(&nc1)
6968 && l2->numeric_constant_value(&nc2))
6970 mpz_t v1;
6971 if (nc1.to_int(&v1))
6973 mpz_t v2;
6974 if (nc2.to_int(&v2))
6976 ret = mpz_cmp(v1, v2) == 0;
6977 mpz_clear(v2);
6979 mpz_clear(v1);
6982 return ret;
6985 // Otherwise the arrays are not identical.
6986 return false;
6989 // Traversal.
6992 Array_type::do_traverse(Traverse* traverse)
6994 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6995 return TRAVERSE_EXIT;
6996 if (this->length_ != NULL
6997 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6998 return TRAVERSE_EXIT;
6999 return TRAVERSE_CONTINUE;
7002 // Check that the length is valid.
7004 bool
7005 Array_type::verify_length()
7007 if (this->length_ == NULL)
7008 return true;
7010 Type_context context(Type::lookup_integer_type("int"), false);
7011 this->length_->determine_type(&context);
7013 if (!this->length_->is_constant())
7015 go_error_at(this->length_->location(), "array bound is not constant");
7016 return false;
7019 // For array types, the length expression can be an untyped constant
7020 // representable as an int, but we don't allow explicitly non-integer
7021 // values such as "float64(10)". See issues #13485 and #13486.
7022 if (this->length_->type()->integer_type() == NULL
7023 && !this->length_->type()->is_error_type())
7025 go_error_at(this->length_->location(), "invalid array bound");
7026 return false;
7029 Numeric_constant nc;
7030 if (!this->length_->numeric_constant_value(&nc))
7032 if (this->length_->type()->integer_type() != NULL
7033 || this->length_->type()->float_type() != NULL)
7034 go_error_at(this->length_->location(), "array bound is not constant");
7035 else
7036 go_error_at(this->length_->location(), "array bound is not numeric");
7037 return false;
7040 Type* int_type = Type::lookup_integer_type("int");
7041 unsigned int tbits = int_type->integer_type()->bits();
7042 unsigned long val;
7043 switch (nc.to_unsigned_long(&val))
7045 case Numeric_constant::NC_UL_VALID:
7046 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7048 go_error_at(this->length_->location(), "array bound overflows");
7049 return false;
7051 break;
7052 case Numeric_constant::NC_UL_NOTINT:
7053 go_error_at(this->length_->location(), "array bound truncated to integer");
7054 return false;
7055 case Numeric_constant::NC_UL_NEGATIVE:
7056 go_error_at(this->length_->location(), "negative array bound");
7057 return false;
7058 case Numeric_constant::NC_UL_BIG:
7060 mpz_t val;
7061 if (!nc.to_int(&val))
7062 go_unreachable();
7063 unsigned int bits = mpz_sizeinbase(val, 2);
7064 mpz_clear(val);
7065 if (bits >= tbits)
7067 go_error_at(this->length_->location(), "array bound overflows");
7068 return false;
7071 break;
7072 default:
7073 go_unreachable();
7076 return true;
7079 // Verify the type.
7081 bool
7082 Array_type::do_verify()
7084 if (this->element_type()->is_error_type())
7085 return false;
7086 if (!this->verify_length())
7087 this->length_ = Expression::make_error(this->length_->location());
7088 return true;
7091 // Whether the type contains pointers. This is always true for a
7092 // slice. For an array it is true if the element type has pointers
7093 // and the length is greater than zero.
7095 bool
7096 Array_type::do_has_pointer() const
7098 if (this->length_ == NULL)
7099 return true;
7100 if (!this->element_type_->has_pointer())
7101 return false;
7103 Numeric_constant nc;
7104 if (!this->length_->numeric_constant_value(&nc))
7106 // Error reported elsewhere.
7107 return false;
7110 unsigned long val;
7111 switch (nc.to_unsigned_long(&val))
7113 case Numeric_constant::NC_UL_VALID:
7114 return val > 0;
7115 case Numeric_constant::NC_UL_BIG:
7116 return true;
7117 default:
7118 // Error reported elsewhere.
7119 return false;
7123 // Whether we can use memcmp to compare this array.
7125 bool
7126 Array_type::do_compare_is_identity(Gogo* gogo)
7128 if (this->length_ == NULL)
7129 return false;
7131 // Check for [...], which indicates that this is not a real type.
7132 if (this->length_->is_nil_expression())
7133 return false;
7135 if (!this->element_type_->compare_is_identity(gogo))
7136 return false;
7138 // If there is any padding, then we can't use memcmp.
7139 int64_t size;
7140 int64_t align;
7141 if (!this->element_type_->backend_type_size(gogo, &size)
7142 || !this->element_type_->backend_type_align(gogo, &align))
7143 return false;
7144 if ((size & (align - 1)) != 0)
7145 return false;
7147 return true;
7150 // Array type hash code.
7152 unsigned int
7153 Array_type::do_hash_for_method(Gogo* gogo) const
7155 unsigned int ret;
7157 // There is no very convenient way to get a hash code for the
7158 // length.
7159 ret = this->element_type_->hash_for_method(gogo) + 1;
7160 if (this->is_array_incomparable_)
7161 ret <<= 1;
7162 return ret;
7165 // Write the hash function for an array which can not use the identify
7166 // function.
7168 void
7169 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7170 Function_type* hash_fntype,
7171 Function_type* equal_fntype)
7173 Location bloc = Linemap::predeclared_location();
7175 // The pointer to the array that we are going to hash. This is an
7176 // argument to the hash function we are implementing here.
7177 Named_object* key_arg = gogo->lookup("key", NULL);
7178 go_assert(key_arg != NULL);
7179 Type* key_arg_type = key_arg->var_value()->type();
7181 // The seed argument to the hash function.
7182 Named_object* seed_arg = gogo->lookup("seed", NULL);
7183 go_assert(seed_arg != NULL);
7185 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7187 // Make a temporary to hold the return value, initialized to the seed.
7188 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7189 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7190 bloc);
7191 gogo->add_statement(retval);
7193 // Make a temporary to hold the key as a uintptr.
7194 ref = Expression::make_var_reference(key_arg, bloc);
7195 ref = Expression::make_cast(uintptr_type, ref, bloc);
7196 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7197 bloc);
7198 gogo->add_statement(key);
7200 // Loop over the array elements.
7201 // for i = range a
7202 Type* int_type = Type::lookup_integer_type("int");
7203 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7204 gogo->add_statement(index);
7206 Expression* iref = Expression::make_temporary_reference(index, bloc);
7207 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7208 Type* pt = Type::make_pointer_type(name != NULL
7209 ? static_cast<Type*>(name)
7210 : static_cast<Type*>(this));
7211 aref = Expression::make_cast(pt, aref, bloc);
7212 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7213 NULL,
7214 aref,
7215 bloc);
7217 gogo->start_block(bloc);
7219 // Get the hash function for the element type.
7220 Named_object* hash_fn;
7221 Named_object* equal_fn;
7222 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7223 hash_fntype, equal_fntype, &hash_fn,
7224 &equal_fn);
7226 // Get a pointer to this element in the loop.
7227 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7228 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7230 // Get the size of each element.
7231 Expression* ele_size = Expression::make_type_info(this->element_type_,
7232 Expression::TYPE_INFO_SIZE);
7234 // Get the hash of this element, passing retval as the seed.
7235 ref = Expression::make_temporary_reference(retval, bloc);
7236 Expression_list* args = new Expression_list();
7237 args->push_back(subkey);
7238 args->push_back(ref);
7239 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7240 Expression* call = Expression::make_call(func, args, false, bloc);
7242 // Set retval to the result.
7243 Temporary_reference_expression* tref =
7244 Expression::make_temporary_reference(retval, bloc);
7245 tref->set_is_lvalue();
7246 Statement* s = Statement::make_assignment(tref, call, bloc);
7247 gogo->add_statement(s);
7249 // Increase the element pointer.
7250 tref = Expression::make_temporary_reference(key, bloc);
7251 tref->set_is_lvalue();
7252 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7253 bloc);
7254 Block* statements = gogo->finish_block(bloc);
7256 for_range->add_statements(statements);
7257 gogo->add_statement(for_range);
7259 // Return retval to the caller of the hash function.
7260 Expression_list* vals = new Expression_list();
7261 ref = Expression::make_temporary_reference(retval, bloc);
7262 vals->push_back(ref);
7263 s = Statement::make_return_statement(vals, bloc);
7264 gogo->add_statement(s);
7267 // Write the equality function for an array which can not use the
7268 // identity function.
7270 void
7271 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7273 Location bloc = Linemap::predeclared_location();
7275 // The pointers to the arrays we are going to compare.
7276 Named_object* key1_arg = gogo->lookup("key1", NULL);
7277 Named_object* key2_arg = gogo->lookup("key2", NULL);
7278 go_assert(key1_arg != NULL && key2_arg != NULL);
7280 // Build temporaries for the keys with the right types.
7281 Type* pt = Type::make_pointer_type(name != NULL
7282 ? static_cast<Type*>(name)
7283 : static_cast<Type*>(this));
7285 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7286 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7287 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7288 gogo->add_statement(p1);
7290 ref = Expression::make_var_reference(key2_arg, bloc);
7291 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7292 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7293 gogo->add_statement(p2);
7295 // Loop over the array elements.
7296 // for i = range a
7297 Type* int_type = Type::lookup_integer_type("int");
7298 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7299 gogo->add_statement(index);
7301 Expression* iref = Expression::make_temporary_reference(index, bloc);
7302 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7303 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7304 NULL,
7305 aref,
7306 bloc);
7308 gogo->start_block(bloc);
7310 // Compare element in P1 and P2.
7311 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7312 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7313 ref = Expression::make_temporary_reference(index, bloc);
7314 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7316 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7317 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7318 ref = Expression::make_temporary_reference(index, bloc);
7319 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7321 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7323 // If the elements are not equal, return false.
7324 gogo->start_block(bloc);
7325 Expression_list* vals = new Expression_list();
7326 vals->push_back(Expression::make_boolean(false, bloc));
7327 Statement* s = Statement::make_return_statement(vals, bloc);
7328 gogo->add_statement(s);
7329 Block* then_block = gogo->finish_block(bloc);
7331 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7332 gogo->add_statement(s);
7334 Block* statements = gogo->finish_block(bloc);
7336 for_range->add_statements(statements);
7337 gogo->add_statement(for_range);
7339 // All the elements are equal, so return true.
7340 vals = new Expression_list();
7341 vals->push_back(Expression::make_boolean(true, bloc));
7342 s = Statement::make_return_statement(vals, bloc);
7343 gogo->add_statement(s);
7346 // Get the backend representation of the fields of a slice. This is
7347 // not declared in types.h so that types.h doesn't have to #include
7348 // backend.h.
7350 // We use int for the count and capacity fields. This matches 6g.
7351 // The language more or less assumes that we can't allocate space of a
7352 // size which does not fit in int.
7354 static void
7355 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7356 std::vector<Backend::Btyped_identifier>* bfields)
7358 bfields->resize(3);
7360 Type* pet = Type::make_pointer_type(type->element_type());
7361 Btype* pbet = (use_placeholder
7362 ? pet->get_backend_placeholder(gogo)
7363 : pet->get_backend(gogo));
7364 Location ploc = Linemap::predeclared_location();
7366 Backend::Btyped_identifier* p = &(*bfields)[0];
7367 p->name = "__values";
7368 p->btype = pbet;
7369 p->location = ploc;
7371 Type* int_type = Type::lookup_integer_type("int");
7373 p = &(*bfields)[1];
7374 p->name = "__count";
7375 p->btype = int_type->get_backend(gogo);
7376 p->location = ploc;
7378 p = &(*bfields)[2];
7379 p->name = "__capacity";
7380 p->btype = int_type->get_backend(gogo);
7381 p->location = ploc;
7384 // Get the backend representation for the type of this array. A fixed array is
7385 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7386 // just like an array in C. An open array is a struct with three
7387 // fields: a data pointer, the length, and the capacity.
7389 Btype*
7390 Array_type::do_get_backend(Gogo* gogo)
7392 if (this->length_ == NULL)
7394 std::vector<Backend::Btyped_identifier> bfields;
7395 get_backend_slice_fields(gogo, this, false, &bfields);
7396 return gogo->backend()->struct_type(bfields);
7398 else
7400 Btype* element = this->get_backend_element(gogo, false);
7401 Bexpression* len = this->get_backend_length(gogo);
7402 return gogo->backend()->array_type(element, len);
7406 // Return the backend representation of the element type.
7408 Btype*
7409 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7411 if (use_placeholder)
7412 return this->element_type_->get_backend_placeholder(gogo);
7413 else
7414 return this->element_type_->get_backend(gogo);
7417 // Return the backend representation of the length. The length may be
7418 // computed using a function call, so we must only evaluate it once.
7420 Bexpression*
7421 Array_type::get_backend_length(Gogo* gogo)
7423 go_assert(this->length_ != NULL);
7424 if (this->blength_ == NULL)
7426 if (this->length_->is_error_expression())
7428 this->blength_ = gogo->backend()->error_expression();
7429 return this->blength_;
7431 Numeric_constant nc;
7432 mpz_t val;
7433 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7435 if (mpz_sgn(val) < 0)
7437 this->blength_ = gogo->backend()->error_expression();
7438 return this->blength_;
7440 Type* t = nc.type();
7441 if (t == NULL)
7442 t = Type::lookup_integer_type("int");
7443 else if (t->is_abstract())
7444 t = t->make_non_abstract_type();
7445 Btype* btype = t->get_backend(gogo);
7446 this->blength_ =
7447 gogo->backend()->integer_constant_expression(btype, val);
7448 mpz_clear(val);
7450 else
7452 // Make up a translation context for the array length
7453 // expression. FIXME: This won't work in general.
7454 Translate_context context(gogo, NULL, NULL, NULL);
7455 this->blength_ = this->length_->get_backend(&context);
7457 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7458 this->blength_ =
7459 gogo->backend()->convert_expression(ibtype, this->blength_,
7460 this->length_->location());
7463 return this->blength_;
7466 // Finish backend representation of the array.
7468 void
7469 Array_type::finish_backend_element(Gogo* gogo)
7471 Type* et = this->array_type()->element_type();
7472 et->get_backend(gogo);
7473 if (this->is_slice_type())
7475 // This relies on the fact that we always use the same
7476 // structure for a pointer to any given type.
7477 Type* pet = Type::make_pointer_type(et);
7478 pet->get_backend(gogo);
7482 // Return an expression for a pointer to the values in ARRAY.
7484 Expression*
7485 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7487 if (this->length() != NULL)
7489 // Fixed array.
7490 go_assert(array->type()->array_type() != NULL);
7491 Type* etype = array->type()->array_type()->element_type();
7492 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7493 return Expression::make_cast(Type::make_pointer_type(etype), array,
7494 array->location());
7497 // Slice.
7499 if (is_lvalue)
7501 Temporary_reference_expression* tref =
7502 array->temporary_reference_expression();
7503 Var_expression* ve = array->var_expression();
7504 if (tref != NULL)
7506 tref = tref->copy()->temporary_reference_expression();
7507 tref->set_is_lvalue();
7508 array = tref;
7510 else if (ve != NULL)
7512 ve = new Var_expression(ve->named_object(), ve->location());
7513 array = ve;
7517 return Expression::make_slice_info(array,
7518 Expression::SLICE_INFO_VALUE_POINTER,
7519 array->location());
7522 // Return an expression for the length of the array ARRAY which has this
7523 // type.
7525 Expression*
7526 Array_type::get_length(Gogo*, Expression* array) const
7528 if (this->length_ != NULL)
7529 return this->length_;
7531 // This is a slice. We need to read the length field.
7532 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7533 array->location());
7536 // Return an expression for the capacity of the array ARRAY which has this
7537 // type.
7539 Expression*
7540 Array_type::get_capacity(Gogo*, Expression* array) const
7542 if (this->length_ != NULL)
7543 return this->length_;
7545 // This is a slice. We need to read the capacity field.
7546 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7547 array->location());
7550 // Export.
7552 void
7553 Array_type::do_export(Export* exp) const
7555 exp->write_c_string("[");
7556 if (this->length_ != NULL)
7557 this->length_->export_expression(exp);
7558 exp->write_c_string("] ");
7559 exp->write_type(this->element_type_);
7562 // Import.
7564 Array_type*
7565 Array_type::do_import(Import* imp)
7567 imp->require_c_string("[");
7568 Expression* length;
7569 if (imp->peek_char() == ']')
7570 length = NULL;
7571 else
7572 length = Expression::import_expression(imp);
7573 imp->require_c_string("] ");
7574 Type* element_type = imp->read_type();
7575 return Type::make_array_type(element_type, length);
7578 // The type of an array type descriptor.
7580 Type*
7581 Array_type::make_array_type_descriptor_type()
7583 static Type* ret;
7584 if (ret == NULL)
7586 Type* tdt = Type::make_type_descriptor_type();
7587 Type* ptdt = Type::make_type_descriptor_ptr_type();
7589 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7591 Struct_type* sf =
7592 Type::make_builtin_struct_type(4,
7593 "", tdt,
7594 "elem", ptdt,
7595 "slice", ptdt,
7596 "len", uintptr_type);
7598 ret = Type::make_builtin_named_type("ArrayType", sf);
7601 return ret;
7604 // The type of an slice type descriptor.
7606 Type*
7607 Array_type::make_slice_type_descriptor_type()
7609 static Type* ret;
7610 if (ret == NULL)
7612 Type* tdt = Type::make_type_descriptor_type();
7613 Type* ptdt = Type::make_type_descriptor_ptr_type();
7615 Struct_type* sf =
7616 Type::make_builtin_struct_type(2,
7617 "", tdt,
7618 "elem", ptdt);
7620 ret = Type::make_builtin_named_type("SliceType", sf);
7623 return ret;
7626 // Build a type descriptor for an array/slice type.
7628 Expression*
7629 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7631 if (this->length_ != NULL)
7632 return this->array_type_descriptor(gogo, name);
7633 else
7634 return this->slice_type_descriptor(gogo, name);
7637 // Build a type descriptor for an array type.
7639 Expression*
7640 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7642 Location bloc = Linemap::predeclared_location();
7644 Type* atdt = Array_type::make_array_type_descriptor_type();
7646 const Struct_field_list* fields = atdt->struct_type()->fields();
7648 Expression_list* vals = new Expression_list();
7649 vals->reserve(3);
7651 Struct_field_list::const_iterator p = fields->begin();
7652 go_assert(p->is_field_name("_type"));
7653 vals->push_back(this->type_descriptor_constructor(gogo,
7654 RUNTIME_TYPE_KIND_ARRAY,
7655 name, NULL, true));
7657 ++p;
7658 go_assert(p->is_field_name("elem"));
7659 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7661 ++p;
7662 go_assert(p->is_field_name("slice"));
7663 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7664 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7666 ++p;
7667 go_assert(p->is_field_name("len"));
7668 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7670 ++p;
7671 go_assert(p == fields->end());
7673 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7676 // Build a type descriptor for a slice type.
7678 Expression*
7679 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7681 Location bloc = Linemap::predeclared_location();
7683 Type* stdt = Array_type::make_slice_type_descriptor_type();
7685 const Struct_field_list* fields = stdt->struct_type()->fields();
7687 Expression_list* vals = new Expression_list();
7688 vals->reserve(2);
7690 Struct_field_list::const_iterator p = fields->begin();
7691 go_assert(p->is_field_name("_type"));
7692 vals->push_back(this->type_descriptor_constructor(gogo,
7693 RUNTIME_TYPE_KIND_SLICE,
7694 name, NULL, true));
7696 ++p;
7697 go_assert(p->is_field_name("elem"));
7698 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7700 ++p;
7701 go_assert(p == fields->end());
7703 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7706 // Reflection string.
7708 void
7709 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7711 ret->push_back('[');
7712 if (this->length_ != NULL)
7714 Numeric_constant nc;
7715 if (!this->length_->numeric_constant_value(&nc))
7717 go_assert(saw_errors());
7718 return;
7720 mpz_t val;
7721 if (!nc.to_int(&val))
7723 go_assert(saw_errors());
7724 return;
7726 char* s = mpz_get_str(NULL, 10, val);
7727 ret->append(s);
7728 free(s);
7729 mpz_clear(val);
7731 ret->push_back(']');
7733 this->append_reflection(this->element_type_, gogo, ret);
7736 // Make an array type.
7738 Array_type*
7739 Type::make_array_type(Type* element_type, Expression* length)
7741 return new Array_type(element_type, length);
7744 // Class Map_type.
7746 Named_object* Map_type::zero_value;
7747 int64_t Map_type::zero_value_size;
7748 int64_t Map_type::zero_value_align;
7750 // If this map requires the "fat" functions, return the pointer to
7751 // pass as the zero value to those functions. Otherwise, in the
7752 // normal case, return NULL. The map requires the "fat" functions if
7753 // the value size is larger than max_zero_size bytes. max_zero_size
7754 // must match maxZero in libgo/go/runtime/hashmap.go.
7756 Expression*
7757 Map_type::fat_zero_value(Gogo* gogo)
7759 int64_t valsize;
7760 if (!this->val_type_->backend_type_size(gogo, &valsize))
7762 go_assert(saw_errors());
7763 return NULL;
7765 if (valsize <= Map_type::max_zero_size)
7766 return NULL;
7768 if (Map_type::zero_value_size < valsize)
7769 Map_type::zero_value_size = valsize;
7771 int64_t valalign;
7772 if (!this->val_type_->backend_type_align(gogo, &valalign))
7774 go_assert(saw_errors());
7775 return NULL;
7778 if (Map_type::zero_value_align < valalign)
7779 Map_type::zero_value_align = valalign;
7781 Location bloc = Linemap::predeclared_location();
7783 if (Map_type::zero_value == NULL)
7785 // The final type will be set in backend_zero_value.
7786 Type* uint8_type = Type::lookup_integer_type("uint8");
7787 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7788 Array_type* array_type = Type::make_array_type(uint8_type, size);
7789 array_type->set_is_array_incomparable();
7790 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7791 std::string name = gogo->map_zero_value_name();
7792 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7795 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7796 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7797 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7798 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7799 return z;
7802 // Return whether VAR is the map zero value.
7804 bool
7805 Map_type::is_zero_value(Variable* var)
7807 return (Map_type::zero_value != NULL
7808 && Map_type::zero_value->var_value() == var);
7811 // Return the backend representation for the zero value.
7813 Bvariable*
7814 Map_type::backend_zero_value(Gogo* gogo)
7816 Location bloc = Linemap::predeclared_location();
7818 go_assert(Map_type::zero_value != NULL);
7820 Type* uint8_type = Type::lookup_integer_type("uint8");
7821 Btype* buint8_type = uint8_type->get_backend(gogo);
7823 Type* int_type = Type::lookup_integer_type("int");
7825 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7826 int_type, bloc);
7827 Translate_context context(gogo, NULL, NULL, NULL);
7828 Bexpression* blength = e->get_backend(&context);
7830 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7832 std::string zname = Map_type::zero_value->name();
7833 std::string asm_name(go_selectively_encode_id(zname));
7834 Bvariable* zvar =
7835 gogo->backend()->implicit_variable(zname, asm_name,
7836 barray_type, false, false, true,
7837 Map_type::zero_value_align);
7838 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7839 false, false, true, NULL);
7840 return zvar;
7843 // Traversal.
7846 Map_type::do_traverse(Traverse* traverse)
7848 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7849 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7850 return TRAVERSE_EXIT;
7851 return TRAVERSE_CONTINUE;
7854 // Check that the map type is OK.
7856 bool
7857 Map_type::do_verify()
7859 // The runtime support uses "map[void]void".
7860 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7861 go_error_at(this->location_, "invalid map key type");
7862 if (!this->key_type_->in_heap())
7863 go_error_at(this->location_, "go:notinheap map key not allowed");
7864 if (!this->val_type_->in_heap())
7865 go_error_at(this->location_, "go:notinheap map value not allowed");
7866 return true;
7869 // Whether two map types are identical.
7871 bool
7872 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7873 bool errors_are_identical) const
7875 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7876 cmp_tags, errors_are_identical, NULL)
7877 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7878 cmp_tags, errors_are_identical,
7879 NULL));
7882 // Hash code.
7884 unsigned int
7885 Map_type::do_hash_for_method(Gogo* gogo) const
7887 return (this->key_type_->hash_for_method(gogo)
7888 + this->val_type_->hash_for_method(gogo)
7889 + 2);
7892 // Get the backend representation for a map type. A map type is
7893 // represented as a pointer to a struct. The struct is hmap in
7894 // runtime/hashmap.go.
7896 Btype*
7897 Map_type::do_get_backend(Gogo* gogo)
7899 static Btype* backend_map_type;
7900 if (backend_map_type == NULL)
7902 std::vector<Backend::Btyped_identifier> bfields(9);
7904 Location bloc = Linemap::predeclared_location();
7906 Type* int_type = Type::lookup_integer_type("int");
7907 bfields[0].name = "count";
7908 bfields[0].btype = int_type->get_backend(gogo);
7909 bfields[0].location = bloc;
7911 Type* uint8_type = Type::lookup_integer_type("uint8");
7912 bfields[1].name = "flags";
7913 bfields[1].btype = uint8_type->get_backend(gogo);
7914 bfields[1].location = bloc;
7916 bfields[2].name = "B";
7917 bfields[2].btype = bfields[1].btype;
7918 bfields[2].location = bloc;
7920 Type* uint16_type = Type::lookup_integer_type("uint16");
7921 bfields[3].name = "noverflow";
7922 bfields[3].btype = uint16_type->get_backend(gogo);
7923 bfields[3].location = bloc;
7925 Type* uint32_type = Type::lookup_integer_type("uint32");
7926 bfields[4].name = "hash0";
7927 bfields[4].btype = uint32_type->get_backend(gogo);
7928 bfields[4].location = bloc;
7930 Btype* bvt = gogo->backend()->void_type();
7931 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7932 bfields[5].name = "buckets";
7933 bfields[5].btype = bpvt;
7934 bfields[5].location = bloc;
7936 bfields[6].name = "oldbuckets";
7937 bfields[6].btype = bpvt;
7938 bfields[6].location = bloc;
7940 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7941 bfields[7].name = "nevacuate";
7942 bfields[7].btype = uintptr_type->get_backend(gogo);
7943 bfields[7].location = bloc;
7945 bfields[8].name = "extra";
7946 bfields[8].btype = bpvt;
7947 bfields[8].location = bloc;
7949 Btype *bt = gogo->backend()->struct_type(bfields);
7950 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7951 backend_map_type = gogo->backend()->pointer_type(bt);
7953 return backend_map_type;
7956 // The type of a map type descriptor.
7958 Type*
7959 Map_type::make_map_type_descriptor_type()
7961 static Type* ret;
7962 if (ret == NULL)
7964 Type* tdt = Type::make_type_descriptor_type();
7965 Type* ptdt = Type::make_type_descriptor_ptr_type();
7966 Type* uint8_type = Type::lookup_integer_type("uint8");
7967 Type* uint16_type = Type::lookup_integer_type("uint16");
7968 Type* bool_type = Type::lookup_bool_type();
7970 Struct_type* sf =
7971 Type::make_builtin_struct_type(12,
7972 "", tdt,
7973 "key", ptdt,
7974 "elem", ptdt,
7975 "bucket", ptdt,
7976 "hmap", ptdt,
7977 "keysize", uint8_type,
7978 "indirectkey", bool_type,
7979 "valuesize", uint8_type,
7980 "indirectvalue", bool_type,
7981 "bucketsize", uint16_type,
7982 "reflexivekey", bool_type,
7983 "needkeyupdate", bool_type);
7985 ret = Type::make_builtin_named_type("MapType", sf);
7988 return ret;
7991 // Build a type descriptor for a map type.
7993 Expression*
7994 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7996 Location bloc = Linemap::predeclared_location();
7998 Type* mtdt = Map_type::make_map_type_descriptor_type();
7999 Type* uint8_type = Type::lookup_integer_type("uint8");
8000 Type* uint16_type = Type::lookup_integer_type("uint16");
8002 int64_t keysize;
8003 if (!this->key_type_->backend_type_size(gogo, &keysize))
8005 go_error_at(this->location_, "error determining map key type size");
8006 return Expression::make_error(this->location_);
8009 int64_t valsize;
8010 if (!this->val_type_->backend_type_size(gogo, &valsize))
8012 go_error_at(this->location_, "error determining map value type size");
8013 return Expression::make_error(this->location_);
8016 int64_t ptrsize;
8017 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8019 go_assert(saw_errors());
8020 return Expression::make_error(this->location_);
8023 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8024 if (bucket_type == NULL)
8026 go_assert(saw_errors());
8027 return Expression::make_error(this->location_);
8030 int64_t bucketsize;
8031 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8033 go_assert(saw_errors());
8034 return Expression::make_error(this->location_);
8037 const Struct_field_list* fields = mtdt->struct_type()->fields();
8039 Expression_list* vals = new Expression_list();
8040 vals->reserve(12);
8042 Struct_field_list::const_iterator p = fields->begin();
8043 go_assert(p->is_field_name("_type"));
8044 vals->push_back(this->type_descriptor_constructor(gogo,
8045 RUNTIME_TYPE_KIND_MAP,
8046 name, NULL, true));
8048 ++p;
8049 go_assert(p->is_field_name("key"));
8050 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8052 ++p;
8053 go_assert(p->is_field_name("elem"));
8054 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8056 ++p;
8057 go_assert(p->is_field_name("bucket"));
8058 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8060 ++p;
8061 go_assert(p->is_field_name("hmap"));
8062 Type* hmap_type = this->hmap_type(bucket_type);
8063 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8065 ++p;
8066 go_assert(p->is_field_name("keysize"));
8067 if (keysize > Map_type::max_key_size)
8068 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8069 else
8070 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8072 ++p;
8073 go_assert(p->is_field_name("indirectkey"));
8074 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8075 bloc));
8077 ++p;
8078 go_assert(p->is_field_name("valuesize"));
8079 if (valsize > Map_type::max_val_size)
8080 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8081 else
8082 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8084 ++p;
8085 go_assert(p->is_field_name("indirectvalue"));
8086 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8087 bloc));
8089 ++p;
8090 go_assert(p->is_field_name("bucketsize"));
8091 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8092 bloc));
8094 ++p;
8095 go_assert(p->is_field_name("reflexivekey"));
8096 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8097 bloc));
8099 ++p;
8100 go_assert(p->is_field_name("needkeyupdate"));
8101 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8102 bloc));
8104 ++p;
8105 go_assert(p == fields->end());
8107 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8110 // Return the bucket type to use for a map type. This must correspond
8111 // to libgo/go/runtime/hashmap.go.
8113 Type*
8114 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8116 if (this->bucket_type_ != NULL)
8117 return this->bucket_type_;
8119 Type* key_type = this->key_type_;
8120 if (keysize > Map_type::max_key_size)
8121 key_type = Type::make_pointer_type(key_type);
8123 Type* val_type = this->val_type_;
8124 if (valsize > Map_type::max_val_size)
8125 val_type = Type::make_pointer_type(val_type);
8127 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8128 NULL, this->location_);
8130 Type* uint8_type = Type::lookup_integer_type("uint8");
8131 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8132 topbits_type->set_is_array_incomparable();
8133 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8134 keys_type->set_is_array_incomparable();
8135 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8136 values_type->set_is_array_incomparable();
8138 // If keys and values have no pointers, the map implementation can
8139 // keep a list of overflow pointers on the side so that buckets can
8140 // be marked as having no pointers. Arrange for the bucket to have
8141 // no pointers by changing the type of the overflow field to uintptr
8142 // in this case. See comment on the hmap.overflow field in
8143 // libgo/go/runtime/hashmap.go.
8144 Type* overflow_type;
8145 if (!key_type->has_pointer() && !val_type->has_pointer())
8146 overflow_type = Type::lookup_integer_type("uintptr");
8147 else
8149 // This should really be a pointer to the bucket type itself,
8150 // but that would require us to construct a Named_type for it to
8151 // give it a way to refer to itself. Since nothing really cares
8152 // (except perhaps for someone using a debugger) just use an
8153 // unsafe pointer.
8154 overflow_type = Type::make_pointer_type(Type::make_void_type());
8157 // Make sure the overflow pointer is the last memory in the struct,
8158 // because the runtime assumes it can use size-ptrSize as the offset
8159 // of the overflow pointer. We double-check that property below
8160 // once the offsets and size are computed.
8162 int64_t topbits_field_size, topbits_field_align;
8163 int64_t keys_field_size, keys_field_align;
8164 int64_t values_field_size, values_field_align;
8165 int64_t overflow_field_size, overflow_field_align;
8166 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8167 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8168 || !keys_type->backend_type_size(gogo, &keys_field_size)
8169 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8170 || !values_type->backend_type_size(gogo, &values_field_size)
8171 || !values_type->backend_type_field_align(gogo, &values_field_align)
8172 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8173 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8175 go_assert(saw_errors());
8176 return NULL;
8179 Struct_type* ret;
8180 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8181 values_field_align);
8182 if (max_align <= overflow_field_align)
8183 ret = make_builtin_struct_type(4,
8184 "topbits", topbits_type,
8185 "keys", keys_type,
8186 "values", values_type,
8187 "overflow", overflow_type);
8188 else
8190 size_t off = topbits_field_size;
8191 off = ((off + keys_field_align - 1)
8192 &~ static_cast<size_t>(keys_field_align - 1));
8193 off += keys_field_size;
8194 off = ((off + values_field_align - 1)
8195 &~ static_cast<size_t>(values_field_align - 1));
8196 off += values_field_size;
8198 int64_t padded_overflow_field_size =
8199 ((overflow_field_size + max_align - 1)
8200 &~ static_cast<size_t>(max_align - 1));
8202 size_t ovoff = off;
8203 ovoff = ((ovoff + max_align - 1)
8204 &~ static_cast<size_t>(max_align - 1));
8205 size_t pad = (ovoff - off
8206 + padded_overflow_field_size - overflow_field_size);
8208 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8209 this->location_);
8210 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8211 pad_type->set_is_array_incomparable();
8213 ret = make_builtin_struct_type(5,
8214 "topbits", topbits_type,
8215 "keys", keys_type,
8216 "values", values_type,
8217 "pad", pad_type,
8218 "overflow", overflow_type);
8221 // Verify that the overflow field is just before the end of the
8222 // bucket type.
8224 Btype* btype = ret->get_backend(gogo);
8225 int64_t offset = gogo->backend()->type_field_offset(btype,
8226 ret->field_count() - 1);
8227 int64_t size;
8228 if (!ret->backend_type_size(gogo, &size))
8230 go_assert(saw_errors());
8231 return NULL;
8234 int64_t ptr_size;
8235 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8237 go_assert(saw_errors());
8238 return NULL;
8241 go_assert(offset + ptr_size == size);
8243 ret->set_is_struct_incomparable();
8245 this->bucket_type_ = ret;
8246 return ret;
8249 // Return the hashmap type for a map type.
8251 Type*
8252 Map_type::hmap_type(Type* bucket_type)
8254 if (this->hmap_type_ != NULL)
8255 return this->hmap_type_;
8257 Type* int_type = Type::lookup_integer_type("int");
8258 Type* uint8_type = Type::lookup_integer_type("uint8");
8259 Type* uint16_type = Type::lookup_integer_type("uint16");
8260 Type* uint32_type = Type::lookup_integer_type("uint32");
8261 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8262 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8264 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8266 Struct_type* ret = make_builtin_struct_type(9,
8267 "count", int_type,
8268 "flags", uint8_type,
8269 "B", uint8_type,
8270 "noverflow", uint16_type,
8271 "hash0", uint32_type,
8272 "buckets", ptr_bucket_type,
8273 "oldbuckets", ptr_bucket_type,
8274 "nevacuate", uintptr_type,
8275 "extra", void_ptr_type);
8276 ret->set_is_struct_incomparable();
8277 this->hmap_type_ = ret;
8278 return ret;
8281 // Return the iterator type for a map type. This is the type of the
8282 // value used when doing a range over a map.
8284 Type*
8285 Map_type::hiter_type(Gogo* gogo)
8287 if (this->hiter_type_ != NULL)
8288 return this->hiter_type_;
8290 int64_t keysize, valsize;
8291 if (!this->key_type_->backend_type_size(gogo, &keysize)
8292 || !this->val_type_->backend_type_size(gogo, &valsize))
8294 go_assert(saw_errors());
8295 return NULL;
8298 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8299 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8300 Type* uint8_type = Type::lookup_integer_type("uint8");
8301 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8302 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8303 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8304 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8305 Type* hmap_type = this->hmap_type(bucket_type);
8306 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8307 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8308 Type* bool_type = Type::lookup_bool_type();
8310 Struct_type* ret = make_builtin_struct_type(15,
8311 "key", key_ptr_type,
8312 "val", val_ptr_type,
8313 "t", uint8_ptr_type,
8314 "h", hmap_ptr_type,
8315 "buckets", bucket_ptr_type,
8316 "bptr", bucket_ptr_type,
8317 "overflow", void_ptr_type,
8318 "oldoverflow", void_ptr_type,
8319 "startBucket", uintptr_type,
8320 "offset", uint8_type,
8321 "wrapped", bool_type,
8322 "B", uint8_type,
8323 "i", uint8_type,
8324 "bucket", uintptr_type,
8325 "checkBucket", uintptr_type);
8326 ret->set_is_struct_incomparable();
8327 this->hiter_type_ = ret;
8328 return ret;
8331 // Reflection string for a map.
8333 void
8334 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8336 ret->append("map[");
8337 this->append_reflection(this->key_type_, gogo, ret);
8338 ret->append("]");
8339 this->append_reflection(this->val_type_, gogo, ret);
8342 // Export a map type.
8344 void
8345 Map_type::do_export(Export* exp) const
8347 exp->write_c_string("map [");
8348 exp->write_type(this->key_type_);
8349 exp->write_c_string("] ");
8350 exp->write_type(this->val_type_);
8353 // Import a map type.
8355 Map_type*
8356 Map_type::do_import(Import* imp)
8358 imp->require_c_string("map [");
8359 Type* key_type = imp->read_type();
8360 imp->require_c_string("] ");
8361 Type* val_type = imp->read_type();
8362 return Type::make_map_type(key_type, val_type, imp->location());
8365 // Make a map type.
8367 Map_type*
8368 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8370 return new Map_type(key_type, val_type, location);
8373 // Class Channel_type.
8375 // Verify.
8377 bool
8378 Channel_type::do_verify()
8380 // We have no location for this error, but this is not something the
8381 // ordinary user will see.
8382 if (!this->element_type_->in_heap())
8383 go_error_at(Linemap::unknown_location(),
8384 "chan of go:notinheap type not allowed");
8385 return true;
8388 // Hash code.
8390 unsigned int
8391 Channel_type::do_hash_for_method(Gogo* gogo) const
8393 unsigned int ret = 0;
8394 if (this->may_send_)
8395 ret += 1;
8396 if (this->may_receive_)
8397 ret += 2;
8398 if (this->element_type_ != NULL)
8399 ret += this->element_type_->hash_for_method(gogo) << 2;
8400 return ret << 3;
8403 // Whether this type is the same as T.
8405 bool
8406 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8407 bool errors_are_identical) const
8409 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8410 cmp_tags, errors_are_identical, NULL))
8411 return false;
8412 return (this->may_send_ == t->may_send_
8413 && this->may_receive_ == t->may_receive_);
8416 // Return the backend representation for a channel type. A channel is a pointer
8417 // to a __go_channel struct. The __go_channel struct is defined in
8418 // libgo/runtime/channel.h.
8420 Btype*
8421 Channel_type::do_get_backend(Gogo* gogo)
8423 static Btype* backend_channel_type;
8424 if (backend_channel_type == NULL)
8426 std::vector<Backend::Btyped_identifier> bfields;
8427 Btype* bt = gogo->backend()->struct_type(bfields);
8428 bt = gogo->backend()->named_type("__go_channel", bt,
8429 Linemap::predeclared_location());
8430 backend_channel_type = gogo->backend()->pointer_type(bt);
8432 return backend_channel_type;
8435 // Build a type descriptor for a channel type.
8437 Type*
8438 Channel_type::make_chan_type_descriptor_type()
8440 static Type* ret;
8441 if (ret == NULL)
8443 Type* tdt = Type::make_type_descriptor_type();
8444 Type* ptdt = Type::make_type_descriptor_ptr_type();
8446 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8448 Struct_type* sf =
8449 Type::make_builtin_struct_type(3,
8450 "", tdt,
8451 "elem", ptdt,
8452 "dir", uintptr_type);
8454 ret = Type::make_builtin_named_type("ChanType", sf);
8457 return ret;
8460 // Build a type descriptor for a map type.
8462 Expression*
8463 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8465 Location bloc = Linemap::predeclared_location();
8467 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8469 const Struct_field_list* fields = ctdt->struct_type()->fields();
8471 Expression_list* vals = new Expression_list();
8472 vals->reserve(3);
8474 Struct_field_list::const_iterator p = fields->begin();
8475 go_assert(p->is_field_name("_type"));
8476 vals->push_back(this->type_descriptor_constructor(gogo,
8477 RUNTIME_TYPE_KIND_CHAN,
8478 name, NULL, true));
8480 ++p;
8481 go_assert(p->is_field_name("elem"));
8482 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8484 ++p;
8485 go_assert(p->is_field_name("dir"));
8486 // These bits must match the ones in libgo/runtime/go-type.h.
8487 int val = 0;
8488 if (this->may_receive_)
8489 val |= 1;
8490 if (this->may_send_)
8491 val |= 2;
8492 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8494 ++p;
8495 go_assert(p == fields->end());
8497 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8500 // Reflection string.
8502 void
8503 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8505 if (!this->may_send_)
8506 ret->append("<-");
8507 ret->append("chan");
8508 if (!this->may_receive_)
8509 ret->append("<-");
8510 ret->push_back(' ');
8511 this->append_reflection(this->element_type_, gogo, ret);
8514 // Export.
8516 void
8517 Channel_type::do_export(Export* exp) const
8519 exp->write_c_string("chan ");
8520 if (this->may_send_ && !this->may_receive_)
8521 exp->write_c_string("-< ");
8522 else if (this->may_receive_ && !this->may_send_)
8523 exp->write_c_string("<- ");
8524 exp->write_type(this->element_type_);
8527 // Import.
8529 Channel_type*
8530 Channel_type::do_import(Import* imp)
8532 imp->require_c_string("chan ");
8534 bool may_send;
8535 bool may_receive;
8536 if (imp->match_c_string("-< "))
8538 imp->advance(3);
8539 may_send = true;
8540 may_receive = false;
8542 else if (imp->match_c_string("<- "))
8544 imp->advance(3);
8545 may_receive = true;
8546 may_send = false;
8548 else
8550 may_send = true;
8551 may_receive = true;
8554 Type* element_type = imp->read_type();
8556 return Type::make_channel_type(may_send, may_receive, element_type);
8559 // Return the type to manage a select statement with ncases case
8560 // statements. A value of this type is allocated on the stack. This
8561 // must match the type hselect in libgo/go/runtime/select.go.
8563 Type*
8564 Channel_type::select_type(int ncases)
8566 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8567 Type* uint16_type = Type::lookup_integer_type("uint16");
8569 static Struct_type* scase_type;
8570 if (scase_type == NULL)
8572 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8573 Type* uint64_type = Type::lookup_integer_type("uint64");
8574 scase_type =
8575 Type::make_builtin_struct_type(7,
8576 "elem", unsafe_pointer_type,
8577 "chan", unsafe_pointer_type,
8578 "pc", uintptr_type,
8579 "kind", uint16_type,
8580 "index", uint16_type,
8581 "receivedp", unsafe_pointer_type,
8582 "releasetime", uint64_type);
8583 scase_type->set_is_struct_incomparable();
8586 Expression* ncases_expr =
8587 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8588 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8589 scases->set_is_array_incomparable();
8590 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8591 order->set_is_array_incomparable();
8593 Struct_type* ret =
8594 Type::make_builtin_struct_type(7,
8595 "tcase", uint16_type,
8596 "ncase", uint16_type,
8597 "pollorder", unsafe_pointer_type,
8598 "lockorder", unsafe_pointer_type,
8599 "scase", scases,
8600 "lockorderarr", order,
8601 "pollorderarr", order);
8602 ret->set_is_struct_incomparable();
8603 return ret;
8606 // Make a new channel type.
8608 Channel_type*
8609 Type::make_channel_type(bool send, bool receive, Type* element_type)
8611 return new Channel_type(send, receive, element_type);
8614 // Class Interface_type.
8616 // Return the list of methods.
8618 const Typed_identifier_list*
8619 Interface_type::methods() const
8621 go_assert(this->methods_are_finalized_ || saw_errors());
8622 return this->all_methods_;
8625 // Return the number of methods.
8627 size_t
8628 Interface_type::method_count() const
8630 go_assert(this->methods_are_finalized_ || saw_errors());
8631 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8634 // Traversal.
8637 Interface_type::do_traverse(Traverse* traverse)
8639 Typed_identifier_list* methods = (this->methods_are_finalized_
8640 ? this->all_methods_
8641 : this->parse_methods_);
8642 if (methods == NULL)
8643 return TRAVERSE_CONTINUE;
8644 return methods->traverse(traverse);
8647 // Finalize the methods. This handles interface inheritance.
8649 void
8650 Interface_type::finalize_methods()
8652 if (this->methods_are_finalized_)
8653 return;
8654 this->methods_are_finalized_ = true;
8655 if (this->parse_methods_ == NULL)
8656 return;
8658 this->all_methods_ = new Typed_identifier_list();
8659 this->all_methods_->reserve(this->parse_methods_->size());
8660 Typed_identifier_list inherit;
8661 for (Typed_identifier_list::const_iterator pm =
8662 this->parse_methods_->begin();
8663 pm != this->parse_methods_->end();
8664 ++pm)
8666 const Typed_identifier* p = &*pm;
8667 if (p->name().empty())
8668 inherit.push_back(*p);
8669 else if (this->find_method(p->name()) == NULL)
8670 this->all_methods_->push_back(*p);
8671 else
8672 go_error_at(p->location(), "duplicate method %qs",
8673 Gogo::message_name(p->name()).c_str());
8676 std::vector<Named_type*> seen;
8677 seen.reserve(inherit.size());
8678 bool issued_recursive_error = false;
8679 while (!inherit.empty())
8681 Type* t = inherit.back().type();
8682 Location tl = inherit.back().location();
8683 inherit.pop_back();
8685 Interface_type* it = t->interface_type();
8686 if (it == NULL)
8688 if (!t->is_error())
8689 go_error_at(tl, "interface contains embedded non-interface");
8690 continue;
8692 if (it == this)
8694 if (!issued_recursive_error)
8696 go_error_at(tl, "invalid recursive interface");
8697 issued_recursive_error = true;
8699 continue;
8702 Named_type* nt = t->named_type();
8703 if (nt != NULL && it->parse_methods_ != NULL)
8705 std::vector<Named_type*>::const_iterator q;
8706 for (q = seen.begin(); q != seen.end(); ++q)
8708 if (*q == nt)
8710 go_error_at(tl, "inherited interface loop");
8711 break;
8714 if (q != seen.end())
8715 continue;
8716 seen.push_back(nt);
8719 const Typed_identifier_list* imethods = it->parse_methods_;
8720 if (imethods == NULL)
8721 continue;
8722 for (Typed_identifier_list::const_iterator q = imethods->begin();
8723 q != imethods->end();
8724 ++q)
8726 if (q->name().empty())
8727 inherit.push_back(*q);
8728 else if (this->find_method(q->name()) == NULL)
8729 this->all_methods_->push_back(Typed_identifier(q->name(),
8730 q->type(), tl));
8731 else
8732 go_error_at(tl, "inherited method %qs is ambiguous",
8733 Gogo::message_name(q->name()).c_str());
8737 if (!this->all_methods_->empty())
8738 this->all_methods_->sort_by_name();
8739 else
8741 delete this->all_methods_;
8742 this->all_methods_ = NULL;
8746 // Return the method NAME, or NULL.
8748 const Typed_identifier*
8749 Interface_type::find_method(const std::string& name) const
8751 go_assert(this->methods_are_finalized_);
8752 if (this->all_methods_ == NULL)
8753 return NULL;
8754 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8755 p != this->all_methods_->end();
8756 ++p)
8757 if (p->name() == name)
8758 return &*p;
8759 return NULL;
8762 // Return the method index.
8764 size_t
8765 Interface_type::method_index(const std::string& name) const
8767 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8768 size_t ret = 0;
8769 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8770 p != this->all_methods_->end();
8771 ++p, ++ret)
8772 if (p->name() == name)
8773 return ret;
8774 go_unreachable();
8777 // Return whether NAME is an unexported method, for better error
8778 // reporting.
8780 bool
8781 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8783 go_assert(this->methods_are_finalized_);
8784 if (this->all_methods_ == NULL)
8785 return false;
8786 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8787 p != this->all_methods_->end();
8788 ++p)
8790 const std::string& method_name(p->name());
8791 if (Gogo::is_hidden_name(method_name)
8792 && name == Gogo::unpack_hidden_name(method_name)
8793 && gogo->pack_hidden_name(name, false) != method_name)
8794 return true;
8796 return false;
8799 // Whether this type is identical with T.
8801 bool
8802 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
8803 bool errors_are_identical) const
8805 // If methods have not been finalized, then we are asking whether
8806 // func redeclarations are the same. This is an error, so for
8807 // simplicity we say they are never the same.
8808 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8809 return false;
8811 // We require the same methods with the same types. The methods
8812 // have already been sorted.
8813 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8814 return this->all_methods_ == t->all_methods_;
8816 if (this->assume_identical(this, t) || t->assume_identical(t, this))
8817 return true;
8819 Assume_identical* hold_ai = this->assume_identical_;
8820 Assume_identical ai;
8821 ai.t1 = this;
8822 ai.t2 = t;
8823 ai.next = hold_ai;
8824 this->assume_identical_ = &ai;
8826 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8827 Typed_identifier_list::const_iterator p2;
8828 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8830 if (p1 == this->all_methods_->end())
8831 break;
8832 if (p1->name() != p2->name()
8833 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
8834 errors_are_identical, NULL))
8835 break;
8838 this->assume_identical_ = hold_ai;
8840 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8843 // Return true if T1 and T2 are assumed to be identical during a type
8844 // comparison.
8846 bool
8847 Interface_type::assume_identical(const Interface_type* t1,
8848 const Interface_type* t2) const
8850 for (Assume_identical* p = this->assume_identical_;
8851 p != NULL;
8852 p = p->next)
8853 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8854 return true;
8855 return false;
8858 // Whether we can assign the interface type T to this type. The types
8859 // are known to not be identical. An interface assignment is only
8860 // permitted if T is known to implement all methods in THIS.
8861 // Otherwise a type guard is required.
8863 bool
8864 Interface_type::is_compatible_for_assign(const Interface_type* t,
8865 std::string* reason) const
8867 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8868 if (this->all_methods_ == NULL)
8869 return true;
8870 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8871 p != this->all_methods_->end();
8872 ++p)
8874 const Typed_identifier* m = t->find_method(p->name());
8875 if (m == NULL)
8877 if (reason != NULL)
8879 char buf[200];
8880 snprintf(buf, sizeof buf,
8881 _("need explicit conversion; missing method %s%s%s"),
8882 go_open_quote(), Gogo::message_name(p->name()).c_str(),
8883 go_close_quote());
8884 reason->assign(buf);
8886 return false;
8889 std::string subreason;
8890 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8892 if (reason != NULL)
8894 std::string n = Gogo::message_name(p->name());
8895 size_t len = 100 + n.length() + subreason.length();
8896 char* buf = new char[len];
8897 if (subreason.empty())
8898 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8899 go_open_quote(), n.c_str(), go_close_quote());
8900 else
8901 snprintf(buf, len,
8902 _("incompatible type for method %s%s%s (%s)"),
8903 go_open_quote(), n.c_str(), go_close_quote(),
8904 subreason.c_str());
8905 reason->assign(buf);
8906 delete[] buf;
8908 return false;
8912 return true;
8915 // Hash code.
8917 unsigned int
8918 Interface_type::do_hash_for_method(Gogo*) const
8920 go_assert(this->methods_are_finalized_);
8921 unsigned int ret = 0;
8922 if (this->all_methods_ != NULL)
8924 for (Typed_identifier_list::const_iterator p =
8925 this->all_methods_->begin();
8926 p != this->all_methods_->end();
8927 ++p)
8929 ret = Type::hash_string(p->name(), ret);
8930 // We don't use the method type in the hash, to avoid
8931 // infinite recursion if an interface method uses a type
8932 // which is an interface which inherits from the interface
8933 // itself.
8934 // type T interface { F() interface {T}}
8935 ret <<= 1;
8938 return ret;
8941 // Return true if T implements the interface. If it does not, and
8942 // REASON is not NULL, set *REASON to a useful error message.
8944 bool
8945 Interface_type::implements_interface(const Type* t, std::string* reason) const
8947 go_assert(this->methods_are_finalized_);
8948 if (this->all_methods_ == NULL)
8949 return true;
8951 bool is_pointer = false;
8952 const Named_type* nt = t->named_type();
8953 const Struct_type* st = t->struct_type();
8954 // If we start with a named type, we don't dereference it to find
8955 // methods.
8956 if (nt == NULL)
8958 const Type* pt = t->points_to();
8959 if (pt != NULL)
8961 // If T is a pointer to a named type, then we need to look at
8962 // the type to which it points.
8963 is_pointer = true;
8964 nt = pt->named_type();
8965 st = pt->struct_type();
8969 // If we have a named type, get the methods from it rather than from
8970 // any struct type.
8971 if (nt != NULL)
8972 st = NULL;
8974 // Only named and struct types have methods.
8975 if (nt == NULL && st == NULL)
8977 if (reason != NULL)
8979 if (t->points_to() != NULL
8980 && t->points_to()->interface_type() != NULL)
8981 reason->assign(_("pointer to interface type has no methods"));
8982 else
8983 reason->assign(_("type has no methods"));
8985 return false;
8988 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8990 if (reason != NULL)
8992 if (t->points_to() != NULL
8993 && t->points_to()->interface_type() != NULL)
8994 reason->assign(_("pointer to interface type has no methods"));
8995 else
8996 reason->assign(_("type has no methods"));
8998 return false;
9001 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9002 p != this->all_methods_->end();
9003 ++p)
9005 bool is_ambiguous = false;
9006 Method* m = (nt != NULL
9007 ? nt->method_function(p->name(), &is_ambiguous)
9008 : st->method_function(p->name(), &is_ambiguous));
9009 if (m == NULL)
9011 if (reason != NULL)
9013 std::string n = Gogo::message_name(p->name());
9014 size_t len = n.length() + 100;
9015 char* buf = new char[len];
9016 if (is_ambiguous)
9017 snprintf(buf, len, _("ambiguous method %s%s%s"),
9018 go_open_quote(), n.c_str(), go_close_quote());
9019 else
9020 snprintf(buf, len, _("missing method %s%s%s"),
9021 go_open_quote(), n.c_str(), go_close_quote());
9022 reason->assign(buf);
9023 delete[] buf;
9025 return false;
9028 Function_type *p_fn_type = p->type()->function_type();
9029 Function_type* m_fn_type = m->type()->function_type();
9030 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9031 std::string subreason;
9032 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9033 &subreason))
9035 if (reason != NULL)
9037 std::string n = Gogo::message_name(p->name());
9038 size_t len = 100 + n.length() + subreason.length();
9039 char* buf = new char[len];
9040 if (subreason.empty())
9041 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9042 go_open_quote(), n.c_str(), go_close_quote());
9043 else
9044 snprintf(buf, len,
9045 _("incompatible type for method %s%s%s (%s)"),
9046 go_open_quote(), n.c_str(), go_close_quote(),
9047 subreason.c_str());
9048 reason->assign(buf);
9049 delete[] buf;
9051 return false;
9054 if (!is_pointer && !m->is_value_method())
9056 if (reason != NULL)
9058 std::string n = Gogo::message_name(p->name());
9059 size_t len = 100 + n.length();
9060 char* buf = new char[len];
9061 snprintf(buf, len,
9062 _("method %s%s%s requires a pointer receiver"),
9063 go_open_quote(), n.c_str(), go_close_quote());
9064 reason->assign(buf);
9065 delete[] buf;
9067 return false;
9070 // If the magic //go:nointerface comment was used, the method
9071 // may not be used to implement interfaces.
9072 if (m->nointerface())
9074 if (reason != NULL)
9076 std::string n = Gogo::message_name(p->name());
9077 size_t len = 100 + n.length();
9078 char* buf = new char[len];
9079 snprintf(buf, len,
9080 _("method %s%s%s is marked go:nointerface"),
9081 go_open_quote(), n.c_str(), go_close_quote());
9082 reason->assign(buf);
9083 delete[] buf;
9085 return false;
9089 return true;
9092 // Return the backend representation of the empty interface type. We
9093 // use the same struct for all empty interfaces.
9095 Btype*
9096 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9098 static Btype* empty_interface_type;
9099 if (empty_interface_type == NULL)
9101 std::vector<Backend::Btyped_identifier> bfields(2);
9103 Location bloc = Linemap::predeclared_location();
9105 Type* pdt = Type::make_type_descriptor_ptr_type();
9106 bfields[0].name = "__type_descriptor";
9107 bfields[0].btype = pdt->get_backend(gogo);
9108 bfields[0].location = bloc;
9110 Type* vt = Type::make_pointer_type(Type::make_void_type());
9111 bfields[1].name = "__object";
9112 bfields[1].btype = vt->get_backend(gogo);
9113 bfields[1].location = bloc;
9115 empty_interface_type = gogo->backend()->struct_type(bfields);
9117 return empty_interface_type;
9120 Interface_type::Bmethods_map Interface_type::bmethods_map;
9122 // Return a pointer to the backend representation of the method table.
9124 Btype*
9125 Interface_type::get_backend_methods(Gogo* gogo)
9127 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9128 return this->bmethods_;
9130 std::pair<Interface_type*, Bmethods_map_entry> val;
9131 val.first = this;
9132 val.second.btype = NULL;
9133 val.second.is_placeholder = false;
9134 std::pair<Bmethods_map::iterator, bool> ins =
9135 Interface_type::bmethods_map.insert(val);
9136 if (!ins.second
9137 && ins.first->second.btype != NULL
9138 && !ins.first->second.is_placeholder)
9140 this->bmethods_ = ins.first->second.btype;
9141 this->bmethods_is_placeholder_ = false;
9142 return this->bmethods_;
9145 Location loc = this->location();
9147 std::vector<Backend::Btyped_identifier>
9148 mfields(this->all_methods_->size() + 1);
9150 Type* pdt = Type::make_type_descriptor_ptr_type();
9151 mfields[0].name = "__type_descriptor";
9152 mfields[0].btype = pdt->get_backend(gogo);
9153 mfields[0].location = loc;
9155 std::string last_name = "";
9156 size_t i = 1;
9157 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9158 p != this->all_methods_->end();
9159 ++p, ++i)
9161 // The type of the method in Go only includes the parameters.
9162 // The actual method also has a receiver, which is always a
9163 // pointer. We need to add that pointer type here in order to
9164 // generate the correct type for the backend.
9165 Function_type* ft = p->type()->function_type();
9166 go_assert(ft->receiver() == NULL);
9168 const Typed_identifier_list* params = ft->parameters();
9169 Typed_identifier_list* mparams = new Typed_identifier_list();
9170 if (params != NULL)
9171 mparams->reserve(params->size() + 1);
9172 Type* vt = Type::make_pointer_type(Type::make_void_type());
9173 mparams->push_back(Typed_identifier("", vt, ft->location()));
9174 if (params != NULL)
9176 for (Typed_identifier_list::const_iterator pp = params->begin();
9177 pp != params->end();
9178 ++pp)
9179 mparams->push_back(*pp);
9182 Typed_identifier_list* mresults = (ft->results() == NULL
9183 ? NULL
9184 : ft->results()->copy());
9185 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9186 ft->location());
9188 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9189 mfields[i].btype = mft->get_backend_fntype(gogo);
9190 mfields[i].location = loc;
9192 // Sanity check: the names should be sorted.
9193 go_assert(Gogo::unpack_hidden_name(p->name())
9194 > Gogo::unpack_hidden_name(last_name));
9195 last_name = p->name();
9198 Btype* st = gogo->backend()->struct_type(mfields);
9199 Btype* ret = gogo->backend()->pointer_type(st);
9201 if (ins.first->second.btype != NULL
9202 && ins.first->second.is_placeholder)
9203 gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9204 ret);
9205 this->bmethods_ = ret;
9206 ins.first->second.btype = ret;
9207 this->bmethods_is_placeholder_ = false;
9208 ins.first->second.is_placeholder = false;
9209 return ret;
9212 // Return a placeholder for the pointer to the backend methods table.
9214 Btype*
9215 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9217 if (this->bmethods_ == NULL)
9219 std::pair<Interface_type*, Bmethods_map_entry> val;
9220 val.first = this;
9221 val.second.btype = NULL;
9222 val.second.is_placeholder = false;
9223 std::pair<Bmethods_map::iterator, bool> ins =
9224 Interface_type::bmethods_map.insert(val);
9225 if (!ins.second && ins.first->second.btype != NULL)
9227 this->bmethods_ = ins.first->second.btype;
9228 this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9229 return this->bmethods_;
9232 Location loc = this->location();
9233 Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9234 this->bmethods_ = bt;
9235 ins.first->second.btype = bt;
9236 this->bmethods_is_placeholder_ = true;
9237 ins.first->second.is_placeholder = true;
9239 return this->bmethods_;
9242 // Return the fields of a non-empty interface type. This is not
9243 // declared in types.h so that types.h doesn't have to #include
9244 // backend.h.
9246 static void
9247 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9248 bool use_placeholder,
9249 std::vector<Backend::Btyped_identifier>* bfields)
9251 Location loc = type->location();
9253 bfields->resize(2);
9255 (*bfields)[0].name = "__methods";
9256 (*bfields)[0].btype = (use_placeholder
9257 ? type->get_backend_methods_placeholder(gogo)
9258 : type->get_backend_methods(gogo));
9259 (*bfields)[0].location = loc;
9261 Type* vt = Type::make_pointer_type(Type::make_void_type());
9262 (*bfields)[1].name = "__object";
9263 (*bfields)[1].btype = vt->get_backend(gogo);
9264 (*bfields)[1].location = Linemap::predeclared_location();
9267 // Return the backend representation for an interface type. An interface is a
9268 // pointer to a struct. The struct has three fields. The first field is a
9269 // pointer to the type descriptor for the dynamic type of the object.
9270 // The second field is a pointer to a table of methods for the
9271 // interface to be used with the object. The third field is the value
9272 // of the object itself.
9274 Btype*
9275 Interface_type::do_get_backend(Gogo* gogo)
9277 if (this->is_empty())
9278 return Interface_type::get_backend_empty_interface_type(gogo);
9279 else
9281 if (this->interface_btype_ != NULL)
9282 return this->interface_btype_;
9283 this->interface_btype_ =
9284 gogo->backend()->placeholder_struct_type("", this->location_);
9285 std::vector<Backend::Btyped_identifier> bfields;
9286 get_backend_interface_fields(gogo, this, false, &bfields);
9287 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9288 bfields))
9289 this->interface_btype_ = gogo->backend()->error_type();
9290 return this->interface_btype_;
9294 // Finish the backend representation of the methods.
9296 void
9297 Interface_type::finish_backend_methods(Gogo* gogo)
9299 if (!this->is_empty())
9301 const Typed_identifier_list* methods = this->methods();
9302 if (methods != NULL)
9304 for (Typed_identifier_list::const_iterator p = methods->begin();
9305 p != methods->end();
9306 ++p)
9307 p->type()->get_backend(gogo);
9310 // Getting the backend methods now will set the placeholder
9311 // pointer.
9312 this->get_backend_methods(gogo);
9316 // The type of an interface type descriptor.
9318 Type*
9319 Interface_type::make_interface_type_descriptor_type()
9321 static Type* ret;
9322 if (ret == NULL)
9324 Type* tdt = Type::make_type_descriptor_type();
9325 Type* ptdt = Type::make_type_descriptor_ptr_type();
9327 Type* string_type = Type::lookup_string_type();
9328 Type* pointer_string_type = Type::make_pointer_type(string_type);
9330 Struct_type* sm =
9331 Type::make_builtin_struct_type(3,
9332 "name", pointer_string_type,
9333 "pkgPath", pointer_string_type,
9334 "typ", ptdt);
9336 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9338 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9340 Struct_type* s = Type::make_builtin_struct_type(2,
9341 "", tdt,
9342 "methods", slice_nsm);
9344 ret = Type::make_builtin_named_type("InterfaceType", s);
9347 return ret;
9350 // Build a type descriptor for an interface type.
9352 Expression*
9353 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9355 Location bloc = Linemap::predeclared_location();
9357 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9359 const Struct_field_list* ifields = itdt->struct_type()->fields();
9361 Expression_list* ivals = new Expression_list();
9362 ivals->reserve(2);
9364 Struct_field_list::const_iterator pif = ifields->begin();
9365 go_assert(pif->is_field_name("_type"));
9366 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9367 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9368 true));
9370 ++pif;
9371 go_assert(pif->is_field_name("methods"));
9373 Expression_list* methods = new Expression_list();
9374 if (this->all_methods_ != NULL)
9376 Type* elemtype = pif->type()->array_type()->element_type();
9378 methods->reserve(this->all_methods_->size());
9379 for (Typed_identifier_list::const_iterator pm =
9380 this->all_methods_->begin();
9381 pm != this->all_methods_->end();
9382 ++pm)
9384 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9386 Expression_list* mvals = new Expression_list();
9387 mvals->reserve(3);
9389 Struct_field_list::const_iterator pmf = mfields->begin();
9390 go_assert(pmf->is_field_name("name"));
9391 std::string s = Gogo::unpack_hidden_name(pm->name());
9392 Expression* e = Expression::make_string(s, bloc);
9393 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9395 ++pmf;
9396 go_assert(pmf->is_field_name("pkgPath"));
9397 if (!Gogo::is_hidden_name(pm->name()))
9398 mvals->push_back(Expression::make_nil(bloc));
9399 else
9401 s = Gogo::hidden_name_pkgpath(pm->name());
9402 e = Expression::make_string(s, bloc);
9403 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9406 ++pmf;
9407 go_assert(pmf->is_field_name("typ"));
9408 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9410 ++pmf;
9411 go_assert(pmf == mfields->end());
9413 e = Expression::make_struct_composite_literal(elemtype, mvals,
9414 bloc);
9415 methods->push_back(e);
9419 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9420 methods, bloc));
9422 ++pif;
9423 go_assert(pif == ifields->end());
9425 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9428 // Reflection string.
9430 void
9431 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9433 ret->append("interface {");
9434 const Typed_identifier_list* methods = this->parse_methods_;
9435 if (methods != NULL)
9437 ret->push_back(' ');
9438 for (Typed_identifier_list::const_iterator p = methods->begin();
9439 p != methods->end();
9440 ++p)
9442 if (p != methods->begin())
9443 ret->append("; ");
9444 if (p->name().empty())
9445 this->append_reflection(p->type(), gogo, ret);
9446 else
9448 if (!Gogo::is_hidden_name(p->name()))
9449 ret->append(p->name());
9450 else if (gogo->pkgpath_from_option())
9451 ret->append(p->name().substr(1));
9452 else
9454 // If no -fgo-pkgpath option, backward compatibility
9455 // for how this used to work before -fgo-pkgpath was
9456 // introduced.
9457 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9458 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9459 ret->push_back('.');
9460 ret->append(Gogo::unpack_hidden_name(p->name()));
9462 std::string sub = p->type()->reflection(gogo);
9463 go_assert(sub.compare(0, 4, "func") == 0);
9464 sub = sub.substr(4);
9465 ret->append(sub);
9468 ret->push_back(' ');
9470 ret->append("}");
9473 // Export.
9475 void
9476 Interface_type::do_export(Export* exp) const
9478 exp->write_c_string("interface { ");
9480 const Typed_identifier_list* methods = this->parse_methods_;
9481 if (methods != NULL)
9483 for (Typed_identifier_list::const_iterator pm = methods->begin();
9484 pm != methods->end();
9485 ++pm)
9487 if (pm->name().empty())
9489 exp->write_c_string("? ");
9490 exp->write_type(pm->type());
9492 else
9494 exp->write_string(pm->name());
9495 exp->write_c_string(" (");
9497 const Function_type* fntype = pm->type()->function_type();
9499 bool first = true;
9500 const Typed_identifier_list* parameters = fntype->parameters();
9501 if (parameters != NULL)
9503 bool is_varargs = fntype->is_varargs();
9504 for (Typed_identifier_list::const_iterator pp =
9505 parameters->begin();
9506 pp != parameters->end();
9507 ++pp)
9509 if (first)
9510 first = false;
9511 else
9512 exp->write_c_string(", ");
9513 exp->write_name(pp->name());
9514 exp->write_c_string(" ");
9515 if (!is_varargs || pp + 1 != parameters->end())
9516 exp->write_type(pp->type());
9517 else
9519 exp->write_c_string("...");
9520 Type *pptype = pp->type();
9521 exp->write_type(pptype->array_type()->element_type());
9526 exp->write_c_string(")");
9528 const Typed_identifier_list* results = fntype->results();
9529 if (results != NULL)
9531 exp->write_c_string(" ");
9532 if (results->size() == 1 && results->begin()->name().empty())
9533 exp->write_type(results->begin()->type());
9534 else
9536 first = true;
9537 exp->write_c_string("(");
9538 for (Typed_identifier_list::const_iterator p =
9539 results->begin();
9540 p != results->end();
9541 ++p)
9543 if (first)
9544 first = false;
9545 else
9546 exp->write_c_string(", ");
9547 exp->write_name(p->name());
9548 exp->write_c_string(" ");
9549 exp->write_type(p->type());
9551 exp->write_c_string(")");
9556 exp->write_c_string("; ");
9560 exp->write_c_string("}");
9563 // Import an interface type.
9565 Interface_type*
9566 Interface_type::do_import(Import* imp)
9568 imp->require_c_string("interface { ");
9570 Typed_identifier_list* methods = new Typed_identifier_list;
9571 while (imp->peek_char() != '}')
9573 std::string name = imp->read_identifier();
9575 if (name == "?")
9577 imp->require_c_string(" ");
9578 Type* t = imp->read_type();
9579 methods->push_back(Typed_identifier("", t, imp->location()));
9580 imp->require_c_string("; ");
9581 continue;
9584 imp->require_c_string(" (");
9586 Typed_identifier_list* parameters;
9587 bool is_varargs = false;
9588 if (imp->peek_char() == ')')
9589 parameters = NULL;
9590 else
9592 parameters = new Typed_identifier_list;
9593 while (true)
9595 std::string name = imp->read_name();
9596 imp->require_c_string(" ");
9598 if (imp->match_c_string("..."))
9600 imp->advance(3);
9601 is_varargs = true;
9604 Type* ptype = imp->read_type();
9605 if (is_varargs)
9606 ptype = Type::make_array_type(ptype, NULL);
9607 parameters->push_back(Typed_identifier(name, ptype,
9608 imp->location()));
9609 if (imp->peek_char() != ',')
9610 break;
9611 go_assert(!is_varargs);
9612 imp->require_c_string(", ");
9615 imp->require_c_string(")");
9617 Typed_identifier_list* results;
9618 if (imp->peek_char() != ' ')
9619 results = NULL;
9620 else
9622 results = new Typed_identifier_list;
9623 imp->advance(1);
9624 if (imp->peek_char() != '(')
9626 Type* rtype = imp->read_type();
9627 results->push_back(Typed_identifier("", rtype, imp->location()));
9629 else
9631 imp->advance(1);
9632 while (true)
9634 std::string name = imp->read_name();
9635 imp->require_c_string(" ");
9636 Type* rtype = imp->read_type();
9637 results->push_back(Typed_identifier(name, rtype,
9638 imp->location()));
9639 if (imp->peek_char() != ',')
9640 break;
9641 imp->require_c_string(", ");
9643 imp->require_c_string(")");
9647 Function_type* fntype = Type::make_function_type(NULL, parameters,
9648 results,
9649 imp->location());
9650 if (is_varargs)
9651 fntype->set_is_varargs();
9652 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9654 imp->require_c_string("; ");
9657 imp->require_c_string("}");
9659 if (methods->empty())
9661 delete methods;
9662 methods = NULL;
9665 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9666 ret->package_ = imp->package();
9667 return ret;
9670 // Make an interface type.
9672 Interface_type*
9673 Type::make_interface_type(Typed_identifier_list* methods,
9674 Location location)
9676 return new Interface_type(methods, location);
9679 // Make an empty interface type.
9681 Interface_type*
9682 Type::make_empty_interface_type(Location location)
9684 Interface_type* ret = new Interface_type(NULL, location);
9685 ret->finalize_methods();
9686 return ret;
9689 // Class Method.
9691 // Bind a method to an object.
9693 Expression*
9694 Method::bind_method(Expression* expr, Location location) const
9696 if (this->stub_ == NULL)
9698 // When there is no stub object, the binding is determined by
9699 // the child class.
9700 return this->do_bind_method(expr, location);
9702 return Expression::make_bound_method(expr, this, this->stub_, location);
9705 // Return the named object associated with a method. This may only be
9706 // called after methods are finalized.
9708 Named_object*
9709 Method::named_object() const
9711 if (this->stub_ != NULL)
9712 return this->stub_;
9713 return this->do_named_object();
9716 // Class Named_method.
9718 // The type of the method.
9720 Function_type*
9721 Named_method::do_type() const
9723 if (this->named_object_->is_function())
9724 return this->named_object_->func_value()->type();
9725 else if (this->named_object_->is_function_declaration())
9726 return this->named_object_->func_declaration_value()->type();
9727 else
9728 go_unreachable();
9731 // Return the location of the method receiver.
9733 Location
9734 Named_method::do_receiver_location() const
9736 return this->do_type()->receiver()->location();
9739 // Bind a method to an object.
9741 Expression*
9742 Named_method::do_bind_method(Expression* expr, Location location) const
9744 Named_object* no = this->named_object_;
9745 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9746 no, location);
9747 // If this is not a local method, and it does not use a stub, then
9748 // the real method expects a different type. We need to cast the
9749 // first argument.
9750 if (this->depth() > 0 && !this->needs_stub_method())
9752 Function_type* ftype = this->do_type();
9753 go_assert(ftype->is_method());
9754 Type* frtype = ftype->receiver()->type();
9755 bme->set_first_argument_type(frtype);
9757 return bme;
9760 // Return whether this method should not participate in interfaces.
9762 bool
9763 Named_method::do_nointerface() const
9765 Named_object* no = this->named_object_;
9766 if (no->is_function())
9767 return no->func_value()->nointerface();
9768 else if (no->is_function_declaration())
9769 return no->func_declaration_value()->nointerface();
9770 else
9771 go_unreachable();
9774 // Class Interface_method.
9776 // Bind a method to an object.
9778 Expression*
9779 Interface_method::do_bind_method(Expression* expr,
9780 Location location) const
9782 return Expression::make_interface_field_reference(expr, this->name_,
9783 location);
9786 // Class Methods.
9788 // Insert a new method. Return true if it was inserted, false
9789 // otherwise.
9791 bool
9792 Methods::insert(const std::string& name, Method* m)
9794 std::pair<Method_map::iterator, bool> ins =
9795 this->methods_.insert(std::make_pair(name, m));
9796 if (ins.second)
9797 return true;
9798 else
9800 Method* old_method = ins.first->second;
9801 if (m->depth() < old_method->depth())
9803 delete old_method;
9804 ins.first->second = m;
9805 return true;
9807 else
9809 if (m->depth() == old_method->depth())
9810 old_method->set_is_ambiguous();
9811 return false;
9816 // Return the number of unambiguous methods.
9818 size_t
9819 Methods::count() const
9821 size_t ret = 0;
9822 for (Method_map::const_iterator p = this->methods_.begin();
9823 p != this->methods_.end();
9824 ++p)
9825 if (!p->second->is_ambiguous())
9826 ++ret;
9827 return ret;
9830 // Class Named_type.
9832 // Return the name of the type.
9834 const std::string&
9835 Named_type::name() const
9837 return this->named_object_->name();
9840 // Return the name of the type to use in an error message.
9842 std::string
9843 Named_type::message_name() const
9845 return this->named_object_->message_name();
9848 // Return the base type for this type. We have to be careful about
9849 // circular type definitions, which are invalid but may be seen here.
9851 Type*
9852 Named_type::named_base()
9854 if (this->seen_)
9855 return this;
9856 this->seen_ = true;
9857 Type* ret = this->type_->base();
9858 this->seen_ = false;
9859 return ret;
9862 const Type*
9863 Named_type::named_base() const
9865 if (this->seen_)
9866 return this;
9867 this->seen_ = true;
9868 const Type* ret = this->type_->base();
9869 this->seen_ = false;
9870 return ret;
9873 // Return whether this is an error type. We have to be careful about
9874 // circular type definitions, which are invalid but may be seen here.
9876 bool
9877 Named_type::is_named_error_type() const
9879 if (this->seen_)
9880 return false;
9881 this->seen_ = true;
9882 bool ret = this->type_->is_error_type();
9883 this->seen_ = false;
9884 return ret;
9887 // Whether this type is comparable. We have to be careful about
9888 // circular type definitions.
9890 bool
9891 Named_type::named_type_is_comparable(std::string* reason) const
9893 if (this->seen_)
9894 return false;
9895 this->seen_ = true;
9896 bool ret = Type::are_compatible_for_comparison(true, this->type_,
9897 this->type_, reason);
9898 this->seen_ = false;
9899 return ret;
9902 // Add a method to this type.
9904 Named_object*
9905 Named_type::add_method(const std::string& name, Function* function)
9907 go_assert(!this->is_alias_);
9908 if (this->local_methods_ == NULL)
9909 this->local_methods_ = new Bindings(NULL);
9910 return this->local_methods_->add_function(name, NULL, function);
9913 // Add a method declaration to this type.
9915 Named_object*
9916 Named_type::add_method_declaration(const std::string& name, Package* package,
9917 Function_type* type,
9918 Location location)
9920 go_assert(!this->is_alias_);
9921 if (this->local_methods_ == NULL)
9922 this->local_methods_ = new Bindings(NULL);
9923 return this->local_methods_->add_function_declaration(name, package, type,
9924 location);
9927 // Add an existing method to this type.
9929 void
9930 Named_type::add_existing_method(Named_object* no)
9932 go_assert(!this->is_alias_);
9933 if (this->local_methods_ == NULL)
9934 this->local_methods_ = new Bindings(NULL);
9935 this->local_methods_->add_named_object(no);
9938 // Look for a local method NAME, and returns its named object, or NULL
9939 // if not there.
9941 Named_object*
9942 Named_type::find_local_method(const std::string& name) const
9944 if (this->is_error_)
9945 return NULL;
9946 if (this->is_alias_)
9948 Named_type* nt = this->type_->named_type();
9949 if (nt != NULL)
9951 if (this->seen_alias_)
9952 return NULL;
9953 this->seen_alias_ = true;
9954 Named_object* ret = nt->find_local_method(name);
9955 this->seen_alias_ = false;
9956 return ret;
9958 return NULL;
9960 if (this->local_methods_ == NULL)
9961 return NULL;
9962 return this->local_methods_->lookup(name);
9965 // Return the list of local methods.
9967 const Bindings*
9968 Named_type::local_methods() const
9970 if (this->is_error_)
9971 return NULL;
9972 if (this->is_alias_)
9974 Named_type* nt = this->type_->named_type();
9975 if (nt != NULL)
9977 if (this->seen_alias_)
9978 return NULL;
9979 this->seen_alias_ = true;
9980 const Bindings* ret = nt->local_methods();
9981 this->seen_alias_ = false;
9982 return ret;
9984 return NULL;
9986 return this->local_methods_;
9989 // Return whether NAME is an unexported field or method, for better
9990 // error reporting.
9992 bool
9993 Named_type::is_unexported_local_method(Gogo* gogo,
9994 const std::string& name) const
9996 if (this->is_error_)
9997 return false;
9998 if (this->is_alias_)
10000 Named_type* nt = this->type_->named_type();
10001 if (nt != NULL)
10003 if (this->seen_alias_)
10004 return false;
10005 this->seen_alias_ = true;
10006 bool ret = nt->is_unexported_local_method(gogo, name);
10007 this->seen_alias_ = false;
10008 return ret;
10010 return false;
10012 Bindings* methods = this->local_methods_;
10013 if (methods != NULL)
10015 for (Bindings::const_declarations_iterator p =
10016 methods->begin_declarations();
10017 p != methods->end_declarations();
10018 ++p)
10020 if (Gogo::is_hidden_name(p->first)
10021 && name == Gogo::unpack_hidden_name(p->first)
10022 && gogo->pack_hidden_name(name, false) != p->first)
10023 return true;
10026 return false;
10029 // Build the complete list of methods for this type, which means
10030 // recursively including all methods for anonymous fields. Create all
10031 // stub methods.
10033 void
10034 Named_type::finalize_methods(Gogo* gogo)
10036 if (this->is_alias_)
10037 return;
10038 if (this->all_methods_ != NULL)
10039 return;
10041 if (this->local_methods_ != NULL
10042 && (this->points_to() != NULL || this->interface_type() != NULL))
10044 const Bindings* lm = this->local_methods_;
10045 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10046 p != lm->end_declarations();
10047 ++p)
10048 go_error_at(p->second->location(),
10049 "invalid pointer or interface receiver type");
10050 delete this->local_methods_;
10051 this->local_methods_ = NULL;
10052 return;
10055 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10058 // Return whether this type has any methods.
10060 bool
10061 Named_type::has_any_methods() const
10063 if (this->is_error_)
10064 return false;
10065 if (this->is_alias_)
10067 if (this->type_->named_type() != NULL)
10069 if (this->seen_alias_)
10070 return false;
10071 this->seen_alias_ = true;
10072 bool ret = this->type_->named_type()->has_any_methods();
10073 this->seen_alias_ = false;
10074 return ret;
10076 if (this->type_->struct_type() != NULL)
10077 return this->type_->struct_type()->has_any_methods();
10078 return false;
10080 return this->all_methods_ != NULL;
10083 // Return the methods for this type.
10085 const Methods*
10086 Named_type::methods() const
10088 if (this->is_error_)
10089 return NULL;
10090 if (this->is_alias_)
10092 if (this->type_->named_type() != NULL)
10094 if (this->seen_alias_)
10095 return NULL;
10096 this->seen_alias_ = true;
10097 const Methods* ret = this->type_->named_type()->methods();
10098 this->seen_alias_ = false;
10099 return ret;
10101 if (this->type_->struct_type() != NULL)
10102 return this->type_->struct_type()->methods();
10103 return NULL;
10105 return this->all_methods_;
10108 // Return the method NAME, or NULL if there isn't one or if it is
10109 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10110 // ambiguous.
10112 Method*
10113 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10115 if (this->is_error_)
10116 return NULL;
10117 if (this->is_alias_)
10119 if (is_ambiguous != NULL)
10120 *is_ambiguous = false;
10121 if (this->type_->named_type() != NULL)
10123 if (this->seen_alias_)
10124 return NULL;
10125 this->seen_alias_ = true;
10126 Named_type* nt = this->type_->named_type();
10127 Method* ret = nt->method_function(name, is_ambiguous);
10128 this->seen_alias_ = false;
10129 return ret;
10131 if (this->type_->struct_type() != NULL)
10132 return this->type_->struct_type()->method_function(name, is_ambiguous);
10133 return NULL;
10135 return Type::method_function(this->all_methods_, name, is_ambiguous);
10138 // Return a pointer to the interface method table for this type for
10139 // the interface INTERFACE. IS_POINTER is true if this is for a
10140 // pointer to THIS.
10142 Expression*
10143 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10145 if (this->is_error_)
10146 return Expression::make_error(this->location_);
10147 if (this->is_alias_)
10149 if (this->type_->named_type() != NULL)
10151 if (this->seen_alias_)
10152 return Expression::make_error(this->location_);
10153 this->seen_alias_ = true;
10154 Named_type* nt = this->type_->named_type();
10155 Expression* ret = nt->interface_method_table(interface, is_pointer);
10156 this->seen_alias_ = false;
10157 return ret;
10159 if (this->type_->struct_type() != NULL)
10160 return this->type_->struct_type()->interface_method_table(interface,
10161 is_pointer);
10162 go_unreachable();
10164 return Type::interface_method_table(this, interface, is_pointer,
10165 &this->interface_method_tables_,
10166 &this->pointer_interface_method_tables_);
10169 // Look for a use of a complete type within another type. This is
10170 // used to check that we don't try to use a type within itself.
10172 class Find_type_use : public Traverse
10174 public:
10175 Find_type_use(Named_type* find_type)
10176 : Traverse(traverse_types),
10177 find_type_(find_type), found_(false)
10180 // Whether we found the type.
10181 bool
10182 found() const
10183 { return this->found_; }
10185 protected:
10187 type(Type*);
10189 private:
10190 // The type we are looking for.
10191 Named_type* find_type_;
10192 // Whether we found the type.
10193 bool found_;
10196 // Check for FIND_TYPE in TYPE.
10199 Find_type_use::type(Type* type)
10201 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10203 this->found_ = true;
10204 return TRAVERSE_EXIT;
10207 // It's OK if we see a reference to the type in any type which is
10208 // essentially a pointer: a pointer, a slice, a function, a map, or
10209 // a channel.
10210 if (type->points_to() != NULL
10211 || type->is_slice_type()
10212 || type->function_type() != NULL
10213 || type->map_type() != NULL
10214 || type->channel_type() != NULL)
10215 return TRAVERSE_SKIP_COMPONENTS;
10217 // For an interface, a reference to the type in a method type should
10218 // be ignored, but we have to consider direct inheritance. When
10219 // this is called, there may be cases of direct inheritance
10220 // represented as a method with no name.
10221 if (type->interface_type() != NULL)
10223 const Typed_identifier_list* methods = type->interface_type()->methods();
10224 if (methods != NULL)
10226 for (Typed_identifier_list::const_iterator p = methods->begin();
10227 p != methods->end();
10228 ++p)
10230 if (p->name().empty())
10232 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10233 return TRAVERSE_EXIT;
10237 return TRAVERSE_SKIP_COMPONENTS;
10240 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10241 // to convert TYPE to the backend representation before we convert
10242 // FIND_TYPE_.
10243 if (type->named_type() != NULL)
10245 switch (type->base()->classification())
10247 case Type::TYPE_ERROR:
10248 case Type::TYPE_BOOLEAN:
10249 case Type::TYPE_INTEGER:
10250 case Type::TYPE_FLOAT:
10251 case Type::TYPE_COMPLEX:
10252 case Type::TYPE_STRING:
10253 case Type::TYPE_NIL:
10254 break;
10256 case Type::TYPE_ARRAY:
10257 case Type::TYPE_STRUCT:
10258 this->find_type_->add_dependency(type->named_type());
10259 break;
10261 case Type::TYPE_NAMED:
10262 case Type::TYPE_FORWARD:
10263 go_assert(saw_errors());
10264 break;
10266 case Type::TYPE_VOID:
10267 case Type::TYPE_SINK:
10268 case Type::TYPE_FUNCTION:
10269 case Type::TYPE_POINTER:
10270 case Type::TYPE_CALL_MULTIPLE_RESULT:
10271 case Type::TYPE_MAP:
10272 case Type::TYPE_CHANNEL:
10273 case Type::TYPE_INTERFACE:
10274 default:
10275 go_unreachable();
10279 return TRAVERSE_CONTINUE;
10282 // Look for a circular reference of an alias.
10284 class Find_alias : public Traverse
10286 public:
10287 Find_alias(Named_type* find_type)
10288 : Traverse(traverse_types),
10289 find_type_(find_type), found_(false)
10292 // Whether we found the type.
10293 bool
10294 found() const
10295 { return this->found_; }
10297 protected:
10299 type(Type*);
10301 private:
10302 // The type we are looking for.
10303 Named_type* find_type_;
10304 // Whether we found the type.
10305 bool found_;
10309 Find_alias::type(Type* type)
10311 Named_type* nt = type->named_type();
10312 if (nt != NULL)
10314 if (nt == this->find_type_)
10316 this->found_ = true;
10317 return TRAVERSE_EXIT;
10320 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10321 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10322 // an alias itself, it's OK if whatever T2 is defined as refers
10323 // to T1.
10324 if (!nt->is_alias())
10325 return TRAVERSE_SKIP_COMPONENTS;
10328 return TRAVERSE_CONTINUE;
10331 // Verify that a named type does not refer to itself.
10333 bool
10334 Named_type::do_verify()
10336 if (this->is_verified_)
10337 return true;
10338 this->is_verified_ = true;
10340 if (this->is_error_)
10341 return false;
10343 if (this->is_alias_)
10345 Find_alias find(this);
10346 Type::traverse(this->type_, &find);
10347 if (find.found())
10349 go_error_at(this->location_, "invalid recursive alias %qs",
10350 this->message_name().c_str());
10351 this->is_error_ = true;
10352 return false;
10356 Find_type_use find(this);
10357 Type::traverse(this->type_, &find);
10358 if (find.found())
10360 go_error_at(this->location_, "invalid recursive type %qs",
10361 this->message_name().c_str());
10362 this->is_error_ = true;
10363 return false;
10366 // Check whether any of the local methods overloads an existing
10367 // struct field or interface method. We don't need to check the
10368 // list of methods against itself: that is handled by the Bindings
10369 // code.
10370 if (this->local_methods_ != NULL)
10372 Struct_type* st = this->type_->struct_type();
10373 if (st != NULL)
10375 for (Bindings::const_declarations_iterator p =
10376 this->local_methods_->begin_declarations();
10377 p != this->local_methods_->end_declarations();
10378 ++p)
10380 const std::string& name(p->first);
10381 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10383 go_error_at(p->second->location(),
10384 "method %qs redeclares struct field name",
10385 Gogo::message_name(name).c_str());
10391 return true;
10394 // Return whether this type is or contains a pointer.
10396 bool
10397 Named_type::do_has_pointer() const
10399 if (this->seen_)
10400 return false;
10401 this->seen_ = true;
10402 bool ret = this->type_->has_pointer();
10403 this->seen_ = false;
10404 return ret;
10407 // Return whether comparisons for this type can use the identity
10408 // function.
10410 bool
10411 Named_type::do_compare_is_identity(Gogo* gogo)
10413 // We don't use this->seen_ here because compare_is_identity may
10414 // call base() later, and that will mess up if seen_ is set here.
10415 if (this->seen_in_compare_is_identity_)
10416 return false;
10417 this->seen_in_compare_is_identity_ = true;
10418 bool ret = this->type_->compare_is_identity(gogo);
10419 this->seen_in_compare_is_identity_ = false;
10420 return ret;
10423 // Return whether this type is reflexive--whether it is always equal
10424 // to itself.
10426 bool
10427 Named_type::do_is_reflexive()
10429 if (this->seen_in_compare_is_identity_)
10430 return false;
10431 this->seen_in_compare_is_identity_ = true;
10432 bool ret = this->type_->is_reflexive();
10433 this->seen_in_compare_is_identity_ = false;
10434 return ret;
10437 // Return whether this type needs a key update when used as a map key.
10439 bool
10440 Named_type::do_needs_key_update()
10442 if (this->seen_in_compare_is_identity_)
10443 return true;
10444 this->seen_in_compare_is_identity_ = true;
10445 bool ret = this->type_->needs_key_update();
10446 this->seen_in_compare_is_identity_ = false;
10447 return ret;
10450 // Return a hash code. This is used for method lookup. We simply
10451 // hash on the name itself.
10453 unsigned int
10454 Named_type::do_hash_for_method(Gogo* gogo) const
10456 if (this->is_error_)
10457 return 0;
10459 // Aliases are handled in Type::hash_for_method.
10460 go_assert(!this->is_alias_);
10462 const std::string& name(this->named_object()->name());
10463 unsigned int ret = Type::hash_string(name, 0);
10465 // GOGO will be NULL here when called from Type_hash_identical.
10466 // That is OK because that is only used for internal hash tables
10467 // where we are going to be comparing named types for equality. In
10468 // other cases, which are cases where the runtime is going to
10469 // compare hash codes to see if the types are the same, we need to
10470 // include the pkgpath in the hash.
10471 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10473 const Package* package = this->named_object()->package();
10474 if (package == NULL)
10475 ret = Type::hash_string(gogo->pkgpath(), ret);
10476 else
10477 ret = Type::hash_string(package->pkgpath(), ret);
10480 return ret;
10483 // Convert a named type to the backend representation. In order to
10484 // get dependencies right, we fill in a dummy structure for this type,
10485 // then convert all the dependencies, then complete this type. When
10486 // this function is complete, the size of the type is known.
10488 void
10489 Named_type::convert(Gogo* gogo)
10491 if (this->is_error_ || this->is_converted_)
10492 return;
10494 this->create_placeholder(gogo);
10496 // If we are called to turn unsafe.Sizeof into a constant, we may
10497 // not have verified the type yet. We have to make sure it is
10498 // verified, since that sets the list of dependencies.
10499 this->verify();
10501 // Convert all the dependencies. If they refer indirectly back to
10502 // this type, they will pick up the intermediate representation we just
10503 // created.
10504 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10505 p != this->dependencies_.end();
10506 ++p)
10507 (*p)->convert(gogo);
10509 // Complete this type.
10510 Btype* bt = this->named_btype_;
10511 Type* base = this->type_->base();
10512 switch (base->classification())
10514 case TYPE_VOID:
10515 case TYPE_BOOLEAN:
10516 case TYPE_INTEGER:
10517 case TYPE_FLOAT:
10518 case TYPE_COMPLEX:
10519 case TYPE_STRING:
10520 case TYPE_NIL:
10521 break;
10523 case TYPE_MAP:
10524 case TYPE_CHANNEL:
10525 break;
10527 case TYPE_FUNCTION:
10528 case TYPE_POINTER:
10529 // The size of these types is already correct. We don't worry
10530 // about filling them in until later, when we also track
10531 // circular references.
10532 break;
10534 case TYPE_STRUCT:
10536 std::vector<Backend::Btyped_identifier> bfields;
10537 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10538 true, &bfields);
10539 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10540 bt = gogo->backend()->error_type();
10542 break;
10544 case TYPE_ARRAY:
10545 // Slice types were completed in create_placeholder.
10546 if (!base->is_slice_type())
10548 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10549 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10550 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10551 bt = gogo->backend()->error_type();
10553 break;
10555 case TYPE_INTERFACE:
10556 // Interface types were completed in create_placeholder.
10557 break;
10559 case TYPE_ERROR:
10560 return;
10562 default:
10563 case TYPE_SINK:
10564 case TYPE_CALL_MULTIPLE_RESULT:
10565 case TYPE_NAMED:
10566 case TYPE_FORWARD:
10567 go_unreachable();
10570 this->named_btype_ = bt;
10571 this->is_converted_ = true;
10572 this->is_placeholder_ = false;
10575 // Create the placeholder for a named type. This is the first step in
10576 // converting to the backend representation.
10578 void
10579 Named_type::create_placeholder(Gogo* gogo)
10581 if (this->is_error_)
10582 this->named_btype_ = gogo->backend()->error_type();
10584 if (this->named_btype_ != NULL)
10585 return;
10587 // Create the structure for this type. Note that because we call
10588 // base() here, we don't attempt to represent a named type defined
10589 // as another named type. Instead both named types will point to
10590 // different base representations.
10591 Type* base = this->type_->base();
10592 Btype* bt;
10593 bool set_name = true;
10594 switch (base->classification())
10596 case TYPE_ERROR:
10597 this->is_error_ = true;
10598 this->named_btype_ = gogo->backend()->error_type();
10599 return;
10601 case TYPE_VOID:
10602 case TYPE_BOOLEAN:
10603 case TYPE_INTEGER:
10604 case TYPE_FLOAT:
10605 case TYPE_COMPLEX:
10606 case TYPE_STRING:
10607 case TYPE_NIL:
10608 // These are simple basic types, we can just create them
10609 // directly.
10610 bt = Type::get_named_base_btype(gogo, base);
10611 break;
10613 case TYPE_MAP:
10614 case TYPE_CHANNEL:
10615 // All maps and channels have the same backend representation.
10616 bt = Type::get_named_base_btype(gogo, base);
10617 break;
10619 case TYPE_FUNCTION:
10620 case TYPE_POINTER:
10622 bool for_function = base->classification() == TYPE_FUNCTION;
10623 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10624 this->location_,
10625 for_function);
10626 set_name = false;
10628 break;
10630 case TYPE_STRUCT:
10631 bt = gogo->backend()->placeholder_struct_type(this->name(),
10632 this->location_);
10633 this->is_placeholder_ = true;
10634 set_name = false;
10635 break;
10637 case TYPE_ARRAY:
10638 if (base->is_slice_type())
10639 bt = gogo->backend()->placeholder_struct_type(this->name(),
10640 this->location_);
10641 else
10643 bt = gogo->backend()->placeholder_array_type(this->name(),
10644 this->location_);
10645 this->is_placeholder_ = true;
10647 set_name = false;
10648 break;
10650 case TYPE_INTERFACE:
10651 if (base->interface_type()->is_empty())
10652 bt = Interface_type::get_backend_empty_interface_type(gogo);
10653 else
10655 bt = gogo->backend()->placeholder_struct_type(this->name(),
10656 this->location_);
10657 set_name = false;
10659 break;
10661 default:
10662 case TYPE_SINK:
10663 case TYPE_CALL_MULTIPLE_RESULT:
10664 case TYPE_NAMED:
10665 case TYPE_FORWARD:
10666 go_unreachable();
10669 if (set_name)
10670 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10672 this->named_btype_ = bt;
10674 if (base->is_slice_type())
10676 // We do not record slices as dependencies of other types,
10677 // because we can fill them in completely here with the final
10678 // size.
10679 std::vector<Backend::Btyped_identifier> bfields;
10680 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10681 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10682 this->named_btype_ = gogo->backend()->error_type();
10684 else if (base->interface_type() != NULL
10685 && !base->interface_type()->is_empty())
10687 // We do not record interfaces as dependencies of other types,
10688 // because we can fill them in completely here with the final
10689 // size.
10690 std::vector<Backend::Btyped_identifier> bfields;
10691 get_backend_interface_fields(gogo, base->interface_type(), true,
10692 &bfields);
10693 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10694 this->named_btype_ = gogo->backend()->error_type();
10698 // Get the backend representation for a named type.
10700 Btype*
10701 Named_type::do_get_backend(Gogo* gogo)
10703 if (this->is_error_)
10704 return gogo->backend()->error_type();
10706 Btype* bt = this->named_btype_;
10708 if (!gogo->named_types_are_converted())
10710 // We have not completed converting named types. NAMED_BTYPE_
10711 // is a placeholder and we shouldn't do anything further.
10712 if (bt != NULL)
10713 return bt;
10715 // We don't build dependencies for types whose sizes do not
10716 // change or are not relevant, so we may see them here while
10717 // converting types.
10718 this->create_placeholder(gogo);
10719 bt = this->named_btype_;
10720 go_assert(bt != NULL);
10721 return bt;
10724 // We are not converting types. This should only be called if the
10725 // type has already been converted.
10726 if (!this->is_converted_)
10728 go_assert(saw_errors());
10729 return gogo->backend()->error_type();
10732 go_assert(bt != NULL);
10734 // Complete the backend representation.
10735 Type* base = this->type_->base();
10736 Btype* bt1;
10737 switch (base->classification())
10739 case TYPE_ERROR:
10740 return gogo->backend()->error_type();
10742 case TYPE_VOID:
10743 case TYPE_BOOLEAN:
10744 case TYPE_INTEGER:
10745 case TYPE_FLOAT:
10746 case TYPE_COMPLEX:
10747 case TYPE_STRING:
10748 case TYPE_NIL:
10749 case TYPE_MAP:
10750 case TYPE_CHANNEL:
10751 return bt;
10753 case TYPE_STRUCT:
10754 if (!this->seen_in_get_backend_)
10756 this->seen_in_get_backend_ = true;
10757 base->struct_type()->finish_backend_fields(gogo);
10758 this->seen_in_get_backend_ = false;
10760 return bt;
10762 case TYPE_ARRAY:
10763 if (!this->seen_in_get_backend_)
10765 this->seen_in_get_backend_ = true;
10766 base->array_type()->finish_backend_element(gogo);
10767 this->seen_in_get_backend_ = false;
10769 return bt;
10771 case TYPE_INTERFACE:
10772 if (!this->seen_in_get_backend_)
10774 this->seen_in_get_backend_ = true;
10775 base->interface_type()->finish_backend_methods(gogo);
10776 this->seen_in_get_backend_ = false;
10778 return bt;
10780 case TYPE_FUNCTION:
10781 // Don't build a circular data structure. GENERIC can't handle
10782 // it.
10783 if (this->seen_in_get_backend_)
10785 this->is_circular_ = true;
10786 return gogo->backend()->circular_pointer_type(bt, true);
10788 this->seen_in_get_backend_ = true;
10789 bt1 = Type::get_named_base_btype(gogo, base);
10790 this->seen_in_get_backend_ = false;
10791 if (this->is_circular_)
10792 bt1 = gogo->backend()->circular_pointer_type(bt, true);
10793 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10794 bt = gogo->backend()->error_type();
10795 return bt;
10797 case TYPE_POINTER:
10798 // Don't build a circular data structure. GENERIC can't handle
10799 // it.
10800 if (this->seen_in_get_backend_)
10802 this->is_circular_ = true;
10803 return gogo->backend()->circular_pointer_type(bt, false);
10805 this->seen_in_get_backend_ = true;
10806 bt1 = Type::get_named_base_btype(gogo, base);
10807 this->seen_in_get_backend_ = false;
10808 if (this->is_circular_)
10809 bt1 = gogo->backend()->circular_pointer_type(bt, false);
10810 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10811 bt = gogo->backend()->error_type();
10812 return bt;
10814 default:
10815 case TYPE_SINK:
10816 case TYPE_CALL_MULTIPLE_RESULT:
10817 case TYPE_NAMED:
10818 case TYPE_FORWARD:
10819 go_unreachable();
10822 go_unreachable();
10825 // Build a type descriptor for a named type.
10827 Expression*
10828 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10830 if (this->is_error_)
10831 return Expression::make_error(this->location_);
10832 if (name == NULL && this->is_alias_)
10834 if (this->seen_alias_)
10835 return Expression::make_error(this->location_);
10836 this->seen_alias_ = true;
10837 Expression* ret = this->type_->type_descriptor(gogo, NULL);
10838 this->seen_alias_ = false;
10839 return ret;
10842 // If NAME is not NULL, then we don't really want the type
10843 // descriptor for this type; we want the descriptor for the
10844 // underlying type, giving it the name NAME.
10845 return this->named_type_descriptor(gogo, this->type_,
10846 name == NULL ? this : name);
10849 // Add to the reflection string. This is used mostly for the name of
10850 // the type used in a type descriptor, not for actual reflection
10851 // strings.
10853 void
10854 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10856 this->append_reflection_type_name(gogo, false, ret);
10859 // Add to the reflection string. For an alias we normally use the
10860 // real name, but if USE_ALIAS is true we use the alias name itself.
10862 void
10863 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10864 std::string* ret) const
10866 if (this->is_error_)
10867 return;
10868 if (this->is_alias_ && !use_alias)
10870 if (this->seen_alias_)
10871 return;
10872 this->seen_alias_ = true;
10873 this->append_reflection(this->type_, gogo, ret);
10874 this->seen_alias_ = false;
10875 return;
10877 if (!this->is_builtin())
10879 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10880 // make a unique reflection string, so that the type
10881 // canonicalization in the reflect package will work. In order
10882 // to be compatible with the gc compiler, we put tabs into the
10883 // package path, so that the reflect methods can discard it.
10884 const Package* package = this->named_object_->package();
10885 ret->push_back('\t');
10886 ret->append(package != NULL
10887 ? package->pkgpath_symbol()
10888 : gogo->pkgpath_symbol());
10889 ret->push_back('\t');
10890 ret->append(package != NULL
10891 ? package->package_name()
10892 : gogo->package_name());
10893 ret->push_back('.');
10895 if (this->in_function_ != NULL)
10897 ret->push_back('\t');
10898 const Typed_identifier* rcvr =
10899 this->in_function_->func_value()->type()->receiver();
10900 if (rcvr != NULL)
10902 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10903 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10904 ret->push_back('.');
10906 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10907 ret->push_back('$');
10908 if (this->in_function_index_ > 0)
10910 char buf[30];
10911 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10912 ret->append(buf);
10913 ret->push_back('$');
10915 ret->push_back('\t');
10917 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10920 // Export the type. This is called to export a global type.
10922 void
10923 Named_type::export_named_type(Export* exp, const std::string&) const
10925 // We don't need to write the name of the type here, because it will
10926 // be written by Export::write_type anyhow.
10927 exp->write_c_string("type ");
10928 exp->write_type(this);
10929 exp->write_c_string(";\n");
10932 // Import a named type.
10934 void
10935 Named_type::import_named_type(Import* imp, Named_type** ptype)
10937 imp->require_c_string("type ");
10938 Type *type = imp->read_type();
10939 *ptype = type->named_type();
10940 go_assert(*ptype != NULL);
10941 imp->require_c_string(";\n");
10944 // Export the type when it is referenced by another type. In this
10945 // case Export::export_type will already have issued the name.
10947 void
10948 Named_type::do_export(Export* exp) const
10950 exp->write_type(this->type_);
10952 // To save space, we only export the methods directly attached to
10953 // this type.
10954 Bindings* methods = this->local_methods_;
10955 if (methods == NULL)
10956 return;
10958 exp->write_c_string("\n");
10959 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10960 p != methods->end_definitions();
10961 ++p)
10963 exp->write_c_string(" ");
10964 (*p)->export_named_object(exp);
10967 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10968 p != methods->end_declarations();
10969 ++p)
10971 if (p->second->is_function_declaration())
10973 exp->write_c_string(" ");
10974 p->second->export_named_object(exp);
10979 // Make a named type.
10981 Named_type*
10982 Type::make_named_type(Named_object* named_object, Type* type,
10983 Location location)
10985 return new Named_type(named_object, type, location);
10988 // Finalize the methods for TYPE. It will be a named type or a struct
10989 // type. This sets *ALL_METHODS to the list of methods, and builds
10990 // all required stubs.
10992 void
10993 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10994 Methods** all_methods)
10996 *all_methods = new Methods();
10997 std::vector<const Named_type*> seen;
10998 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10999 if ((*all_methods)->empty())
11001 delete *all_methods;
11002 *all_methods = NULL;
11004 Type::build_stub_methods(gogo, type, *all_methods, location);
11007 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11008 // build up the struct field indexes as we go. DEPTH is the depth of
11009 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11010 // adding these methods for an anonymous field with pointer type.
11011 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11012 // calls the real method. TYPES_SEEN is used to avoid infinite
11013 // recursion.
11015 void
11016 Type::add_methods_for_type(const Type* type,
11017 const Method::Field_indexes* field_indexes,
11018 unsigned int depth,
11019 bool is_embedded_pointer,
11020 bool needs_stub_method,
11021 std::vector<const Named_type*>* seen,
11022 Methods* methods)
11024 // Pointer types may not have methods.
11025 if (type->points_to() != NULL)
11026 return;
11028 const Named_type* nt = type->named_type();
11029 if (nt != NULL)
11031 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11032 p != seen->end();
11033 ++p)
11035 if (*p == nt)
11036 return;
11039 seen->push_back(nt);
11041 Type::add_local_methods_for_type(nt, field_indexes, depth,
11042 is_embedded_pointer, needs_stub_method,
11043 methods);
11046 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11047 is_embedded_pointer, needs_stub_method,
11048 seen, methods);
11050 // If we are called with depth > 0, then we are looking at an
11051 // anonymous field of a struct. If such a field has interface type,
11052 // then we need to add the interface methods. We don't want to add
11053 // them when depth == 0, because we will already handle them
11054 // following the usual rules for an interface type.
11055 if (depth > 0)
11056 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11058 if (nt != NULL)
11059 seen->pop_back();
11062 // Add the local methods for the named type NT to *METHODS. The
11063 // parameters are as for add_methods_to_type.
11065 void
11066 Type::add_local_methods_for_type(const Named_type* nt,
11067 const Method::Field_indexes* field_indexes,
11068 unsigned int depth,
11069 bool is_embedded_pointer,
11070 bool needs_stub_method,
11071 Methods* methods)
11073 const Bindings* local_methods = nt->local_methods();
11074 if (local_methods == NULL)
11075 return;
11077 for (Bindings::const_declarations_iterator p =
11078 local_methods->begin_declarations();
11079 p != local_methods->end_declarations();
11080 ++p)
11082 Named_object* no = p->second;
11083 bool is_value_method = (is_embedded_pointer
11084 || !Type::method_expects_pointer(no));
11085 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11086 (needs_stub_method || depth > 0));
11087 if (!methods->insert(no->name(), m))
11088 delete m;
11092 // Add the embedded methods for TYPE to *METHODS. These are the
11093 // methods attached to anonymous fields. The parameters are as for
11094 // add_methods_to_type.
11096 void
11097 Type::add_embedded_methods_for_type(const Type* type,
11098 const Method::Field_indexes* field_indexes,
11099 unsigned int depth,
11100 bool is_embedded_pointer,
11101 bool needs_stub_method,
11102 std::vector<const Named_type*>* seen,
11103 Methods* methods)
11105 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11106 // struct.
11107 const Struct_type* st = type->struct_type();
11108 if (st == NULL)
11109 return;
11111 const Struct_field_list* fields = st->fields();
11112 if (fields == NULL)
11113 return;
11115 unsigned int i = 0;
11116 for (Struct_field_list::const_iterator pf = fields->begin();
11117 pf != fields->end();
11118 ++pf, ++i)
11120 if (!pf->is_anonymous())
11121 continue;
11123 Type* ftype = pf->type();
11124 bool is_pointer = false;
11125 if (ftype->points_to() != NULL)
11127 ftype = ftype->points_to();
11128 is_pointer = true;
11130 Named_type* fnt = ftype->named_type();
11131 if (fnt == NULL)
11133 // This is an error, but it will be diagnosed elsewhere.
11134 continue;
11137 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11138 sub_field_indexes->next = field_indexes;
11139 sub_field_indexes->field_index = i;
11141 Methods tmp_methods;
11142 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11143 (is_embedded_pointer || is_pointer),
11144 (needs_stub_method
11145 || is_pointer
11146 || i > 0),
11147 seen,
11148 &tmp_methods);
11149 // Check if there are promoted methods that conflict with field names and
11150 // don't add them to the method map.
11151 for (Methods::const_iterator p = tmp_methods.begin();
11152 p != tmp_methods.end();
11153 ++p)
11155 bool found = false;
11156 for (Struct_field_list::const_iterator fp = fields->begin();
11157 fp != fields->end();
11158 ++fp)
11160 if (fp->field_name() == p->first)
11162 found = true;
11163 break;
11166 if (!found &&
11167 !methods->insert(p->first, p->second))
11168 delete p->second;
11173 // If TYPE is an interface type, then add its method to *METHODS.
11174 // This is for interface methods attached to an anonymous field. The
11175 // parameters are as for add_methods_for_type.
11177 void
11178 Type::add_interface_methods_for_type(const Type* type,
11179 const Method::Field_indexes* field_indexes,
11180 unsigned int depth,
11181 Methods* methods)
11183 const Interface_type* it = type->interface_type();
11184 if (it == NULL)
11185 return;
11187 const Typed_identifier_list* imethods = it->methods();
11188 if (imethods == NULL)
11189 return;
11191 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11192 pm != imethods->end();
11193 ++pm)
11195 Function_type* fntype = pm->type()->function_type();
11196 if (fntype == NULL)
11198 // This is an error, but it should be reported elsewhere
11199 // when we look at the methods for IT.
11200 continue;
11202 go_assert(!fntype->is_method());
11203 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11204 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11205 field_indexes, depth);
11206 if (!methods->insert(pm->name(), m))
11207 delete m;
11211 // Build stub methods for TYPE as needed. METHODS is the set of
11212 // methods for the type. A stub method may be needed when a type
11213 // inherits a method from an anonymous field. When we need the
11214 // address of the method, as in a type descriptor, we need to build a
11215 // little stub which does the required field dereferences and jumps to
11216 // the real method. LOCATION is the location of the type definition.
11218 void
11219 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11220 Location location)
11222 if (methods == NULL)
11223 return;
11224 for (Methods::const_iterator p = methods->begin();
11225 p != methods->end();
11226 ++p)
11228 Method* m = p->second;
11229 if (m->is_ambiguous() || !m->needs_stub_method())
11230 continue;
11232 const std::string& name(p->first);
11234 // Build a stub method.
11236 const Function_type* fntype = m->type();
11238 static unsigned int counter;
11239 char buf[100];
11240 snprintf(buf, sizeof buf, "$this%u", counter);
11241 ++counter;
11243 Type* receiver_type = const_cast<Type*>(type);
11244 if (!m->is_value_method())
11245 receiver_type = Type::make_pointer_type(receiver_type);
11246 Location receiver_location = m->receiver_location();
11247 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11248 receiver_location);
11250 const Typed_identifier_list* fnparams = fntype->parameters();
11251 Typed_identifier_list* stub_params;
11252 if (fnparams == NULL || fnparams->empty())
11253 stub_params = NULL;
11254 else
11256 // We give each stub parameter a unique name.
11257 stub_params = new Typed_identifier_list();
11258 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11259 pp != fnparams->end();
11260 ++pp)
11262 char pbuf[100];
11263 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11264 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11265 pp->location()));
11266 ++counter;
11270 const Typed_identifier_list* fnresults = fntype->results();
11271 Typed_identifier_list* stub_results;
11272 if (fnresults == NULL || fnresults->empty())
11273 stub_results = NULL;
11274 else
11276 // We create the result parameters without any names, since
11277 // we won't refer to them.
11278 stub_results = new Typed_identifier_list();
11279 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11280 pr != fnresults->end();
11281 ++pr)
11282 stub_results->push_back(Typed_identifier("", pr->type(),
11283 pr->location()));
11286 Function_type* stub_type = Type::make_function_type(receiver,
11287 stub_params,
11288 stub_results,
11289 fntype->location());
11290 if (fntype->is_varargs())
11291 stub_type->set_is_varargs();
11293 // We only create the function in the package which creates the
11294 // type.
11295 const Package* package;
11296 if (type->named_type() == NULL)
11297 package = NULL;
11298 else
11299 package = type->named_type()->named_object()->package();
11300 std::string stub_name = gogo->stub_method_name(package, name);
11301 Named_object* stub;
11302 if (package != NULL)
11303 stub = Named_object::make_function_declaration(stub_name, package,
11304 stub_type, location);
11305 else
11307 stub = gogo->start_function(stub_name, stub_type, false,
11308 fntype->location());
11309 Type::build_one_stub_method(gogo, m, buf, stub_params,
11310 fntype->is_varargs(), location);
11311 gogo->finish_function(fntype->location());
11313 if (type->named_type() == NULL && stub->is_function())
11314 stub->func_value()->set_is_unnamed_type_stub_method();
11315 if (m->nointerface() && stub->is_function())
11316 stub->func_value()->set_nointerface();
11319 m->set_stub_object(stub);
11323 // Build a stub method which adjusts the receiver as required to call
11324 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11325 // PARAMS is the list of function parameters.
11327 void
11328 Type::build_one_stub_method(Gogo* gogo, Method* method,
11329 const char* receiver_name,
11330 const Typed_identifier_list* params,
11331 bool is_varargs,
11332 Location location)
11334 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11335 go_assert(receiver_object != NULL);
11337 Expression* expr = Expression::make_var_reference(receiver_object, location);
11338 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11339 if (expr->type()->points_to() == NULL)
11340 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11342 Expression_list* arguments;
11343 if (params == NULL || params->empty())
11344 arguments = NULL;
11345 else
11347 arguments = new Expression_list();
11348 for (Typed_identifier_list::const_iterator p = params->begin();
11349 p != params->end();
11350 ++p)
11352 Named_object* param = gogo->lookup(p->name(), NULL);
11353 go_assert(param != NULL);
11354 Expression* param_ref = Expression::make_var_reference(param,
11355 location);
11356 arguments->push_back(param_ref);
11360 Expression* func = method->bind_method(expr, location);
11361 go_assert(func != NULL);
11362 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11363 location);
11365 gogo->add_statement(Statement::make_return_from_call(call, location));
11368 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11369 // in reverse order.
11371 Expression*
11372 Type::apply_field_indexes(Expression* expr,
11373 const Method::Field_indexes* field_indexes,
11374 Location location)
11376 if (field_indexes == NULL)
11377 return expr;
11378 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11379 Struct_type* stype = expr->type()->deref()->struct_type();
11380 go_assert(stype != NULL
11381 && field_indexes->field_index < stype->field_count());
11382 if (expr->type()->struct_type() == NULL)
11384 go_assert(expr->type()->points_to() != NULL);
11385 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11386 location);
11387 go_assert(expr->type()->struct_type() == stype);
11389 return Expression::make_field_reference(expr, field_indexes->field_index,
11390 location);
11393 // Return whether NO is a method for which the receiver is a pointer.
11395 bool
11396 Type::method_expects_pointer(const Named_object* no)
11398 const Function_type *fntype;
11399 if (no->is_function())
11400 fntype = no->func_value()->type();
11401 else if (no->is_function_declaration())
11402 fntype = no->func_declaration_value()->type();
11403 else
11404 go_unreachable();
11405 return fntype->receiver()->type()->points_to() != NULL;
11408 // Given a set of methods for a type, METHODS, return the method NAME,
11409 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11410 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11411 // but is ambiguous (and return NULL).
11413 Method*
11414 Type::method_function(const Methods* methods, const std::string& name,
11415 bool* is_ambiguous)
11417 if (is_ambiguous != NULL)
11418 *is_ambiguous = false;
11419 if (methods == NULL)
11420 return NULL;
11421 Methods::const_iterator p = methods->find(name);
11422 if (p == methods->end())
11423 return NULL;
11424 Method* m = p->second;
11425 if (m->is_ambiguous())
11427 if (is_ambiguous != NULL)
11428 *is_ambiguous = true;
11429 return NULL;
11431 return m;
11434 // Return a pointer to the interface method table for TYPE for the
11435 // interface INTERFACE.
11437 Expression*
11438 Type::interface_method_table(Type* type,
11439 Interface_type *interface,
11440 bool is_pointer,
11441 Interface_method_tables** method_tables,
11442 Interface_method_tables** pointer_tables)
11444 go_assert(!interface->is_empty());
11446 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11448 if (*pimt == NULL)
11449 *pimt = new Interface_method_tables(5);
11451 std::pair<Interface_type*, Expression*> val(interface, NULL);
11452 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11454 Location loc = Linemap::predeclared_location();
11455 if (ins.second)
11457 // This is a new entry in the hash table.
11458 go_assert(ins.first->second == NULL);
11459 ins.first->second =
11460 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11462 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11465 // Look for field or method NAME for TYPE. Return an Expression for
11466 // the field or method bound to EXPR. If there is no such field or
11467 // method, give an appropriate error and return an error expression.
11469 Expression*
11470 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11471 const std::string& name,
11472 Location location)
11474 if (type->deref()->is_error_type())
11475 return Expression::make_error(location);
11477 const Named_type* nt = type->deref()->named_type();
11478 const Struct_type* st = type->deref()->struct_type();
11479 const Interface_type* it = type->interface_type();
11481 // If this is a pointer to a pointer, then it is possible that the
11482 // pointed-to type has methods.
11483 bool dereferenced = false;
11484 if (nt == NULL
11485 && st == NULL
11486 && it == NULL
11487 && type->points_to() != NULL
11488 && type->points_to()->points_to() != NULL)
11490 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11491 location);
11492 type = type->points_to();
11493 if (type->deref()->is_error_type())
11494 return Expression::make_error(location);
11495 nt = type->points_to()->named_type();
11496 st = type->points_to()->struct_type();
11497 dereferenced = true;
11500 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11501 || expr->is_addressable());
11502 std::vector<const Named_type*> seen;
11503 bool is_method = false;
11504 bool found_pointer_method = false;
11505 std::string ambig1;
11506 std::string ambig2;
11507 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11508 &seen, NULL, &is_method,
11509 &found_pointer_method, &ambig1, &ambig2))
11511 Expression* ret;
11512 if (!is_method)
11514 go_assert(st != NULL);
11515 if (type->struct_type() == NULL)
11517 if (dereferenced)
11519 go_error_at(location, "pointer type has no field %qs",
11520 Gogo::message_name(name).c_str());
11521 return Expression::make_error(location);
11523 go_assert(type->points_to() != NULL);
11524 expr = Expression::make_dereference(expr,
11525 Expression::NIL_CHECK_DEFAULT,
11526 location);
11527 go_assert(expr->type()->struct_type() == st);
11529 ret = st->field_reference(expr, name, location);
11530 if (ret == NULL)
11532 go_error_at(location, "type has no field %qs",
11533 Gogo::message_name(name).c_str());
11534 return Expression::make_error(location);
11537 else if (it != NULL && it->find_method(name) != NULL)
11538 ret = Expression::make_interface_field_reference(expr, name,
11539 location);
11540 else
11542 Method* m;
11543 if (nt != NULL)
11544 m = nt->method_function(name, NULL);
11545 else if (st != NULL)
11546 m = st->method_function(name, NULL);
11547 else
11548 go_unreachable();
11549 go_assert(m != NULL);
11550 if (dereferenced)
11552 go_error_at(location,
11553 "calling method %qs requires explicit dereference",
11554 Gogo::message_name(name).c_str());
11555 return Expression::make_error(location);
11557 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11558 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11559 ret = m->bind_method(expr, location);
11561 go_assert(ret != NULL);
11562 return ret;
11564 else
11566 if (Gogo::is_erroneous_name(name))
11568 // An error was already reported.
11570 else if (!ambig1.empty())
11571 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11572 Gogo::message_name(name).c_str(), ambig1.c_str(),
11573 ambig2.c_str());
11574 else if (found_pointer_method)
11575 go_error_at(location, "method requires a pointer receiver");
11576 else if (nt == NULL && st == NULL && it == NULL)
11577 go_error_at(location,
11578 ("reference to field %qs in object which "
11579 "has no fields or methods"),
11580 Gogo::message_name(name).c_str());
11581 else
11583 bool is_unexported;
11584 // The test for 'a' and 'z' is to handle builtin names,
11585 // which are not hidden.
11586 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11587 is_unexported = false;
11588 else
11590 std::string unpacked = Gogo::unpack_hidden_name(name);
11591 seen.clear();
11592 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11593 unpacked,
11594 &seen);
11596 if (is_unexported)
11597 go_error_at(location, "reference to unexported field or method %qs",
11598 Gogo::message_name(name).c_str());
11599 else
11600 go_error_at(location, "reference to undefined field or method %qs",
11601 Gogo::message_name(name).c_str());
11603 return Expression::make_error(location);
11607 // Look in TYPE for a field or method named NAME, return true if one
11608 // is found. This looks through embedded anonymous fields and handles
11609 // ambiguity. If a method is found, sets *IS_METHOD to true;
11610 // otherwise, if a field is found, set it to false. If
11611 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11612 // whose address can not be taken. SEEN is used to avoid infinite
11613 // recursion on invalid types.
11615 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11616 // method we couldn't use because it requires a pointer. LEVEL is
11617 // used for recursive calls, and can be NULL for a non-recursive call.
11618 // When this function returns false because it finds that the name is
11619 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11620 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11621 // will be unchanged.
11623 // This function just returns whether or not there is a field or
11624 // method, and whether it is a field or method. It doesn't build an
11625 // expression to refer to it. If it is a method, we then look in the
11626 // list of all methods for the type. If it is a field, the search has
11627 // to be done again, looking only for fields, and building up the
11628 // expression as we go.
11630 bool
11631 Type::find_field_or_method(const Type* type,
11632 const std::string& name,
11633 bool receiver_can_be_pointer,
11634 std::vector<const Named_type*>* seen,
11635 int* level,
11636 bool* is_method,
11637 bool* found_pointer_method,
11638 std::string* ambig1,
11639 std::string* ambig2)
11641 // Named types can have locally defined methods.
11642 const Named_type* nt = type->unalias()->named_type();
11643 if (nt == NULL && type->points_to() != NULL)
11644 nt = type->points_to()->unalias()->named_type();
11645 if (nt != NULL)
11647 Named_object* no = nt->find_local_method(name);
11648 if (no != NULL)
11650 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11652 *is_method = true;
11653 return true;
11656 // Record that we have found a pointer method in order to
11657 // give a better error message if we don't find anything
11658 // else.
11659 *found_pointer_method = true;
11662 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11663 p != seen->end();
11664 ++p)
11666 if (*p == nt)
11668 // We've already seen this type when searching for methods.
11669 return false;
11674 // Interface types can have methods.
11675 const Interface_type* it = type->interface_type();
11676 if (it != NULL && it->find_method(name) != NULL)
11678 *is_method = true;
11679 return true;
11682 // Struct types can have fields. They can also inherit fields and
11683 // methods from anonymous fields.
11684 const Struct_type* st = type->deref()->struct_type();
11685 if (st == NULL)
11686 return false;
11687 const Struct_field_list* fields = st->fields();
11688 if (fields == NULL)
11689 return false;
11691 if (nt != NULL)
11692 seen->push_back(nt);
11694 int found_level = 0;
11695 bool found_is_method = false;
11696 std::string found_ambig1;
11697 std::string found_ambig2;
11698 const Struct_field* found_parent = NULL;
11699 for (Struct_field_list::const_iterator pf = fields->begin();
11700 pf != fields->end();
11701 ++pf)
11703 if (pf->is_field_name(name))
11705 *is_method = false;
11706 if (nt != NULL)
11707 seen->pop_back();
11708 return true;
11711 if (!pf->is_anonymous())
11712 continue;
11714 if (pf->type()->deref()->is_error_type()
11715 || pf->type()->deref()->is_undefined())
11716 continue;
11718 Named_type* fnt = pf->type()->named_type();
11719 if (fnt == NULL)
11720 fnt = pf->type()->deref()->named_type();
11721 go_assert(fnt != NULL);
11723 // Methods with pointer receivers on embedded field are
11724 // inherited by the pointer to struct, and also by the struct
11725 // type if the field itself is a pointer.
11726 bool can_be_pointer = (receiver_can_be_pointer
11727 || pf->type()->points_to() != NULL);
11728 int sublevel = level == NULL ? 1 : *level + 1;
11729 bool sub_is_method;
11730 std::string subambig1;
11731 std::string subambig2;
11732 bool subfound = Type::find_field_or_method(fnt,
11733 name,
11734 can_be_pointer,
11735 seen,
11736 &sublevel,
11737 &sub_is_method,
11738 found_pointer_method,
11739 &subambig1,
11740 &subambig2);
11741 if (!subfound)
11743 if (!subambig1.empty())
11745 // The name was found via this field, but is ambiguous.
11746 // if the ambiguity is lower or at the same level as
11747 // anything else we have already found, then we want to
11748 // pass the ambiguity back to the caller.
11749 if (found_level == 0 || sublevel <= found_level)
11751 found_ambig1 = (Gogo::message_name(pf->field_name())
11752 + '.' + subambig1);
11753 found_ambig2 = (Gogo::message_name(pf->field_name())
11754 + '.' + subambig2);
11755 found_level = sublevel;
11759 else
11761 // The name was found via this field. Use the level to see
11762 // if we want to use this one, or whether it introduces an
11763 // ambiguity.
11764 if (found_level == 0 || sublevel < found_level)
11766 found_level = sublevel;
11767 found_is_method = sub_is_method;
11768 found_ambig1.clear();
11769 found_ambig2.clear();
11770 found_parent = &*pf;
11772 else if (sublevel > found_level)
11774 else if (found_ambig1.empty())
11776 // We found an ambiguity.
11777 go_assert(found_parent != NULL);
11778 found_ambig1 = Gogo::message_name(found_parent->field_name());
11779 found_ambig2 = Gogo::message_name(pf->field_name());
11781 else
11783 // We found an ambiguity, but we already know of one.
11784 // Just report the earlier one.
11789 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
11790 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11791 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
11792 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11794 if (nt != NULL)
11795 seen->pop_back();
11797 if (found_level == 0)
11798 return false;
11799 else if (found_is_method
11800 && type->named_type() != NULL
11801 && type->points_to() != NULL)
11803 // If this is a method inherited from a struct field in a named pointer
11804 // type, it is invalid to automatically dereference the pointer to the
11805 // struct to find this method.
11806 if (level != NULL)
11807 *level = found_level;
11808 *is_method = true;
11809 return false;
11811 else if (!found_ambig1.empty())
11813 go_assert(!found_ambig1.empty());
11814 ambig1->assign(found_ambig1);
11815 ambig2->assign(found_ambig2);
11816 if (level != NULL)
11817 *level = found_level;
11818 return false;
11820 else
11822 if (level != NULL)
11823 *level = found_level;
11824 *is_method = found_is_method;
11825 return true;
11829 // Return whether NAME is an unexported field or method for TYPE.
11831 bool
11832 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11833 const std::string& name,
11834 std::vector<const Named_type*>* seen)
11836 const Named_type* nt = type->named_type();
11837 if (nt == NULL)
11838 nt = type->deref()->named_type();
11839 if (nt != NULL)
11841 if (nt->is_unexported_local_method(gogo, name))
11842 return true;
11844 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11845 p != seen->end();
11846 ++p)
11848 if (*p == nt)
11850 // We've already seen this type.
11851 return false;
11856 const Interface_type* it = type->interface_type();
11857 if (it != NULL && it->is_unexported_method(gogo, name))
11858 return true;
11860 type = type->deref();
11862 const Struct_type* st = type->struct_type();
11863 if (st != NULL && st->is_unexported_local_field(gogo, name))
11864 return true;
11866 if (st == NULL)
11867 return false;
11869 const Struct_field_list* fields = st->fields();
11870 if (fields == NULL)
11871 return false;
11873 if (nt != NULL)
11874 seen->push_back(nt);
11876 for (Struct_field_list::const_iterator pf = fields->begin();
11877 pf != fields->end();
11878 ++pf)
11880 if (pf->is_anonymous()
11881 && !pf->type()->deref()->is_error_type()
11882 && !pf->type()->deref()->is_undefined())
11884 Named_type* subtype = pf->type()->named_type();
11885 if (subtype == NULL)
11886 subtype = pf->type()->deref()->named_type();
11887 if (subtype == NULL)
11889 // This is an error, but it will be diagnosed elsewhere.
11890 continue;
11892 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11894 if (nt != NULL)
11895 seen->pop_back();
11896 return true;
11901 if (nt != NULL)
11902 seen->pop_back();
11904 return false;
11907 // Class Forward_declaration.
11909 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11910 : Type(TYPE_FORWARD),
11911 named_object_(named_object->resolve()), warned_(false)
11913 go_assert(this->named_object_->is_unknown()
11914 || this->named_object_->is_type_declaration());
11917 // Return the named object.
11919 Named_object*
11920 Forward_declaration_type::named_object()
11922 return this->named_object_->resolve();
11925 const Named_object*
11926 Forward_declaration_type::named_object() const
11928 return this->named_object_->resolve();
11931 // Return the name of the forward declared type.
11933 const std::string&
11934 Forward_declaration_type::name() const
11936 return this->named_object()->name();
11939 // Warn about a use of a type which has been declared but not defined.
11941 void
11942 Forward_declaration_type::warn() const
11944 Named_object* no = this->named_object_->resolve();
11945 if (no->is_unknown())
11947 // The name was not defined anywhere.
11948 if (!this->warned_)
11950 go_error_at(this->named_object_->location(),
11951 "use of undefined type %qs",
11952 no->message_name().c_str());
11953 this->warned_ = true;
11956 else if (no->is_type_declaration())
11958 // The name was seen as a type, but the type was never defined.
11959 if (no->type_declaration_value()->using_type())
11961 go_error_at(this->named_object_->location(),
11962 "use of undefined type %qs",
11963 no->message_name().c_str());
11964 this->warned_ = true;
11967 else
11969 // The name was defined, but not as a type.
11970 if (!this->warned_)
11972 go_error_at(this->named_object_->location(), "expected type");
11973 this->warned_ = true;
11978 // Get the base type of a declaration. This gives an error if the
11979 // type has not yet been defined.
11981 Type*
11982 Forward_declaration_type::real_type()
11984 if (this->is_defined())
11986 Named_type* nt = this->named_object()->type_value();
11987 if (!nt->is_valid())
11988 return Type::make_error_type();
11989 return this->named_object()->type_value();
11991 else
11993 this->warn();
11994 return Type::make_error_type();
11998 const Type*
11999 Forward_declaration_type::real_type() const
12001 if (this->is_defined())
12003 const Named_type* nt = this->named_object()->type_value();
12004 if (!nt->is_valid())
12005 return Type::make_error_type();
12006 return this->named_object()->type_value();
12008 else
12010 this->warn();
12011 return Type::make_error_type();
12015 // Return whether the base type is defined.
12017 bool
12018 Forward_declaration_type::is_defined() const
12020 return this->named_object()->is_type();
12023 // Add a method. This is used when methods are defined before the
12024 // type.
12026 Named_object*
12027 Forward_declaration_type::add_method(const std::string& name,
12028 Function* function)
12030 Named_object* no = this->named_object();
12031 if (no->is_unknown())
12032 no->declare_as_type();
12033 return no->type_declaration_value()->add_method(name, function);
12036 // Add a method declaration. This is used when methods are declared
12037 // before the type.
12039 Named_object*
12040 Forward_declaration_type::add_method_declaration(const std::string& name,
12041 Package* package,
12042 Function_type* type,
12043 Location location)
12045 Named_object* no = this->named_object();
12046 if (no->is_unknown())
12047 no->declare_as_type();
12048 Type_declaration* td = no->type_declaration_value();
12049 return td->add_method_declaration(name, package, type, location);
12052 // Add an already created object as a method.
12054 void
12055 Forward_declaration_type::add_existing_method(Named_object* nom)
12057 Named_object* no = this->named_object();
12058 if (no->is_unknown())
12059 no->declare_as_type();
12060 no->type_declaration_value()->add_existing_method(nom);
12063 // Traversal.
12066 Forward_declaration_type::do_traverse(Traverse* traverse)
12068 if (this->is_defined()
12069 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12070 return TRAVERSE_EXIT;
12071 return TRAVERSE_CONTINUE;
12074 // Verify the type.
12076 bool
12077 Forward_declaration_type::do_verify()
12079 if (!this->is_defined() && !this->is_nil_constant_as_type())
12081 this->warn();
12082 return false;
12084 return true;
12087 // Get the backend representation for the type.
12089 Btype*
12090 Forward_declaration_type::do_get_backend(Gogo* gogo)
12092 if (this->is_defined())
12093 return Type::get_named_base_btype(gogo, this->real_type());
12095 if (this->warned_)
12096 return gogo->backend()->error_type();
12098 // We represent an undefined type as a struct with no fields. That
12099 // should work fine for the backend, since the same case can arise
12100 // in C.
12101 std::vector<Backend::Btyped_identifier> fields;
12102 Btype* bt = gogo->backend()->struct_type(fields);
12103 return gogo->backend()->named_type(this->name(), bt,
12104 this->named_object()->location());
12107 // Build a type descriptor for a forwarded type.
12109 Expression*
12110 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12112 Location ploc = Linemap::predeclared_location();
12113 if (!this->is_defined())
12114 return Expression::make_error(ploc);
12115 else
12117 Type* t = this->real_type();
12118 if (name != NULL)
12119 return this->named_type_descriptor(gogo, t, name);
12120 else
12121 return Expression::make_error(this->named_object_->location());
12125 // The reflection string.
12127 void
12128 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12130 this->append_reflection(this->real_type(), gogo, ret);
12133 // Export a forward declaration. This can happen when a defined type
12134 // refers to a type which is only declared (and is presumably defined
12135 // in some other file in the same package).
12137 void
12138 Forward_declaration_type::do_export(Export*) const
12140 // If there is a base type, that should be exported instead of this.
12141 go_assert(!this->is_defined());
12143 // We don't output anything.
12146 // Make a forward declaration.
12148 Type*
12149 Type::make_forward_declaration(Named_object* named_object)
12151 return new Forward_declaration_type(named_object);
12154 // Class Typed_identifier_list.
12156 // Sort the entries by name.
12158 struct Typed_identifier_list_sort
12160 public:
12161 bool
12162 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12164 return (Gogo::unpack_hidden_name(t1.name())
12165 < Gogo::unpack_hidden_name(t2.name()));
12169 void
12170 Typed_identifier_list::sort_by_name()
12172 std::sort(this->entries_.begin(), this->entries_.end(),
12173 Typed_identifier_list_sort());
12176 // Traverse types.
12179 Typed_identifier_list::traverse(Traverse* traverse)
12181 for (Typed_identifier_list::const_iterator p = this->begin();
12182 p != this->end();
12183 ++p)
12185 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12186 return TRAVERSE_EXIT;
12188 return TRAVERSE_CONTINUE;
12191 // Copy the list.
12193 Typed_identifier_list*
12194 Typed_identifier_list::copy() const
12196 Typed_identifier_list* ret = new Typed_identifier_list();
12197 for (Typed_identifier_list::const_iterator p = this->begin();
12198 p != this->end();
12199 ++p)
12200 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12201 return ret;