compiler: track //go:nointerface in export data
[official-gcc.git] / gcc / go / gofrontend / types.cc
blob40eccfcadcaf8b70a7b04abf55d7adf1a6c4faf9
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->named_type() != NULL)
601 return t1->named_type()->named_type_is_comparable(reason);
602 else if (t2->named_type() != NULL)
603 return t2->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 // The types are assignable if they have identical underlying types
682 // and either LHS or RHS is not a named type.
683 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
684 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
685 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
686 return true;
688 // The types are assignable if LHS is an interface type and RHS
689 // implements the required methods.
690 const Interface_type* lhs_interface_type = lhs->interface_type();
691 if (lhs_interface_type != NULL)
693 if (lhs_interface_type->implements_interface(rhs, reason))
694 return true;
695 const Interface_type* rhs_interface_type = rhs->interface_type();
696 if (rhs_interface_type != NULL
697 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
698 reason))
699 return true;
702 // The type are assignable if RHS is a bidirectional channel type,
703 // LHS is a channel type, they have identical element types, and
704 // either LHS or RHS is not a named type.
705 if (lhs->channel_type() != NULL
706 && rhs->channel_type() != NULL
707 && rhs->channel_type()->may_send()
708 && rhs->channel_type()->may_receive()
709 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
710 && Type::are_identical(lhs->channel_type()->element_type(),
711 rhs->channel_type()->element_type(),
712 true,
713 reason))
714 return true;
716 // The nil type may be assigned to a pointer, function, slice, map,
717 // channel, or interface type.
718 if (rhs->is_nil_type()
719 && (lhs->points_to() != NULL
720 || lhs->function_type() != NULL
721 || lhs->is_slice_type()
722 || lhs->map_type() != NULL
723 || lhs->channel_type() != NULL
724 || lhs->interface_type() != NULL))
725 return true;
727 // An untyped numeric constant may be assigned to a numeric type if
728 // it is representable in that type.
729 if ((rhs->is_abstract()
730 && (rhs->integer_type() != NULL
731 || rhs->float_type() != NULL
732 || rhs->complex_type() != NULL))
733 && (lhs->integer_type() != NULL
734 || lhs->float_type() != NULL
735 || lhs->complex_type() != NULL))
736 return true;
738 // Give some better error messages.
739 if (reason != NULL && reason->empty())
741 if (rhs->interface_type() != NULL)
742 reason->assign(_("need explicit conversion"));
743 else if (lhs->named_type() != NULL && rhs->named_type() != NULL)
745 size_t len = (lhs->named_type()->name().length()
746 + rhs->named_type()->name().length()
747 + 100);
748 char* buf = new char[len];
749 snprintf(buf, len, _("cannot use type %s as type %s"),
750 rhs->named_type()->message_name().c_str(),
751 lhs->named_type()->message_name().c_str());
752 reason->assign(buf);
753 delete[] buf;
757 return false;
760 // Return true if a value with type RHS may be converted to type LHS.
761 // If REASON is not NULL, set *REASON to the reason the types are not
762 // convertible.
764 bool
765 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
767 // The types are convertible if they are assignable.
768 if (Type::are_assignable(lhs, rhs, reason))
769 return true;
771 // A pointer to a regular type may not be converted to a pointer to
772 // a type that may not live in the heap, except when converting from
773 // unsafe.Pointer.
774 if (lhs->points_to() != NULL
775 && rhs->points_to() != NULL
776 && !lhs->points_to()->in_heap()
777 && rhs->points_to()->in_heap()
778 && !rhs->is_unsafe_pointer_type())
780 if (reason != NULL)
781 reason->assign(_("conversion from normal type to notinheap type"));
782 return false;
785 // The types are convertible if they have identical underlying
786 // types, ignoring struct field tags.
787 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
788 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
789 true, reason))
790 return true;
792 // The types are convertible if they are both unnamed pointer types
793 // and their pointer base types have identical underlying types,
794 // ignoring struct field tags.
795 if (lhs->named_type() == NULL
796 && rhs->named_type() == NULL
797 && lhs->points_to() != NULL
798 && rhs->points_to() != NULL
799 && (lhs->points_to()->named_type() != NULL
800 || rhs->points_to()->named_type() != NULL)
801 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
802 rhs->points_to()->base(),
803 IGNORE_TAGS,
804 true,
805 reason))
806 return true;
808 // Integer and floating point types are convertible to each other.
809 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
810 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
811 return true;
813 // Complex types are convertible to each other.
814 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
815 return true;
817 // An integer, or []byte, or []rune, may be converted to a string.
818 if (lhs->is_string_type())
820 if (rhs->integer_type() != NULL)
821 return true;
822 if (rhs->is_slice_type())
824 const Type* e = rhs->array_type()->element_type()->forwarded();
825 if (e->integer_type() != NULL
826 && (e->integer_type()->is_byte()
827 || e->integer_type()->is_rune()))
828 return true;
832 // A string may be converted to []byte or []rune.
833 if (rhs->is_string_type() && lhs->is_slice_type())
835 const Type* e = lhs->array_type()->element_type()->forwarded();
836 if (e->integer_type() != NULL
837 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
838 return true;
841 // An unsafe.Pointer type may be converted to any pointer type or to
842 // a type whose underlying type is uintptr, and vice-versa.
843 if (lhs->is_unsafe_pointer_type()
844 && (rhs->points_to() != NULL
845 || (rhs->integer_type() != NULL
846 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
847 return true;
848 if (rhs->is_unsafe_pointer_type()
849 && (lhs->points_to() != NULL
850 || (lhs->integer_type() != NULL
851 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
852 return true;
854 // Give a better error message.
855 if (reason != NULL)
857 if (reason->empty())
858 *reason = "invalid type conversion";
859 else
861 std::string s = "invalid type conversion (";
862 s += *reason;
863 s += ')';
864 *reason = s;
868 return false;
871 // Copy expressions if it may change the size.
873 // The only type that has an expression is an array type. The only
874 // types whose size can be changed by the size of an array type are an
875 // array type itself, or a struct type with an array field.
876 Type*
877 Type::copy_expressions()
879 // This is run during parsing, so types may not be valid yet.
880 // We only have to worry about array type literals.
881 switch (this->classification_)
883 default:
884 return this;
886 case TYPE_ARRAY:
888 Array_type* at = this->array_type();
889 if (at->length() == NULL)
890 return this;
891 Expression* len = at->length()->copy();
892 if (at->length() == len)
893 return this;
894 return Type::make_array_type(at->element_type(), len);
897 case TYPE_STRUCT:
899 Struct_type* st = this->struct_type();
900 const Struct_field_list* sfl = st->fields();
901 if (sfl == NULL)
902 return this;
903 bool changed = false;
904 Struct_field_list *nsfl = new Struct_field_list();
905 for (Struct_field_list::const_iterator pf = sfl->begin();
906 pf != sfl->end();
907 ++pf)
909 Type* ft = pf->type()->copy_expressions();
910 Struct_field nf(Typed_identifier((pf->is_anonymous()
911 ? ""
912 : pf->field_name()),
914 pf->location()));
915 if (pf->has_tag())
916 nf.set_tag(pf->tag());
917 nsfl->push_back(nf);
918 if (ft != pf->type())
919 changed = true;
921 if (!changed)
923 delete(nsfl);
924 return this;
926 return Type::make_struct_type(nsfl, st->location());
930 go_unreachable();
933 // Return a hash code for the type to be used for method lookup.
935 unsigned int
936 Type::hash_for_method(Gogo* gogo) const
938 if (this->named_type() != NULL && this->named_type()->is_alias())
939 return this->named_type()->real_type()->hash_for_method(gogo);
940 unsigned int ret = 0;
941 if (this->classification_ != TYPE_FORWARD)
942 ret += this->classification_;
943 return ret + this->do_hash_for_method(gogo);
946 // Default implementation of do_hash_for_method. This is appropriate
947 // for types with no subfields.
949 unsigned int
950 Type::do_hash_for_method(Gogo*) const
952 return 0;
955 // Return a hash code for a string, given a starting hash.
957 unsigned int
958 Type::hash_string(const std::string& s, unsigned int h)
960 const char* p = s.data();
961 size_t len = s.length();
962 for (; len > 0; --len)
964 h ^= *p++;
965 h*= 16777619;
967 return h;
970 // A hash table mapping unnamed types to the backend representation of
971 // those types.
973 Type::Type_btypes Type::type_btypes;
975 // Return the backend representation for this type.
977 Btype*
978 Type::get_backend(Gogo* gogo)
980 if (this->btype_ != NULL)
981 return this->btype_;
983 if (this->forward_declaration_type() != NULL
984 || this->named_type() != NULL)
985 return this->get_btype_without_hash(gogo);
987 if (this->is_error_type())
988 return gogo->backend()->error_type();
990 // To avoid confusing the backend, translate all identical Go types
991 // to the same backend representation. We use a hash table to do
992 // that. There is no need to use the hash table for named types, as
993 // named types are only identical to themselves.
995 std::pair<Type*, Type_btype_entry> val;
996 val.first = this;
997 val.second.btype = NULL;
998 val.second.is_placeholder = false;
999 std::pair<Type_btypes::iterator, bool> ins =
1000 Type::type_btypes.insert(val);
1001 if (!ins.second && ins.first->second.btype != NULL)
1003 // Note that GOGO can be NULL here, but only when the GCC
1004 // middle-end is asking for a frontend type. That will only
1005 // happen for simple types, which should never require
1006 // placeholders.
1007 if (!ins.first->second.is_placeholder)
1008 this->btype_ = ins.first->second.btype;
1009 else if (gogo->named_types_are_converted())
1011 this->finish_backend(gogo, ins.first->second.btype);
1012 ins.first->second.is_placeholder = false;
1015 return ins.first->second.btype;
1018 Btype* bt = this->get_btype_without_hash(gogo);
1020 if (ins.first->second.btype == NULL)
1022 ins.first->second.btype = bt;
1023 ins.first->second.is_placeholder = false;
1025 else
1027 // We have already created a backend representation for this
1028 // type. This can happen when an unnamed type is defined using
1029 // a named type which in turns uses an identical unnamed type.
1030 // Use the representation we created earlier and ignore the one we just
1031 // built.
1032 if (this->btype_ == bt)
1033 this->btype_ = ins.first->second.btype;
1034 bt = ins.first->second.btype;
1037 return bt;
1040 // Return the backend representation for a type without looking in the
1041 // hash table for identical types. This is used for named types,
1042 // since a named type is never identical to any other type.
1044 Btype*
1045 Type::get_btype_without_hash(Gogo* gogo)
1047 if (this->btype_ == NULL)
1049 Btype* bt = this->do_get_backend(gogo);
1051 // For a recursive function or pointer type, we will temporarily
1052 // return a circular pointer type during the recursion. We
1053 // don't want to record that for a forwarding type, as it may
1054 // confuse us later.
1055 if (this->forward_declaration_type() != NULL
1056 && gogo->backend()->is_circular_pointer_type(bt))
1057 return bt;
1059 if (gogo == NULL || !gogo->named_types_are_converted())
1060 return bt;
1062 this->btype_ = bt;
1064 return this->btype_;
1067 // Get the backend representation of a type without forcing the
1068 // creation of the backend representation of all supporting types.
1069 // This will return a backend type that has the correct size but may
1070 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1071 // and will not contain the final representation of the type to which
1072 // it points. This is used while converting all named types to the
1073 // backend representation, to avoid problems with indirect references
1074 // to types which are not yet complete. When this is called, the
1075 // sizes of all direct references (e.g., a struct field) should be
1076 // known, but the sizes of indirect references (e.g., the type to
1077 // which a pointer points) may not.
1079 Btype*
1080 Type::get_backend_placeholder(Gogo* gogo)
1082 if (gogo->named_types_are_converted())
1083 return this->get_backend(gogo);
1084 if (this->btype_ != NULL)
1085 return this->btype_;
1087 Btype* bt;
1088 switch (this->classification_)
1090 case TYPE_ERROR:
1091 case TYPE_VOID:
1092 case TYPE_BOOLEAN:
1093 case TYPE_INTEGER:
1094 case TYPE_FLOAT:
1095 case TYPE_COMPLEX:
1096 case TYPE_STRING:
1097 case TYPE_NIL:
1098 // These are simple types that can just be created directly.
1099 return this->get_backend(gogo);
1101 case TYPE_MAP:
1102 case TYPE_CHANNEL:
1103 // All maps and channels have the same backend representation.
1104 return this->get_backend(gogo);
1106 case TYPE_NAMED:
1107 case TYPE_FORWARD:
1108 // Named types keep track of their own dependencies and manage
1109 // their own placeholders.
1110 return this->get_backend(gogo);
1112 case TYPE_INTERFACE:
1113 if (this->interface_type()->is_empty())
1114 return Interface_type::get_backend_empty_interface_type(gogo);
1115 break;
1117 default:
1118 break;
1121 std::pair<Type*, Type_btype_entry> val;
1122 val.first = this;
1123 val.second.btype = NULL;
1124 val.second.is_placeholder = false;
1125 std::pair<Type_btypes::iterator, bool> ins =
1126 Type::type_btypes.insert(val);
1127 if (!ins.second && ins.first->second.btype != NULL)
1128 return ins.first->second.btype;
1130 switch (this->classification_)
1132 case TYPE_FUNCTION:
1134 // A Go function type is a pointer to a struct type.
1135 Location loc = this->function_type()->location();
1136 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1138 break;
1140 case TYPE_POINTER:
1142 Location loc = Linemap::unknown_location();
1143 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1144 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1145 Type::placeholder_pointers.push_back(pt);
1147 break;
1149 case TYPE_STRUCT:
1150 // We don't have to make the struct itself be a placeholder. We
1151 // are promised that we know the sizes of the struct fields.
1152 // But we may have to use a placeholder for any particular
1153 // struct field.
1155 std::vector<Backend::Btyped_identifier> bfields;
1156 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1157 true, &bfields);
1158 bt = gogo->backend()->struct_type(bfields);
1160 break;
1162 case TYPE_ARRAY:
1163 if (this->is_slice_type())
1165 std::vector<Backend::Btyped_identifier> bfields;
1166 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1167 bt = gogo->backend()->struct_type(bfields);
1169 else
1171 Btype* element = this->array_type()->get_backend_element(gogo, true);
1172 Bexpression* len = this->array_type()->get_backend_length(gogo);
1173 bt = gogo->backend()->array_type(element, len);
1175 break;
1177 case TYPE_INTERFACE:
1179 go_assert(!this->interface_type()->is_empty());
1180 std::vector<Backend::Btyped_identifier> bfields;
1181 get_backend_interface_fields(gogo, this->interface_type(), true,
1182 &bfields);
1183 bt = gogo->backend()->struct_type(bfields);
1185 break;
1187 case TYPE_SINK:
1188 case TYPE_CALL_MULTIPLE_RESULT:
1189 /* Note that various classifications were handled in the earlier
1190 switch. */
1191 default:
1192 go_unreachable();
1195 if (ins.first->second.btype == NULL)
1197 ins.first->second.btype = bt;
1198 ins.first->second.is_placeholder = true;
1200 else
1202 // A placeholder for this type got created along the way. Use
1203 // that one and ignore the one we just built.
1204 bt = ins.first->second.btype;
1207 return bt;
1210 // Complete the backend representation. This is called for a type
1211 // using a placeholder type.
1213 void
1214 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1216 switch (this->classification_)
1218 case TYPE_ERROR:
1219 case TYPE_VOID:
1220 case TYPE_BOOLEAN:
1221 case TYPE_INTEGER:
1222 case TYPE_FLOAT:
1223 case TYPE_COMPLEX:
1224 case TYPE_STRING:
1225 case TYPE_NIL:
1226 go_unreachable();
1228 case TYPE_FUNCTION:
1230 Btype* bt = this->do_get_backend(gogo);
1231 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1232 go_assert(saw_errors());
1234 break;
1236 case TYPE_POINTER:
1238 Btype* bt = this->do_get_backend(gogo);
1239 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1240 go_assert(saw_errors());
1242 break;
1244 case TYPE_STRUCT:
1245 // The struct type itself is done, but we have to make sure that
1246 // all the field types are converted.
1247 this->struct_type()->finish_backend_fields(gogo);
1248 break;
1250 case TYPE_ARRAY:
1251 // The array type itself is done, but make sure the element type
1252 // is converted.
1253 this->array_type()->finish_backend_element(gogo);
1254 break;
1256 case TYPE_MAP:
1257 case TYPE_CHANNEL:
1258 go_unreachable();
1260 case TYPE_INTERFACE:
1261 // The interface type itself is done, but make sure the method
1262 // types are converted.
1263 this->interface_type()->finish_backend_methods(gogo);
1264 break;
1266 case TYPE_NAMED:
1267 case TYPE_FORWARD:
1268 go_unreachable();
1270 case TYPE_SINK:
1271 case TYPE_CALL_MULTIPLE_RESULT:
1272 default:
1273 go_unreachable();
1276 this->btype_ = placeholder;
1279 // Return a pointer to the type descriptor for this type.
1281 Bexpression*
1282 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1284 Type* t = this->unalias();
1285 if (t->type_descriptor_var_ == NULL)
1287 t->make_type_descriptor_var(gogo);
1288 go_assert(t->type_descriptor_var_ != NULL);
1290 Bexpression* var_expr =
1291 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1292 Bexpression* var_addr =
1293 gogo->backend()->address_expression(var_expr, location);
1294 Type* td_type = Type::make_type_descriptor_type();
1295 Btype* td_btype = td_type->get_backend(gogo);
1296 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1297 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1300 // A mapping from unnamed types to type descriptor variables.
1302 Type::Type_descriptor_vars Type::type_descriptor_vars;
1304 // Build the type descriptor for this type.
1306 void
1307 Type::make_type_descriptor_var(Gogo* gogo)
1309 go_assert(this->type_descriptor_var_ == NULL);
1311 Named_type* nt = this->named_type();
1313 // We can have multiple instances of unnamed types, but we only want
1314 // to emit the type descriptor once. We use a hash table. This is
1315 // not necessary for named types, as they are unique, and we store
1316 // the type descriptor in the type itself.
1317 Bvariable** phash = NULL;
1318 if (nt == NULL)
1320 Bvariable* bvnull = NULL;
1321 std::pair<Type_descriptor_vars::iterator, bool> ins =
1322 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1323 if (!ins.second)
1325 // We've already built a type descriptor for this type.
1326 this->type_descriptor_var_ = ins.first->second;
1327 return;
1329 phash = &ins.first->second;
1332 // The type descriptor symbol for the unsafe.Pointer type is defined in
1333 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1334 // symbol if necessary.
1335 if (this->is_unsafe_pointer_type())
1337 Location bloc = Linemap::predeclared_location();
1339 Type* td_type = Type::make_type_descriptor_type();
1340 Btype* td_btype = td_type->get_backend(gogo);
1341 std::string name = gogo->type_descriptor_name(this, nt);
1342 std::string asm_name(go_selectively_encode_id(name));
1343 this->type_descriptor_var_ =
1344 gogo->backend()->immutable_struct_reference(name, asm_name,
1345 td_btype,
1346 bloc);
1348 if (phash != NULL)
1349 *phash = this->type_descriptor_var_;
1350 return;
1353 std::string var_name = gogo->type_descriptor_name(this, nt);
1355 // Build the contents of the type descriptor.
1356 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1358 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1360 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1362 const Package* dummy;
1363 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1365 std::string asm_name(go_selectively_encode_id(var_name));
1366 this->type_descriptor_var_ =
1367 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1368 initializer_btype,
1369 loc);
1370 if (phash != NULL)
1371 *phash = this->type_descriptor_var_;
1372 return;
1375 // See if this type descriptor can appear in multiple packages.
1376 bool is_common = false;
1377 if (nt != NULL)
1379 // We create the descriptor for a builtin type whenever we need
1380 // it.
1381 is_common = nt->is_builtin();
1383 else
1385 // This is an unnamed type. The descriptor could be defined in
1386 // any package where it is needed, and the linker will pick one
1387 // descriptor to keep.
1388 is_common = true;
1391 // We are going to build the type descriptor in this package. We
1392 // must create the variable before we convert the initializer to the
1393 // backend representation, because the initializer may refer to the
1394 // type descriptor of this type. By setting type_descriptor_var_ we
1395 // ensure that type_descriptor_pointer will work if called while
1396 // converting INITIALIZER.
1398 std::string asm_name(go_selectively_encode_id(var_name));
1399 this->type_descriptor_var_ =
1400 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1401 initializer_btype, loc);
1402 if (phash != NULL)
1403 *phash = this->type_descriptor_var_;
1405 Translate_context context(gogo, NULL, NULL, NULL);
1406 context.set_is_const();
1407 Bexpression* binitializer = initializer->get_backend(&context);
1409 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1410 var_name, false, is_common,
1411 initializer_btype, loc,
1412 binitializer);
1415 // Return true if this type descriptor is defined in a different
1416 // package. If this returns true it sets *PACKAGE to the package.
1418 bool
1419 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1420 const Package** package)
1422 if (nt != NULL)
1424 if (nt->named_object()->package() != NULL)
1426 // This is a named type defined in a different package. The
1427 // type descriptor should be defined in that package.
1428 *package = nt->named_object()->package();
1429 return true;
1432 else
1434 if (this->points_to() != NULL
1435 && this->points_to()->named_type() != NULL
1436 && this->points_to()->named_type()->named_object()->package() != NULL)
1438 // This is an unnamed pointer to a named type defined in a
1439 // different package. The descriptor should be defined in
1440 // that package.
1441 *package = this->points_to()->named_type()->named_object()->package();
1442 return true;
1445 return false;
1448 // Return a composite literal for a type descriptor.
1450 Expression*
1451 Type::type_descriptor(Gogo* gogo, Type* type)
1453 return type->do_type_descriptor(gogo, NULL);
1456 // Return a composite literal for a type descriptor with a name.
1458 Expression*
1459 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1461 go_assert(name != NULL && type->named_type() != name);
1462 return type->do_type_descriptor(gogo, name);
1465 // Make a builtin struct type from a list of fields. The fields are
1466 // pairs of a name and a type.
1468 Struct_type*
1469 Type::make_builtin_struct_type(int nfields, ...)
1471 va_list ap;
1472 va_start(ap, nfields);
1474 Location bloc = Linemap::predeclared_location();
1475 Struct_field_list* sfl = new Struct_field_list();
1476 for (int i = 0; i < nfields; i++)
1478 const char* field_name = va_arg(ap, const char *);
1479 Type* type = va_arg(ap, Type*);
1480 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1483 va_end(ap);
1485 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1486 ret->set_is_struct_incomparable();
1487 return ret;
1490 // A list of builtin named types.
1492 std::vector<Named_type*> Type::named_builtin_types;
1494 // Make a builtin named type.
1496 Named_type*
1497 Type::make_builtin_named_type(const char* name, Type* type)
1499 Location bloc = Linemap::predeclared_location();
1500 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1501 Named_type* ret = no->type_value();
1502 Type::named_builtin_types.push_back(ret);
1503 return ret;
1506 // Convert the named builtin types.
1508 void
1509 Type::convert_builtin_named_types(Gogo* gogo)
1511 for (std::vector<Named_type*>::const_iterator p =
1512 Type::named_builtin_types.begin();
1513 p != Type::named_builtin_types.end();
1514 ++p)
1516 bool r = (*p)->verify();
1517 go_assert(r);
1518 (*p)->convert(gogo);
1522 // Return the type of a type descriptor. We should really tie this to
1523 // runtime.Type rather than copying it. This must match the struct "_type"
1524 // declared in libgo/go/runtime/type.go.
1526 Type*
1527 Type::make_type_descriptor_type()
1529 static Type* ret;
1530 if (ret == NULL)
1532 Location bloc = Linemap::predeclared_location();
1534 Type* uint8_type = Type::lookup_integer_type("uint8");
1535 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1536 Type* uint32_type = Type::lookup_integer_type("uint32");
1537 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1538 Type* string_type = Type::lookup_string_type();
1539 Type* pointer_string_type = Type::make_pointer_type(string_type);
1541 // This is an unnamed version of unsafe.Pointer. Perhaps we
1542 // should use the named version instead, although that would
1543 // require us to create the unsafe package if it has not been
1544 // imported. It probably doesn't matter.
1545 Type* void_type = Type::make_void_type();
1546 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1548 Typed_identifier_list *params = new Typed_identifier_list();
1549 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1550 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1552 Typed_identifier_list* results = new Typed_identifier_list();
1553 results->push_back(Typed_identifier("", uintptr_type, bloc));
1555 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1556 bloc);
1558 params = new Typed_identifier_list();
1559 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1560 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1562 results = new Typed_identifier_list();
1563 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1565 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1566 bloc);
1568 // Forward declaration for the type descriptor type.
1569 Named_object* named_type_descriptor_type =
1570 Named_object::make_type_declaration("_type", NULL, bloc);
1571 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1572 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1574 // The type of a method on a concrete type.
1575 Struct_type* method_type =
1576 Type::make_builtin_struct_type(5,
1577 "name", pointer_string_type,
1578 "pkgPath", pointer_string_type,
1579 "mtyp", pointer_type_descriptor_type,
1580 "typ", pointer_type_descriptor_type,
1581 "tfn", unsafe_pointer_type);
1582 Named_type* named_method_type =
1583 Type::make_builtin_named_type("method", method_type);
1585 // Information for types with a name or methods.
1586 Type* slice_named_method_type =
1587 Type::make_array_type(named_method_type, NULL);
1588 Struct_type* uncommon_type =
1589 Type::make_builtin_struct_type(3,
1590 "name", pointer_string_type,
1591 "pkgPath", pointer_string_type,
1592 "methods", slice_named_method_type);
1593 Named_type* named_uncommon_type =
1594 Type::make_builtin_named_type("uncommonType", uncommon_type);
1596 Type* pointer_uncommon_type =
1597 Type::make_pointer_type(named_uncommon_type);
1599 // The type descriptor type.
1601 Struct_type* type_descriptor_type =
1602 Type::make_builtin_struct_type(12,
1603 "size", uintptr_type,
1604 "ptrdata", uintptr_type,
1605 "hash", uint32_type,
1606 "kind", uint8_type,
1607 "align", uint8_type,
1608 "fieldAlign", uint8_type,
1609 "hashfn", hash_fntype,
1610 "equalfn", equal_fntype,
1611 "gcdata", pointer_uint8_type,
1612 "string", pointer_string_type,
1613 "", pointer_uncommon_type,
1614 "ptrToThis",
1615 pointer_type_descriptor_type);
1617 Named_type* named = Type::make_builtin_named_type("_type",
1618 type_descriptor_type);
1620 named_type_descriptor_type->set_type_value(named);
1622 ret = named;
1625 return ret;
1628 // Make the type of a pointer to a type descriptor as represented in
1629 // Go.
1631 Type*
1632 Type::make_type_descriptor_ptr_type()
1634 static Type* ret;
1635 if (ret == NULL)
1636 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1637 return ret;
1640 // Return the alignment required by the memequalN function. N is a
1641 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1642 // in libgo/go/runtime/alg.go.
1644 int64_t
1645 Type::memequal_align(Gogo* gogo, int size)
1647 const char* tn;
1648 switch (size)
1650 case 16:
1651 tn = "int16";
1652 break;
1653 case 32:
1654 tn = "int32";
1655 break;
1656 case 64:
1657 tn = "int64";
1658 break;
1659 case 128:
1660 // The code uses [2]int64, which must have the same alignment as
1661 // int64.
1662 tn = "int64";
1663 break;
1664 default:
1665 go_unreachable();
1668 Type* t = Type::lookup_integer_type(tn);
1670 int64_t ret;
1671 if (!t->backend_type_align(gogo, &ret))
1672 go_unreachable();
1673 return ret;
1676 // Return whether this type needs specially built type functions.
1677 // This returns true for types that are comparable and either can not
1678 // use an identity comparison, or are a non-standard size.
1680 bool
1681 Type::needs_specific_type_functions(Gogo* gogo)
1683 Named_type* nt = this->named_type();
1684 if (nt != NULL && nt->is_alias())
1685 return false;
1686 if (!this->is_comparable())
1687 return false;
1688 if (!this->compare_is_identity(gogo))
1689 return true;
1691 // We create a few predeclared types for type descriptors; they are
1692 // really just for the backend and don't need hash or equality
1693 // functions.
1694 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1695 return false;
1697 int64_t size, align;
1698 if (!this->backend_type_size(gogo, &size)
1699 || !this->backend_type_align(gogo, &align))
1701 go_assert(saw_errors());
1702 return false;
1704 // This switch matches the one in Type::type_functions.
1705 switch (size)
1707 case 0:
1708 case 1:
1709 case 2:
1710 return align < Type::memequal_align(gogo, 16);
1711 case 4:
1712 return align < Type::memequal_align(gogo, 32);
1713 case 8:
1714 return align < Type::memequal_align(gogo, 64);
1715 case 16:
1716 return align < Type::memequal_align(gogo, 128);
1717 default:
1718 return true;
1722 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1723 // hash code for this type and which compare whether two values of
1724 // this type are equal. If NAME is not NULL it is the name of this
1725 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1726 // functions, for convenience; they may be NULL.
1728 void
1729 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1730 Function_type* equal_fntype, Named_object** hash_fn,
1731 Named_object** equal_fn)
1733 // If the unaliased type is not a named type, then the type does not
1734 // have a name after all.
1735 if (name != NULL)
1736 name = name->unalias()->named_type();
1738 if (!this->is_comparable())
1740 *hash_fn = NULL;
1741 *equal_fn = NULL;
1742 return;
1745 if (hash_fntype == NULL || equal_fntype == NULL)
1747 Location bloc = Linemap::predeclared_location();
1749 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1750 Type* void_type = Type::make_void_type();
1751 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1753 if (hash_fntype == NULL)
1755 Typed_identifier_list* params = new Typed_identifier_list();
1756 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1757 bloc));
1758 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1760 Typed_identifier_list* results = new Typed_identifier_list();
1761 results->push_back(Typed_identifier("", uintptr_type, bloc));
1763 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1765 if (equal_fntype == NULL)
1767 Typed_identifier_list* params = new Typed_identifier_list();
1768 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1769 bloc));
1770 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1771 bloc));
1773 Typed_identifier_list* results = new Typed_identifier_list();
1774 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1775 bloc));
1777 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1781 const char* hash_fnname;
1782 const char* equal_fnname;
1783 if (this->compare_is_identity(gogo))
1785 int64_t size, align;
1786 if (!this->backend_type_size(gogo, &size)
1787 || !this->backend_type_align(gogo, &align))
1789 go_assert(saw_errors());
1790 return;
1792 bool build_functions = false;
1793 // This switch matches the one in Type::needs_specific_type_functions.
1794 // The alignment tests are because of the memequal functions,
1795 // which assume that the values are aligned as required for an
1796 // integer of that size.
1797 switch (size)
1799 case 0:
1800 hash_fnname = "runtime.memhash0";
1801 equal_fnname = "runtime.memequal0";
1802 break;
1803 case 1:
1804 hash_fnname = "runtime.memhash8";
1805 equal_fnname = "runtime.memequal8";
1806 break;
1807 case 2:
1808 if (align < Type::memequal_align(gogo, 16))
1809 build_functions = true;
1810 else
1812 hash_fnname = "runtime.memhash16";
1813 equal_fnname = "runtime.memequal16";
1815 break;
1816 case 4:
1817 if (align < Type::memequal_align(gogo, 32))
1818 build_functions = true;
1819 else
1821 hash_fnname = "runtime.memhash32";
1822 equal_fnname = "runtime.memequal32";
1824 break;
1825 case 8:
1826 if (align < Type::memequal_align(gogo, 64))
1827 build_functions = true;
1828 else
1830 hash_fnname = "runtime.memhash64";
1831 equal_fnname = "runtime.memequal64";
1833 break;
1834 case 16:
1835 if (align < Type::memequal_align(gogo, 128))
1836 build_functions = true;
1837 else
1839 hash_fnname = "runtime.memhash128";
1840 equal_fnname = "runtime.memequal128";
1842 break;
1843 default:
1844 build_functions = true;
1845 break;
1847 if (build_functions)
1849 // We don't have a built-in function for a type of this size
1850 // and alignment. Build a function to use that calls the
1851 // generic hash/equality functions for identity, passing the size.
1852 this->specific_type_functions(gogo, name, size, hash_fntype,
1853 equal_fntype, hash_fn, equal_fn);
1854 return;
1857 else
1859 switch (this->base()->classification())
1861 case Type::TYPE_ERROR:
1862 case Type::TYPE_VOID:
1863 case Type::TYPE_NIL:
1864 case Type::TYPE_FUNCTION:
1865 case Type::TYPE_MAP:
1866 // For these types is_comparable should have returned false.
1867 go_unreachable();
1869 case Type::TYPE_BOOLEAN:
1870 case Type::TYPE_INTEGER:
1871 case Type::TYPE_POINTER:
1872 case Type::TYPE_CHANNEL:
1873 // For these types compare_is_identity should have returned true.
1874 go_unreachable();
1876 case Type::TYPE_FLOAT:
1877 switch (this->float_type()->bits())
1879 case 32:
1880 hash_fnname = "runtime.f32hash";
1881 equal_fnname = "runtime.f32equal";
1882 break;
1883 case 64:
1884 hash_fnname = "runtime.f64hash";
1885 equal_fnname = "runtime.f64equal";
1886 break;
1887 default:
1888 go_unreachable();
1890 break;
1892 case Type::TYPE_COMPLEX:
1893 switch (this->complex_type()->bits())
1895 case 64:
1896 hash_fnname = "runtime.c64hash";
1897 equal_fnname = "runtime.c64equal";
1898 break;
1899 case 128:
1900 hash_fnname = "runtime.c128hash";
1901 equal_fnname = "runtime.c128equal";
1902 break;
1903 default:
1904 go_unreachable();
1906 break;
1908 case Type::TYPE_STRING:
1909 hash_fnname = "runtime.strhash";
1910 equal_fnname = "runtime.strequal";
1911 break;
1913 case Type::TYPE_STRUCT:
1915 // This is a struct which can not be compared using a
1916 // simple identity function. We need to build a function
1917 // for comparison.
1918 this->specific_type_functions(gogo, name, -1, hash_fntype,
1919 equal_fntype, hash_fn, equal_fn);
1920 return;
1923 case Type::TYPE_ARRAY:
1924 if (this->is_slice_type())
1926 // Type::is_compatible_for_comparison should have
1927 // returned false.
1928 go_unreachable();
1930 else
1932 // This is an array which can not be compared using a
1933 // simple identity function. We need to build a
1934 // function for comparison.
1935 this->specific_type_functions(gogo, name, -1, hash_fntype,
1936 equal_fntype, hash_fn, equal_fn);
1937 return;
1939 break;
1941 case Type::TYPE_INTERFACE:
1942 if (this->interface_type()->is_empty())
1944 hash_fnname = "runtime.nilinterhash";
1945 equal_fnname = "runtime.nilinterequal";
1947 else
1949 hash_fnname = "runtime.interhash";
1950 equal_fnname = "runtime.interequal";
1952 break;
1954 case Type::TYPE_NAMED:
1955 case Type::TYPE_FORWARD:
1956 go_unreachable();
1958 default:
1959 go_unreachable();
1964 Location bloc = Linemap::predeclared_location();
1965 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1966 hash_fntype, bloc);
1967 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1968 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1969 equal_fntype, bloc);
1970 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1973 // A hash table mapping types to the specific hash functions.
1975 Type::Type_functions Type::type_functions_table;
1977 // Handle a type function which is specific to a type: if SIZE == -1,
1978 // this is a struct or array that can not use an identity comparison.
1979 // Otherwise, it is a type that uses an identity comparison but is not
1980 // one of the standard supported sizes.
1982 void
1983 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
1984 Function_type* hash_fntype,
1985 Function_type* equal_fntype,
1986 Named_object** hash_fn,
1987 Named_object** equal_fn)
1989 Hash_equal_fn fnull(NULL, NULL);
1990 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
1991 std::pair<Type_functions::iterator, bool> ins =
1992 Type::type_functions_table.insert(val);
1993 if (!ins.second)
1995 // We already have functions for this type
1996 *hash_fn = ins.first->second.first;
1997 *equal_fn = ins.first->second.second;
1998 return;
2001 std::string hash_name;
2002 std::string equal_name;
2003 gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
2005 Location bloc = Linemap::predeclared_location();
2007 const Package* package = NULL;
2008 bool is_defined_elsewhere =
2009 this->type_descriptor_defined_elsewhere(name, &package);
2010 if (is_defined_elsewhere)
2012 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2013 hash_fntype, bloc);
2014 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2015 equal_fntype, bloc);
2017 else
2019 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2020 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2021 bloc);
2024 ins.first->second.first = *hash_fn;
2025 ins.first->second.second = *equal_fn;
2027 if (!is_defined_elsewhere)
2029 if (gogo->in_global_scope())
2030 this->write_specific_type_functions(gogo, name, size, hash_name,
2031 hash_fntype, equal_name,
2032 equal_fntype);
2033 else
2034 gogo->queue_specific_type_function(this, name, size, hash_name,
2035 hash_fntype, equal_name,
2036 equal_fntype);
2040 // Write the hash and equality functions for a type which needs to be
2041 // written specially.
2043 void
2044 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2045 const std::string& hash_name,
2046 Function_type* hash_fntype,
2047 const std::string& equal_name,
2048 Function_type* equal_fntype)
2050 Location bloc = Linemap::predeclared_location();
2052 if (gogo->specific_type_functions_are_written())
2054 go_assert(saw_errors());
2055 return;
2058 go_assert(this->is_comparable());
2060 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2061 bloc);
2062 hash_fn->func_value()->set_is_type_specific_function();
2063 gogo->start_block(bloc);
2065 if (size != -1)
2066 this->write_identity_hash(gogo, size);
2067 else if (name != NULL && name->real_type()->named_type() != NULL)
2068 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2069 else if (this->struct_type() != NULL)
2070 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2071 equal_fntype);
2072 else if (this->array_type() != NULL)
2073 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2074 equal_fntype);
2075 else
2076 go_unreachable();
2078 Block* b = gogo->finish_block(bloc);
2079 gogo->add_block(b, bloc);
2080 gogo->lower_block(hash_fn, b);
2081 gogo->finish_function(bloc);
2083 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2084 false, bloc);
2085 equal_fn->func_value()->set_is_type_specific_function();
2086 gogo->start_block(bloc);
2088 if (size != -1)
2089 this->write_identity_equal(gogo, size);
2090 else if (name != NULL && name->real_type()->named_type() != NULL)
2091 this->write_named_equal(gogo, name);
2092 else if (this->struct_type() != NULL)
2093 this->struct_type()->write_equal_function(gogo, name);
2094 else if (this->array_type() != NULL)
2095 this->array_type()->write_equal_function(gogo, name);
2096 else
2097 go_unreachable();
2099 b = gogo->finish_block(bloc);
2100 gogo->add_block(b, bloc);
2101 gogo->lower_block(equal_fn, b);
2102 gogo->finish_function(bloc);
2104 // Build the function descriptors for the type descriptor to refer to.
2105 hash_fn->func_value()->descriptor(gogo, hash_fn);
2106 equal_fn->func_value()->descriptor(gogo, equal_fn);
2109 // Write a hash function for a type that can use an identity hash but
2110 // is not one of the standard supported sizes. For example, this
2111 // would be used for the type [3]byte. This builds a return statement
2112 // that returns a call to the memhash function, passing the key and
2113 // seed from the function arguments (already constructed before this
2114 // is called), and the constant size.
2116 void
2117 Type::write_identity_hash(Gogo* gogo, int64_t size)
2119 Location bloc = Linemap::predeclared_location();
2121 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2122 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2124 Typed_identifier_list* params = new Typed_identifier_list();
2125 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2126 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2127 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2129 Typed_identifier_list* results = new Typed_identifier_list();
2130 results->push_back(Typed_identifier("", uintptr_type, bloc));
2132 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2133 results, bloc);
2135 Named_object* memhash =
2136 Named_object::make_function_declaration("runtime.memhash", NULL,
2137 memhash_fntype, bloc);
2138 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2140 Named_object* key_arg = gogo->lookup("key", NULL);
2141 go_assert(key_arg != NULL);
2142 Named_object* seed_arg = gogo->lookup("seed", NULL);
2143 go_assert(seed_arg != NULL);
2145 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2146 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2147 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2148 bloc);
2149 Expression_list* args = new Expression_list();
2150 args->push_back(key_ref);
2151 args->push_back(seed_ref);
2152 args->push_back(size_arg);
2153 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2154 Expression* call = Expression::make_call(func, args, false, bloc);
2156 Expression_list* vals = new Expression_list();
2157 vals->push_back(call);
2158 Statement* s = Statement::make_return_statement(vals, bloc);
2159 gogo->add_statement(s);
2162 // Write an equality function for a type that can use an identity
2163 // equality comparison but is not one of the standard supported sizes.
2164 // For example, this would be used for the type [3]byte. This builds
2165 // a return statement that returns a call to the memequal function,
2166 // passing the two keys from the function arguments (already
2167 // constructed before this is called), and the constant size.
2169 void
2170 Type::write_identity_equal(Gogo* gogo, int64_t size)
2172 Location bloc = Linemap::predeclared_location();
2174 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2175 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2177 Typed_identifier_list* params = new Typed_identifier_list();
2178 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2179 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2180 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2182 Typed_identifier_list* results = new Typed_identifier_list();
2183 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2185 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2186 results, bloc);
2188 Named_object* memequal =
2189 Named_object::make_function_declaration("runtime.memequal", NULL,
2190 memequal_fntype, bloc);
2191 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2193 Named_object* key1_arg = gogo->lookup("key1", NULL);
2194 go_assert(key1_arg != NULL);
2195 Named_object* key2_arg = gogo->lookup("key2", NULL);
2196 go_assert(key2_arg != NULL);
2198 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2199 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2200 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2201 bloc);
2202 Expression_list* args = new Expression_list();
2203 args->push_back(key1_ref);
2204 args->push_back(key2_ref);
2205 args->push_back(size_arg);
2206 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2207 Expression* call = Expression::make_call(func, args, false, bloc);
2209 Expression_list* vals = new Expression_list();
2210 vals->push_back(call);
2211 Statement* s = Statement::make_return_statement(vals, bloc);
2212 gogo->add_statement(s);
2215 // Write a hash function that simply calls the hash function for a
2216 // named type. This is used when one named type is defined as
2217 // another. This ensures that this case works when the other named
2218 // type is defined in another package and relies on calling hash
2219 // functions defined only in that package.
2221 void
2222 Type::write_named_hash(Gogo* gogo, Named_type* name,
2223 Function_type* hash_fntype, Function_type* equal_fntype)
2225 Location bloc = Linemap::predeclared_location();
2227 Named_type* base_type = name->real_type()->named_type();
2228 while (base_type->is_alias())
2230 base_type = base_type->real_type()->named_type();
2231 go_assert(base_type != NULL);
2233 go_assert(base_type != NULL);
2235 // The pointer to the type we are going to hash. This is an
2236 // unsafe.Pointer.
2237 Named_object* key_arg = gogo->lookup("key", NULL);
2238 go_assert(key_arg != NULL);
2240 // The seed argument to the hash function.
2241 Named_object* seed_arg = gogo->lookup("seed", NULL);
2242 go_assert(seed_arg != NULL);
2244 Named_object* hash_fn;
2245 Named_object* equal_fn;
2246 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2247 &hash_fn, &equal_fn);
2249 // Call the hash function for the base type.
2250 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2251 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2252 Expression_list* args = new Expression_list();
2253 args->push_back(key_ref);
2254 args->push_back(seed_ref);
2255 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2256 Expression* call = Expression::make_call(func, args, false, bloc);
2258 // Return the hash of the base type.
2259 Expression_list* vals = new Expression_list();
2260 vals->push_back(call);
2261 Statement* s = Statement::make_return_statement(vals, bloc);
2262 gogo->add_statement(s);
2265 // Write an equality function that simply calls the equality function
2266 // for a named type. This is used when one named type is defined as
2267 // another. This ensures that this case works when the other named
2268 // type is defined in another package and relies on calling equality
2269 // functions defined only in that package.
2271 void
2272 Type::write_named_equal(Gogo* gogo, Named_type* name)
2274 Location bloc = Linemap::predeclared_location();
2276 // The pointers to the types we are going to compare. These have
2277 // type unsafe.Pointer.
2278 Named_object* key1_arg = gogo->lookup("key1", NULL);
2279 Named_object* key2_arg = gogo->lookup("key2", NULL);
2280 go_assert(key1_arg != NULL && key2_arg != NULL);
2282 Named_type* base_type = name->real_type()->named_type();
2283 go_assert(base_type != NULL);
2285 // Build temporaries with the base type.
2286 Type* pt = Type::make_pointer_type(base_type);
2288 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2289 ref = Expression::make_cast(pt, ref, bloc);
2290 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2291 gogo->add_statement(p1);
2293 ref = Expression::make_var_reference(key2_arg, bloc);
2294 ref = Expression::make_cast(pt, ref, bloc);
2295 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2296 gogo->add_statement(p2);
2298 // Compare the values for equality.
2299 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2300 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2302 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2303 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2305 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2307 // Return the equality comparison.
2308 Expression_list* vals = new Expression_list();
2309 vals->push_back(cond);
2310 Statement* s = Statement::make_return_statement(vals, bloc);
2311 gogo->add_statement(s);
2314 // Return a composite literal for the type descriptor for a plain type
2315 // of kind RUNTIME_TYPE_KIND named NAME.
2317 Expression*
2318 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2319 Named_type* name, const Methods* methods,
2320 bool only_value_methods)
2322 Location bloc = Linemap::predeclared_location();
2324 Type* td_type = Type::make_type_descriptor_type();
2325 const Struct_field_list* fields = td_type->struct_type()->fields();
2327 Expression_list* vals = new Expression_list();
2328 vals->reserve(12);
2330 if (!this->has_pointer())
2331 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2332 if (this->points_to() != NULL)
2333 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2334 int64_t ptrsize;
2335 int64_t ptrdata;
2336 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2337 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2339 Struct_field_list::const_iterator p = fields->begin();
2340 go_assert(p->is_field_name("size"));
2341 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2342 vals->push_back(Expression::make_type_info(this, type_info));
2344 ++p;
2345 go_assert(p->is_field_name("ptrdata"));
2346 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2347 vals->push_back(Expression::make_type_info(this, type_info));
2349 ++p;
2350 go_assert(p->is_field_name("hash"));
2351 unsigned int h;
2352 if (name != NULL)
2353 h = name->hash_for_method(gogo);
2354 else
2355 h = this->hash_for_method(gogo);
2356 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2358 ++p;
2359 go_assert(p->is_field_name("kind"));
2360 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2361 bloc));
2363 ++p;
2364 go_assert(p->is_field_name("align"));
2365 type_info = Expression::TYPE_INFO_ALIGNMENT;
2366 vals->push_back(Expression::make_type_info(this, type_info));
2368 ++p;
2369 go_assert(p->is_field_name("fieldAlign"));
2370 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2371 vals->push_back(Expression::make_type_info(this, type_info));
2373 ++p;
2374 go_assert(p->is_field_name("hashfn"));
2375 Function_type* hash_fntype = p->type()->function_type();
2377 ++p;
2378 go_assert(p->is_field_name("equalfn"));
2379 Function_type* equal_fntype = p->type()->function_type();
2381 Named_object* hash_fn;
2382 Named_object* equal_fn;
2383 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2384 &equal_fn);
2385 if (hash_fn == NULL)
2386 vals->push_back(Expression::make_cast(hash_fntype,
2387 Expression::make_nil(bloc),
2388 bloc));
2389 else
2390 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2391 if (equal_fn == NULL)
2392 vals->push_back(Expression::make_cast(equal_fntype,
2393 Expression::make_nil(bloc),
2394 bloc));
2395 else
2396 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2398 ++p;
2399 go_assert(p->is_field_name("gcdata"));
2400 vals->push_back(Expression::make_gc_symbol(this));
2402 ++p;
2403 go_assert(p->is_field_name("string"));
2404 Expression* s = Expression::make_string((name != NULL
2405 ? name->reflection(gogo)
2406 : this->reflection(gogo)),
2407 bloc);
2408 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2410 ++p;
2411 go_assert(p->is_field_name("uncommonType"));
2412 if (name == NULL && methods == NULL)
2413 vals->push_back(Expression::make_nil(bloc));
2414 else
2416 if (methods == NULL)
2417 methods = name->methods();
2418 vals->push_back(this->uncommon_type_constructor(gogo,
2419 p->type()->deref(),
2420 name, methods,
2421 only_value_methods));
2424 ++p;
2425 go_assert(p->is_field_name("ptrToThis"));
2426 if (name == NULL && methods == NULL)
2427 vals->push_back(Expression::make_nil(bloc));
2428 else
2430 Type* pt;
2431 if (name != NULL)
2432 pt = Type::make_pointer_type(name);
2433 else
2434 pt = Type::make_pointer_type(this);
2435 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2438 ++p;
2439 go_assert(p == fields->end());
2441 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2444 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2445 // length used by the gc toolchain, and also appears in
2446 // libgo/go/reflect/type.go.
2448 static const int64_t max_ptrmask_bytes = 2048;
2450 // Return a pointer to the Garbage Collection information for this type.
2452 Bexpression*
2453 Type::gc_symbol_pointer(Gogo* gogo)
2455 Type* t = this->unalias();
2457 if (!t->has_pointer())
2458 return gogo->backend()->nil_pointer_expression();
2460 if (t->gc_symbol_var_ == NULL)
2462 t->make_gc_symbol_var(gogo);
2463 go_assert(t->gc_symbol_var_ != NULL);
2465 Location bloc = Linemap::predeclared_location();
2466 Bexpression* var_expr =
2467 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2468 Bexpression* addr_expr =
2469 gogo->backend()->address_expression(var_expr, bloc);
2471 Type* uint8_type = Type::lookup_integer_type("uint8");
2472 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2473 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2474 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2477 // A mapping from unnamed types to GC symbol variables.
2479 Type::GC_symbol_vars Type::gc_symbol_vars;
2481 // Build the GC symbol for this type.
2483 void
2484 Type::make_gc_symbol_var(Gogo* gogo)
2486 go_assert(this->gc_symbol_var_ == NULL);
2488 Named_type* nt = this->named_type();
2490 // We can have multiple instances of unnamed types and similar to type
2491 // descriptors, we only want to the emit the GC data once, so we use a
2492 // hash table.
2493 Bvariable** phash = NULL;
2494 if (nt == NULL)
2496 Bvariable* bvnull = NULL;
2497 std::pair<GC_symbol_vars::iterator, bool> ins =
2498 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2499 if (!ins.second)
2501 // We've already built a gc symbol for this type.
2502 this->gc_symbol_var_ = ins.first->second;
2503 return;
2505 phash = &ins.first->second;
2508 int64_t ptrsize;
2509 int64_t ptrdata;
2510 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2512 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2513 if (phash != NULL)
2514 *phash = this->gc_symbol_var_;
2515 return;
2518 std::string sym_name = gogo->gc_symbol_name(this);
2520 // Build the contents of the gc symbol.
2521 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2522 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2524 // If the type descriptor for this type is defined somewhere else, so is the
2525 // GC symbol.
2526 const Package* dummy;
2527 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2529 std::string asm_name(go_selectively_encode_id(sym_name));
2530 this->gc_symbol_var_ =
2531 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2532 sym_btype);
2533 if (phash != NULL)
2534 *phash = this->gc_symbol_var_;
2535 return;
2538 // See if this gc symbol can appear in multiple packages.
2539 bool is_common = false;
2540 if (nt != NULL)
2542 // We create the symbol for a builtin type whenever we need
2543 // it.
2544 is_common = nt->is_builtin();
2546 else
2548 // This is an unnamed type. The descriptor could be defined in
2549 // any package where it is needed, and the linker will pick one
2550 // descriptor to keep.
2551 is_common = true;
2554 // Since we are building the GC symbol in this package, we must create the
2555 // variable before converting the initializer to its backend representation
2556 // because the initializer may refer to the GC symbol for this type.
2557 std::string asm_name(go_selectively_encode_id(sym_name));
2558 this->gc_symbol_var_ =
2559 gogo->backend()->implicit_variable(sym_name, asm_name,
2560 sym_btype, false, true, is_common, 0);
2561 if (phash != NULL)
2562 *phash = this->gc_symbol_var_;
2564 Translate_context context(gogo, NULL, NULL, NULL);
2565 context.set_is_const();
2566 Bexpression* sym_binit = sym_init->get_backend(&context);
2567 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2568 sym_btype, false, true, is_common,
2569 sym_binit);
2572 // Return whether this type needs a GC program, and set *PTRDATA to
2573 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2574 // pointer.
2576 bool
2577 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2579 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2580 if (!voidptr->backend_type_size(gogo, ptrsize))
2581 go_unreachable();
2583 if (!this->backend_type_ptrdata(gogo, ptrdata))
2585 go_assert(saw_errors());
2586 return false;
2589 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2592 // A simple class used to build a GC ptrmask for a type.
2594 class Ptrmask
2596 public:
2597 Ptrmask(size_t count)
2598 : bits_((count + 7) / 8, 0)
2601 void
2602 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2604 std::string
2605 symname() const;
2607 Expression*
2608 constructor(Gogo* gogo) const;
2610 private:
2611 void
2612 set(size_t index)
2613 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2615 // The actual bits.
2616 std::vector<unsigned char> bits_;
2619 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2620 // counts in bytes. PTRSIZE is the size of a pointer on the target
2621 // system.
2623 void
2624 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2626 switch (type->base()->classification())
2628 default:
2629 case Type::TYPE_NIL:
2630 case Type::TYPE_CALL_MULTIPLE_RESULT:
2631 case Type::TYPE_NAMED:
2632 case Type::TYPE_FORWARD:
2633 go_unreachable();
2635 case Type::TYPE_ERROR:
2636 case Type::TYPE_VOID:
2637 case Type::TYPE_BOOLEAN:
2638 case Type::TYPE_INTEGER:
2639 case Type::TYPE_FLOAT:
2640 case Type::TYPE_COMPLEX:
2641 case Type::TYPE_SINK:
2642 break;
2644 case Type::TYPE_FUNCTION:
2645 case Type::TYPE_POINTER:
2646 case Type::TYPE_MAP:
2647 case Type::TYPE_CHANNEL:
2648 // These types are all a single pointer.
2649 go_assert((offset % ptrsize) == 0);
2650 this->set(offset / ptrsize);
2651 break;
2653 case Type::TYPE_STRING:
2654 // A string starts with a single pointer.
2655 go_assert((offset % ptrsize) == 0);
2656 this->set(offset / ptrsize);
2657 break;
2659 case Type::TYPE_INTERFACE:
2660 // An interface is two pointers.
2661 go_assert((offset % ptrsize) == 0);
2662 this->set(offset / ptrsize);
2663 this->set((offset / ptrsize) + 1);
2664 break;
2666 case Type::TYPE_STRUCT:
2668 if (!type->has_pointer())
2669 return;
2671 const Struct_field_list* fields = type->struct_type()->fields();
2672 int64_t soffset = 0;
2673 for (Struct_field_list::const_iterator pf = fields->begin();
2674 pf != fields->end();
2675 ++pf)
2677 int64_t field_align;
2678 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2680 go_assert(saw_errors());
2681 return;
2683 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2685 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2687 int64_t field_size;
2688 if (!pf->type()->backend_type_size(gogo, &field_size))
2690 go_assert(saw_errors());
2691 return;
2693 soffset += field_size;
2696 break;
2698 case Type::TYPE_ARRAY:
2699 if (type->is_slice_type())
2701 // A slice starts with a single pointer.
2702 go_assert((offset % ptrsize) == 0);
2703 this->set(offset / ptrsize);
2704 break;
2706 else
2708 if (!type->has_pointer())
2709 return;
2711 int64_t len;
2712 if (!type->array_type()->int_length(&len))
2714 go_assert(saw_errors());
2715 return;
2718 Type* element_type = type->array_type()->element_type();
2719 int64_t ele_size;
2720 if (!element_type->backend_type_size(gogo, &ele_size))
2722 go_assert(saw_errors());
2723 return;
2726 int64_t eoffset = 0;
2727 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2728 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2729 break;
2734 // Return a symbol name for this ptrmask. This is used to coalesce
2735 // identical ptrmasks, which are common. The symbol name must use
2736 // only characters that are valid in symbols. It's nice if it's
2737 // short. We convert it to a string that uses only 32 characters,
2738 // avoiding digits and u and U.
2740 std::string
2741 Ptrmask::symname() const
2743 const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2744 go_assert(chars[32] == '\0');
2745 std::string ret;
2746 unsigned int b = 0;
2747 int remaining = 0;
2748 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2749 p != this->bits_.end();
2750 ++p)
2752 b |= *p << remaining;
2753 remaining += 8;
2754 while (remaining >= 5)
2756 ret += chars[b & 0x1f];
2757 b >>= 5;
2758 remaining -= 5;
2761 while (remaining > 0)
2763 ret += chars[b & 0x1f];
2764 b >>= 5;
2765 remaining -= 5;
2767 return ret;
2770 // Return a constructor for this ptrmask. This will be used to
2771 // initialize the runtime ptrmask value.
2773 Expression*
2774 Ptrmask::constructor(Gogo* gogo) const
2776 Location bloc = Linemap::predeclared_location();
2777 Type* byte_type = gogo->lookup_global("byte")->type_value();
2778 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2779 bloc);
2780 Array_type* at = Type::make_array_type(byte_type, len);
2781 Expression_list* vals = new Expression_list();
2782 vals->reserve(this->bits_.size());
2783 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2784 p != this->bits_.end();
2785 ++p)
2786 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2787 return Expression::make_array_composite_literal(at, vals, bloc);
2790 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2791 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2793 // Return a ptrmask variable for a type. For a type descriptor this
2794 // is only used for variables that are small enough to not need a
2795 // gcprog, but for a global variable this is used for a variable of
2796 // any size. PTRDATA is the number of bytes of the type that contain
2797 // pointer data. PTRSIZE is the size of a pointer on the target
2798 // system.
2800 Bvariable*
2801 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2803 Ptrmask ptrmask(ptrdata / ptrsize);
2804 if (ptrdata >= ptrsize)
2805 ptrmask.set_from(gogo, this, ptrsize, 0);
2806 else
2808 // This can happen in error cases. Just build an empty gcbits.
2809 go_assert(saw_errors());
2812 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2813 Bvariable* bvnull = NULL;
2814 std::pair<GC_gcbits_vars::iterator, bool> ins =
2815 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2816 if (!ins.second)
2818 // We've already built a GC symbol for this set of gcbits.
2819 return ins.first->second;
2822 Expression* val = ptrmask.constructor(gogo);
2823 Translate_context context(gogo, NULL, NULL, NULL);
2824 context.set_is_const();
2825 Bexpression* bval = val->get_backend(&context);
2827 std::string asm_name(go_selectively_encode_id(sym_name));
2828 Btype *btype = val->type()->get_backend(gogo);
2829 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2830 btype, false, true,
2831 true, 0);
2832 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2833 true, true, bval);
2834 ins.first->second = ret;
2835 return ret;
2838 // A GCProg is used to build a program for the garbage collector.
2839 // This is used for types with a lot of pointer data, to reduce the
2840 // size of the data in the compiled program. The program is expanded
2841 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2843 class GCProg
2845 public:
2846 GCProg()
2847 : bytes_(), index_(0), nb_(0)
2850 // The number of bits described so far.
2851 int64_t
2852 bit_index() const
2853 { return this->index_; }
2855 void
2856 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2858 void
2859 end();
2861 Expression*
2862 constructor(Gogo* gogo) const;
2864 private:
2865 void
2866 ptr(int64_t);
2868 bool
2869 should_repeat(int64_t, int64_t);
2871 void
2872 repeat(int64_t, int64_t);
2874 void
2875 zero_until(int64_t);
2877 void
2878 lit(unsigned char);
2880 void
2881 varint(int64_t);
2883 void
2884 flushlit();
2886 // Add a byte to the program.
2887 void
2888 byte(unsigned char x)
2889 { this->bytes_.push_back(x); }
2891 // The maximum number of bytes of literal bits.
2892 static const int max_literal = 127;
2894 // The program.
2895 std::vector<unsigned char> bytes_;
2896 // The index of the last bit described.
2897 int64_t index_;
2898 // The current set of literal bits.
2899 unsigned char b_[max_literal];
2900 // The current number of literal bits.
2901 int nb_;
2904 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2905 // counts in bytes. PTRSIZE is the size of a pointer on the target
2906 // system.
2908 void
2909 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2911 switch (type->base()->classification())
2913 default:
2914 case Type::TYPE_NIL:
2915 case Type::TYPE_CALL_MULTIPLE_RESULT:
2916 case Type::TYPE_NAMED:
2917 case Type::TYPE_FORWARD:
2918 go_unreachable();
2920 case Type::TYPE_ERROR:
2921 case Type::TYPE_VOID:
2922 case Type::TYPE_BOOLEAN:
2923 case Type::TYPE_INTEGER:
2924 case Type::TYPE_FLOAT:
2925 case Type::TYPE_COMPLEX:
2926 case Type::TYPE_SINK:
2927 break;
2929 case Type::TYPE_FUNCTION:
2930 case Type::TYPE_POINTER:
2931 case Type::TYPE_MAP:
2932 case Type::TYPE_CHANNEL:
2933 // These types are all a single pointer.
2934 go_assert((offset % ptrsize) == 0);
2935 this->ptr(offset / ptrsize);
2936 break;
2938 case Type::TYPE_STRING:
2939 // A string starts with a single pointer.
2940 go_assert((offset % ptrsize) == 0);
2941 this->ptr(offset / ptrsize);
2942 break;
2944 case Type::TYPE_INTERFACE:
2945 // An interface is two pointers.
2946 go_assert((offset % ptrsize) == 0);
2947 this->ptr(offset / ptrsize);
2948 this->ptr((offset / ptrsize) + 1);
2949 break;
2951 case Type::TYPE_STRUCT:
2953 if (!type->has_pointer())
2954 return;
2956 const Struct_field_list* fields = type->struct_type()->fields();
2957 int64_t soffset = 0;
2958 for (Struct_field_list::const_iterator pf = fields->begin();
2959 pf != fields->end();
2960 ++pf)
2962 int64_t field_align;
2963 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2965 go_assert(saw_errors());
2966 return;
2968 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2970 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2972 int64_t field_size;
2973 if (!pf->type()->backend_type_size(gogo, &field_size))
2975 go_assert(saw_errors());
2976 return;
2978 soffset += field_size;
2981 break;
2983 case Type::TYPE_ARRAY:
2984 if (type->is_slice_type())
2986 // A slice starts with a single pointer.
2987 go_assert((offset % ptrsize) == 0);
2988 this->ptr(offset / ptrsize);
2989 break;
2991 else
2993 if (!type->has_pointer())
2994 return;
2996 int64_t len;
2997 if (!type->array_type()->int_length(&len))
2999 go_assert(saw_errors());
3000 return;
3003 Type* element_type = type->array_type()->element_type();
3005 // Flatten array of array to a big array by multiplying counts.
3006 while (element_type->array_type() != NULL
3007 && !element_type->is_slice_type())
3009 int64_t ele_len;
3010 if (!element_type->array_type()->int_length(&ele_len))
3012 go_assert(saw_errors());
3013 return;
3016 len *= ele_len;
3017 element_type = element_type->array_type()->element_type();
3020 int64_t ele_size;
3021 if (!element_type->backend_type_size(gogo, &ele_size))
3023 go_assert(saw_errors());
3024 return;
3027 go_assert(len > 0 && ele_size > 0);
3029 if (!this->should_repeat(ele_size / ptrsize, len))
3031 // Cheaper to just emit the bits.
3032 int64_t eoffset = 0;
3033 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3034 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3036 else
3038 go_assert((offset % ptrsize) == 0);
3039 go_assert((ele_size % ptrsize) == 0);
3040 this->set_from(gogo, element_type, ptrsize, offset);
3041 this->zero_until((offset + ele_size) / ptrsize);
3042 this->repeat(ele_size / ptrsize, len - 1);
3045 break;
3050 // Emit a 1 into the bit stream of a GC program at the given bit index.
3052 void
3053 GCProg::ptr(int64_t index)
3055 go_assert(index >= this->index_);
3056 this->zero_until(index);
3057 this->lit(1);
3060 // Return whether it is worthwhile to use a repeat to describe c
3061 // elements of n bits each, compared to just emitting c copies of the
3062 // n-bit description.
3064 bool
3065 GCProg::should_repeat(int64_t n, int64_t c)
3067 // Repeat if there is more than 1 item and if the total data doesn't
3068 // fit into four bytes.
3069 return c > 1 && c * n > 4 * 8;
3072 // Emit an instruction to repeat the description of the last n words c
3073 // times (including the initial description, so c + 1 times in total).
3075 void
3076 GCProg::repeat(int64_t n, int64_t c)
3078 if (n == 0 || c == 0)
3079 return;
3080 this->flushlit();
3081 if (n < 128)
3082 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3083 else
3085 this->byte(0x80);
3086 this->varint(n);
3088 this->varint(c);
3089 this->index_ += n * c;
3092 // Add zeros to the bit stream up to the given index.
3094 void
3095 GCProg::zero_until(int64_t index)
3097 go_assert(index >= this->index_);
3098 int64_t skip = index - this->index_;
3099 if (skip == 0)
3100 return;
3101 if (skip < 4 * 8)
3103 for (int64_t i = 0; i < skip; ++i)
3104 this->lit(0);
3105 return;
3107 this->lit(0);
3108 this->flushlit();
3109 this->repeat(1, skip - 1);
3112 // Add a single literal bit to the program.
3114 void
3115 GCProg::lit(unsigned char x)
3117 if (this->nb_ == GCProg::max_literal)
3118 this->flushlit();
3119 this->b_[this->nb_] = x;
3120 ++this->nb_;
3121 ++this->index_;
3124 // Emit the varint encoding of x.
3126 void
3127 GCProg::varint(int64_t x)
3129 go_assert(x >= 0);
3130 while (x >= 0x80)
3132 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3133 x >>= 7;
3135 this->byte(static_cast<unsigned char>(x & 0x7f));
3138 // Flush any pending literal bits.
3140 void
3141 GCProg::flushlit()
3143 if (this->nb_ == 0)
3144 return;
3145 this->byte(static_cast<unsigned char>(this->nb_));
3146 unsigned char bits = 0;
3147 for (int i = 0; i < this->nb_; ++i)
3149 bits |= this->b_[i] << (i % 8);
3150 if ((i + 1) % 8 == 0)
3152 this->byte(bits);
3153 bits = 0;
3156 if (this->nb_ % 8 != 0)
3157 this->byte(bits);
3158 this->nb_ = 0;
3161 // Mark the end of a GC program.
3163 void
3164 GCProg::end()
3166 this->flushlit();
3167 this->byte(0);
3170 // Return an Expression for the bytes in a GC program.
3172 Expression*
3173 GCProg::constructor(Gogo* gogo) const
3175 Location bloc = Linemap::predeclared_location();
3177 // The first four bytes are the length of the program in target byte
3178 // order. Build a struct whose first type is uint32 to make this
3179 // work.
3181 Type* uint32_type = Type::lookup_integer_type("uint32");
3183 Type* byte_type = gogo->lookup_global("byte")->type_value();
3184 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3185 bloc);
3186 Array_type* at = Type::make_array_type(byte_type, len);
3188 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3189 "bytes", at);
3191 Expression_list* vals = new Expression_list();
3192 vals->reserve(this->bytes_.size());
3193 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3194 p != this->bytes_.end();
3195 ++p)
3196 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3197 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3199 vals = new Expression_list();
3200 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3201 bloc));
3202 vals->push_back(bytes);
3204 return Expression::make_struct_composite_literal(st, vals, bloc);
3207 // Return a composite literal for the garbage collection program for
3208 // this type. This is only used for types that are too large to use a
3209 // ptrmask.
3211 Expression*
3212 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3214 Location bloc = Linemap::predeclared_location();
3216 GCProg prog;
3217 prog.set_from(gogo, this, ptrsize, 0);
3218 int64_t offset = prog.bit_index() * ptrsize;
3219 prog.end();
3221 int64_t type_size;
3222 if (!this->backend_type_size(gogo, &type_size))
3224 go_assert(saw_errors());
3225 return Expression::make_error(bloc);
3228 go_assert(offset >= ptrdata && offset <= type_size);
3230 return prog.constructor(gogo);
3233 // Return a composite literal for the uncommon type information for
3234 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3235 // struct. If name is not NULL, it is the name of the type. If
3236 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3237 // is true if only value methods should be included. At least one of
3238 // NAME and METHODS must not be NULL.
3240 Expression*
3241 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3242 Named_type* name, const Methods* methods,
3243 bool only_value_methods) const
3245 Location bloc = Linemap::predeclared_location();
3247 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3249 Expression_list* vals = new Expression_list();
3250 vals->reserve(3);
3252 Struct_field_list::const_iterator p = fields->begin();
3253 go_assert(p->is_field_name("name"));
3255 ++p;
3256 go_assert(p->is_field_name("pkgPath"));
3258 if (name == NULL)
3260 vals->push_back(Expression::make_nil(bloc));
3261 vals->push_back(Expression::make_nil(bloc));
3263 else
3265 Named_object* no = name->named_object();
3266 std::string n = Gogo::unpack_hidden_name(no->name());
3267 Expression* s = Expression::make_string(n, bloc);
3268 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3270 if (name->is_builtin())
3271 vals->push_back(Expression::make_nil(bloc));
3272 else
3274 const Package* package = no->package();
3275 const std::string& pkgpath(package == NULL
3276 ? gogo->pkgpath()
3277 : package->pkgpath());
3278 s = Expression::make_string(pkgpath, bloc);
3279 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3283 ++p;
3284 go_assert(p->is_field_name("methods"));
3285 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3286 only_value_methods));
3288 ++p;
3289 go_assert(p == fields->end());
3291 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3292 vals, bloc);
3293 return Expression::make_unary(OPERATOR_AND, r, bloc);
3296 // Sort methods by name.
3298 class Sort_methods
3300 public:
3301 bool
3302 operator()(const std::pair<std::string, const Method*>& m1,
3303 const std::pair<std::string, const Method*>& m2) const
3305 return (Gogo::unpack_hidden_name(m1.first)
3306 < Gogo::unpack_hidden_name(m2.first));
3310 // Return a composite literal for the type method table for this type.
3311 // METHODS_TYPE is the type of the table, and is a slice type.
3312 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3313 // then only value methods are used.
3315 Expression*
3316 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3317 const Methods* methods,
3318 bool only_value_methods) const
3320 Location bloc = Linemap::predeclared_location();
3322 std::vector<std::pair<std::string, const Method*> > smethods;
3323 if (methods != NULL)
3325 smethods.reserve(methods->count());
3326 for (Methods::const_iterator p = methods->begin();
3327 p != methods->end();
3328 ++p)
3330 if (p->second->is_ambiguous())
3331 continue;
3332 if (only_value_methods && !p->second->is_value_method())
3333 continue;
3335 // This is where we implement the magic //go:nointerface
3336 // comment. If we saw that comment, we don't add this
3337 // method to the type descriptor.
3338 if (p->second->nointerface())
3339 continue;
3341 smethods.push_back(std::make_pair(p->first, p->second));
3345 if (smethods.empty())
3346 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3348 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3350 Type* method_type = methods_type->array_type()->element_type();
3352 Expression_list* vals = new Expression_list();
3353 vals->reserve(smethods.size());
3354 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3355 = smethods.begin();
3356 p != smethods.end();
3357 ++p)
3358 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3359 p->second, only_value_methods));
3361 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3364 // Return a composite literal for a single method. METHOD_TYPE is the
3365 // type of the entry. METHOD_NAME is the name of the method and M is
3366 // the method information.
3368 Expression*
3369 Type::method_constructor(Gogo*, Type* method_type,
3370 const std::string& method_name,
3371 const Method* m,
3372 bool only_value_methods) const
3374 Location bloc = Linemap::predeclared_location();
3376 const Struct_field_list* fields = method_type->struct_type()->fields();
3378 Expression_list* vals = new Expression_list();
3379 vals->reserve(5);
3381 Struct_field_list::const_iterator p = fields->begin();
3382 go_assert(p->is_field_name("name"));
3383 const std::string n = Gogo::unpack_hidden_name(method_name);
3384 Expression* s = Expression::make_string(n, bloc);
3385 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3387 ++p;
3388 go_assert(p->is_field_name("pkgPath"));
3389 if (!Gogo::is_hidden_name(method_name))
3390 vals->push_back(Expression::make_nil(bloc));
3391 else
3393 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3394 bloc);
3395 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3398 Named_object* no = (m->needs_stub_method()
3399 ? m->stub_object()
3400 : m->named_object());
3402 Function_type* mtype;
3403 if (no->is_function())
3404 mtype = no->func_value()->type();
3405 else
3406 mtype = no->func_declaration_value()->type();
3407 go_assert(mtype->is_method());
3408 Type* nonmethod_type = mtype->copy_without_receiver();
3410 ++p;
3411 go_assert(p->is_field_name("mtyp"));
3412 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3414 ++p;
3415 go_assert(p->is_field_name("typ"));
3416 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3417 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3418 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3420 ++p;
3421 go_assert(p->is_field_name("tfn"));
3422 vals->push_back(Expression::make_func_code_reference(no, bloc));
3424 ++p;
3425 go_assert(p == fields->end());
3427 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3430 // Return a composite literal for the type descriptor of a plain type.
3431 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3432 // NULL, it is the name to use as well as the list of methods.
3434 Expression*
3435 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3436 Named_type* name)
3438 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3439 name, NULL, true);
3442 // Return the type reflection string for this type.
3444 std::string
3445 Type::reflection(Gogo* gogo) const
3447 std::string ret;
3449 // The do_reflection virtual function should set RET to the
3450 // reflection string.
3451 this->do_reflection(gogo, &ret);
3453 return ret;
3456 // Return whether the backend size of the type is known.
3458 bool
3459 Type::is_backend_type_size_known(Gogo* gogo)
3461 switch (this->classification_)
3463 case TYPE_ERROR:
3464 case TYPE_VOID:
3465 case TYPE_BOOLEAN:
3466 case TYPE_INTEGER:
3467 case TYPE_FLOAT:
3468 case TYPE_COMPLEX:
3469 case TYPE_STRING:
3470 case TYPE_FUNCTION:
3471 case TYPE_POINTER:
3472 case TYPE_NIL:
3473 case TYPE_MAP:
3474 case TYPE_CHANNEL:
3475 case TYPE_INTERFACE:
3476 return true;
3478 case TYPE_STRUCT:
3480 const Struct_field_list* fields = this->struct_type()->fields();
3481 for (Struct_field_list::const_iterator pf = fields->begin();
3482 pf != fields->end();
3483 ++pf)
3484 if (!pf->type()->is_backend_type_size_known(gogo))
3485 return false;
3486 return true;
3489 case TYPE_ARRAY:
3491 const Array_type* at = this->array_type();
3492 if (at->length() == NULL)
3493 return true;
3494 else
3496 Numeric_constant nc;
3497 if (!at->length()->numeric_constant_value(&nc))
3498 return false;
3499 mpz_t ival;
3500 if (!nc.to_int(&ival))
3501 return false;
3502 mpz_clear(ival);
3503 return at->element_type()->is_backend_type_size_known(gogo);
3507 case TYPE_NAMED:
3508 this->named_type()->convert(gogo);
3509 return this->named_type()->is_named_backend_type_size_known();
3511 case TYPE_FORWARD:
3513 Forward_declaration_type* fdt = this->forward_declaration_type();
3514 return fdt->real_type()->is_backend_type_size_known(gogo);
3517 case TYPE_SINK:
3518 case TYPE_CALL_MULTIPLE_RESULT:
3519 go_unreachable();
3521 default:
3522 go_unreachable();
3526 // If the size of the type can be determined, set *PSIZE to the size
3527 // in bytes and return true. Otherwise, return false. This queries
3528 // the backend.
3530 bool
3531 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3533 if (!this->is_backend_type_size_known(gogo))
3534 return false;
3535 if (this->is_error_type())
3536 return false;
3537 Btype* bt = this->get_backend_placeholder(gogo);
3538 *psize = gogo->backend()->type_size(bt);
3539 if (*psize == -1)
3541 if (this->named_type() != NULL)
3542 go_error_at(this->named_type()->location(),
3543 "type %s larger than address space",
3544 Gogo::message_name(this->named_type()->name()).c_str());
3545 else
3546 go_error_at(Linemap::unknown_location(),
3547 "type %s larger than address space",
3548 this->reflection(gogo).c_str());
3550 // Make this an error type to avoid knock-on errors.
3551 this->classification_ = TYPE_ERROR;
3552 return false;
3554 return true;
3557 // If the alignment of the type can be determined, set *PALIGN to
3558 // the alignment in bytes and return true. Otherwise, return false.
3560 bool
3561 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3563 if (!this->is_backend_type_size_known(gogo))
3564 return false;
3565 Btype* bt = this->get_backend_placeholder(gogo);
3566 *palign = gogo->backend()->type_alignment(bt);
3567 return true;
3570 // Like backend_type_align, but return the alignment when used as a
3571 // field.
3573 bool
3574 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3576 if (!this->is_backend_type_size_known(gogo))
3577 return false;
3578 Btype* bt = this->get_backend_placeholder(gogo);
3579 *palign = gogo->backend()->type_field_alignment(bt);
3580 return true;
3583 // Get the ptrdata value for a type. This is the size of the prefix
3584 // of the type that contains all pointers. Store the ptrdata in
3585 // *PPTRDATA and return whether we found it.
3587 bool
3588 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3590 *pptrdata = 0;
3592 if (!this->has_pointer())
3593 return true;
3595 if (!this->is_backend_type_size_known(gogo))
3596 return false;
3598 switch (this->classification_)
3600 case TYPE_ERROR:
3601 return true;
3603 case TYPE_FUNCTION:
3604 case TYPE_POINTER:
3605 case TYPE_MAP:
3606 case TYPE_CHANNEL:
3607 // These types are nothing but a pointer.
3608 return this->backend_type_size(gogo, pptrdata);
3610 case TYPE_INTERFACE:
3611 // An interface is a struct of two pointers.
3612 return this->backend_type_size(gogo, pptrdata);
3614 case TYPE_STRING:
3616 // A string is a struct whose first field is a pointer, and
3617 // whose second field is not.
3618 Type* uint8_type = Type::lookup_integer_type("uint8");
3619 Type* ptr = Type::make_pointer_type(uint8_type);
3620 return ptr->backend_type_size(gogo, pptrdata);
3623 case TYPE_NAMED:
3624 case TYPE_FORWARD:
3625 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3627 case TYPE_STRUCT:
3629 const Struct_field_list* fields = this->struct_type()->fields();
3630 int64_t offset = 0;
3631 const Struct_field *ptr = NULL;
3632 int64_t ptr_offset = 0;
3633 for (Struct_field_list::const_iterator pf = fields->begin();
3634 pf != fields->end();
3635 ++pf)
3637 int64_t field_align;
3638 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3639 return false;
3640 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3642 if (pf->type()->has_pointer())
3644 ptr = &*pf;
3645 ptr_offset = offset;
3648 int64_t field_size;
3649 if (!pf->type()->backend_type_size(gogo, &field_size))
3650 return false;
3651 offset += field_size;
3654 if (ptr != NULL)
3656 int64_t ptr_ptrdata;
3657 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3658 return false;
3659 *pptrdata = ptr_offset + ptr_ptrdata;
3661 return true;
3664 case TYPE_ARRAY:
3665 if (this->is_slice_type())
3667 // A slice is a struct whose first field is a pointer, and
3668 // whose remaining fields are not.
3669 Type* element_type = this->array_type()->element_type();
3670 Type* ptr = Type::make_pointer_type(element_type);
3671 return ptr->backend_type_size(gogo, pptrdata);
3673 else
3675 Numeric_constant nc;
3676 if (!this->array_type()->length()->numeric_constant_value(&nc))
3677 return false;
3678 int64_t len;
3679 if (!nc.to_memory_size(&len))
3680 return false;
3682 Type* element_type = this->array_type()->element_type();
3683 int64_t ele_size;
3684 int64_t ele_ptrdata;
3685 if (!element_type->backend_type_size(gogo, &ele_size)
3686 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3687 return false;
3688 go_assert(ele_size > 0 && ele_ptrdata > 0);
3690 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3691 return true;
3694 default:
3695 case TYPE_VOID:
3696 case TYPE_BOOLEAN:
3697 case TYPE_INTEGER:
3698 case TYPE_FLOAT:
3699 case TYPE_COMPLEX:
3700 case TYPE_SINK:
3701 case TYPE_NIL:
3702 case TYPE_CALL_MULTIPLE_RESULT:
3703 go_unreachable();
3707 // Get the ptrdata value to store in a type descriptor. This is
3708 // normally the same as backend_type_ptrdata, but for a type that is
3709 // large enough to use a gcprog we may need to store a different value
3710 // if it ends with an array. If the gcprog uses a repeat descriptor
3711 // for the array, and if the array element ends with non-pointer data,
3712 // then the gcprog will produce a value that describes the complete
3713 // array where the backend ptrdata will omit the non-pointer elements
3714 // of the final array element. This is a subtle difference but the
3715 // run time code checks it to verify that it has expanded a gcprog as
3716 // expected.
3718 bool
3719 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3721 int64_t backend_ptrdata;
3722 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3723 return false;
3725 int64_t ptrsize;
3726 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3728 *pptrdata = backend_ptrdata;
3729 return true;
3732 GCProg prog;
3733 prog.set_from(gogo, this, ptrsize, 0);
3734 int64_t offset = prog.bit_index() * ptrsize;
3736 go_assert(offset >= backend_ptrdata);
3737 *pptrdata = offset;
3738 return true;
3741 // Default function to export a type.
3743 void
3744 Type::do_export(Export*) const
3746 go_unreachable();
3749 // Import a type.
3751 Type*
3752 Type::import_type(Import* imp)
3754 if (imp->match_c_string("("))
3755 return Function_type::do_import(imp);
3756 else if (imp->match_c_string("*"))
3757 return Pointer_type::do_import(imp);
3758 else if (imp->match_c_string("struct "))
3759 return Struct_type::do_import(imp);
3760 else if (imp->match_c_string("["))
3761 return Array_type::do_import(imp);
3762 else if (imp->match_c_string("map "))
3763 return Map_type::do_import(imp);
3764 else if (imp->match_c_string("chan "))
3765 return Channel_type::do_import(imp);
3766 else if (imp->match_c_string("interface"))
3767 return Interface_type::do_import(imp);
3768 else
3770 go_error_at(imp->location(), "import error: expected type");
3771 return Type::make_error_type();
3775 // Class Error_type.
3777 // Return the backend representation of an Error type.
3779 Btype*
3780 Error_type::do_get_backend(Gogo* gogo)
3782 return gogo->backend()->error_type();
3785 // Return an expression for the type descriptor for an error type.
3788 Expression*
3789 Error_type::do_type_descriptor(Gogo*, Named_type*)
3791 return Expression::make_error(Linemap::predeclared_location());
3794 // We should not be asked for the reflection string for an error type.
3796 void
3797 Error_type::do_reflection(Gogo*, std::string*) const
3799 go_assert(saw_errors());
3802 Type*
3803 Type::make_error_type()
3805 static Error_type singleton_error_type;
3806 return &singleton_error_type;
3809 // Class Void_type.
3811 // Get the backend representation of a void type.
3813 Btype*
3814 Void_type::do_get_backend(Gogo* gogo)
3816 return gogo->backend()->void_type();
3819 Type*
3820 Type::make_void_type()
3822 static Void_type singleton_void_type;
3823 return &singleton_void_type;
3826 // Class Boolean_type.
3828 // Return the backend representation of the boolean type.
3830 Btype*
3831 Boolean_type::do_get_backend(Gogo* gogo)
3833 return gogo->backend()->bool_type();
3836 // Make the type descriptor.
3838 Expression*
3839 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3841 if (name != NULL)
3842 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3843 else
3845 Named_object* no = gogo->lookup_global("bool");
3846 go_assert(no != NULL);
3847 return Type::type_descriptor(gogo, no->type_value());
3851 Type*
3852 Type::make_boolean_type()
3854 static Boolean_type boolean_type;
3855 return &boolean_type;
3858 // The named type "bool".
3860 static Named_type* named_bool_type;
3862 // Get the named type "bool".
3864 Named_type*
3865 Type::lookup_bool_type()
3867 return named_bool_type;
3870 // Make the named type "bool".
3872 Named_type*
3873 Type::make_named_bool_type()
3875 Type* bool_type = Type::make_boolean_type();
3876 Named_object* named_object =
3877 Named_object::make_type("bool", NULL, bool_type,
3878 Linemap::predeclared_location());
3879 Named_type* named_type = named_object->type_value();
3880 named_bool_type = named_type;
3881 return named_type;
3884 // Class Integer_type.
3886 Integer_type::Named_integer_types Integer_type::named_integer_types;
3888 // Create a new integer type. Non-abstract integer types always have
3889 // names.
3891 Named_type*
3892 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3893 int bits, int runtime_type_kind)
3895 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3896 runtime_type_kind);
3897 std::string sname(name);
3898 Named_object* named_object =
3899 Named_object::make_type(sname, NULL, integer_type,
3900 Linemap::predeclared_location());
3901 Named_type* named_type = named_object->type_value();
3902 std::pair<Named_integer_types::iterator, bool> ins =
3903 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3904 go_assert(ins.second);
3905 return named_type;
3908 // Look up an existing integer type.
3910 Named_type*
3911 Integer_type::lookup_integer_type(const char* name)
3913 Named_integer_types::const_iterator p =
3914 Integer_type::named_integer_types.find(name);
3915 go_assert(p != Integer_type::named_integer_types.end());
3916 return p->second;
3919 // Create a new abstract integer type.
3921 Integer_type*
3922 Integer_type::create_abstract_integer_type()
3924 static Integer_type* abstract_type;
3925 if (abstract_type == NULL)
3927 Type* int_type = Type::lookup_integer_type("int");
3928 abstract_type = new Integer_type(true, false,
3929 int_type->integer_type()->bits(),
3930 RUNTIME_TYPE_KIND_INT);
3932 return abstract_type;
3935 // Create a new abstract character type.
3937 Integer_type*
3938 Integer_type::create_abstract_character_type()
3940 static Integer_type* abstract_type;
3941 if (abstract_type == NULL)
3943 abstract_type = new Integer_type(true, false, 32,
3944 RUNTIME_TYPE_KIND_INT32);
3945 abstract_type->set_is_rune();
3947 return abstract_type;
3950 // Integer type compatibility.
3952 bool
3953 Integer_type::is_identical(const Integer_type* t) const
3955 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3956 return false;
3957 return this->is_abstract_ == t->is_abstract_;
3960 // Hash code.
3962 unsigned int
3963 Integer_type::do_hash_for_method(Gogo*) const
3965 return ((this->bits_ << 4)
3966 + ((this->is_unsigned_ ? 1 : 0) << 8)
3967 + ((this->is_abstract_ ? 1 : 0) << 9));
3970 // Convert an Integer_type to the backend representation.
3972 Btype*
3973 Integer_type::do_get_backend(Gogo* gogo)
3975 if (this->is_abstract_)
3977 go_assert(saw_errors());
3978 return gogo->backend()->error_type();
3980 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
3983 // The type descriptor for an integer type. Integer types are always
3984 // named.
3986 Expression*
3987 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3989 go_assert(name != NULL || saw_errors());
3990 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
3993 // We should not be asked for the reflection string of a basic type.
3995 void
3996 Integer_type::do_reflection(Gogo*, std::string*) const
3998 go_assert(saw_errors());
4001 // Make an integer type.
4003 Named_type*
4004 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4005 int runtime_type_kind)
4007 return Integer_type::create_integer_type(name, is_unsigned, bits,
4008 runtime_type_kind);
4011 // Make an abstract integer type.
4013 Integer_type*
4014 Type::make_abstract_integer_type()
4016 return Integer_type::create_abstract_integer_type();
4019 // Make an abstract character type.
4021 Integer_type*
4022 Type::make_abstract_character_type()
4024 return Integer_type::create_abstract_character_type();
4027 // Look up an integer type.
4029 Named_type*
4030 Type::lookup_integer_type(const char* name)
4032 return Integer_type::lookup_integer_type(name);
4035 // Class Float_type.
4037 Float_type::Named_float_types Float_type::named_float_types;
4039 // Create a new float type. Non-abstract float types always have
4040 // names.
4042 Named_type*
4043 Float_type::create_float_type(const char* name, int bits,
4044 int runtime_type_kind)
4046 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4047 std::string sname(name);
4048 Named_object* named_object =
4049 Named_object::make_type(sname, NULL, float_type,
4050 Linemap::predeclared_location());
4051 Named_type* named_type = named_object->type_value();
4052 std::pair<Named_float_types::iterator, bool> ins =
4053 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4054 go_assert(ins.second);
4055 return named_type;
4058 // Look up an existing float type.
4060 Named_type*
4061 Float_type::lookup_float_type(const char* name)
4063 Named_float_types::const_iterator p =
4064 Float_type::named_float_types.find(name);
4065 go_assert(p != Float_type::named_float_types.end());
4066 return p->second;
4069 // Create a new abstract float type.
4071 Float_type*
4072 Float_type::create_abstract_float_type()
4074 static Float_type* abstract_type;
4075 if (abstract_type == NULL)
4076 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4077 return abstract_type;
4080 // Whether this type is identical with T.
4082 bool
4083 Float_type::is_identical(const Float_type* t) const
4085 if (this->bits_ != t->bits_)
4086 return false;
4087 return this->is_abstract_ == t->is_abstract_;
4090 // Hash code.
4092 unsigned int
4093 Float_type::do_hash_for_method(Gogo*) const
4095 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4098 // Convert to the backend representation.
4100 Btype*
4101 Float_type::do_get_backend(Gogo* gogo)
4103 return gogo->backend()->float_type(this->bits_);
4106 // The type descriptor for a float type. Float types are always named.
4108 Expression*
4109 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4111 go_assert(name != NULL || saw_errors());
4112 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4115 // We should not be asked for the reflection string of a basic type.
4117 void
4118 Float_type::do_reflection(Gogo*, std::string*) const
4120 go_assert(saw_errors());
4123 // Make a floating point type.
4125 Named_type*
4126 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4128 return Float_type::create_float_type(name, bits, runtime_type_kind);
4131 // Make an abstract float type.
4133 Float_type*
4134 Type::make_abstract_float_type()
4136 return Float_type::create_abstract_float_type();
4139 // Look up a float type.
4141 Named_type*
4142 Type::lookup_float_type(const char* name)
4144 return Float_type::lookup_float_type(name);
4147 // Class Complex_type.
4149 Complex_type::Named_complex_types Complex_type::named_complex_types;
4151 // Create a new complex type. Non-abstract complex types always have
4152 // names.
4154 Named_type*
4155 Complex_type::create_complex_type(const char* name, int bits,
4156 int runtime_type_kind)
4158 Complex_type* complex_type = new Complex_type(false, bits,
4159 runtime_type_kind);
4160 std::string sname(name);
4161 Named_object* named_object =
4162 Named_object::make_type(sname, NULL, complex_type,
4163 Linemap::predeclared_location());
4164 Named_type* named_type = named_object->type_value();
4165 std::pair<Named_complex_types::iterator, bool> ins =
4166 Complex_type::named_complex_types.insert(std::make_pair(sname,
4167 named_type));
4168 go_assert(ins.second);
4169 return named_type;
4172 // Look up an existing complex type.
4174 Named_type*
4175 Complex_type::lookup_complex_type(const char* name)
4177 Named_complex_types::const_iterator p =
4178 Complex_type::named_complex_types.find(name);
4179 go_assert(p != Complex_type::named_complex_types.end());
4180 return p->second;
4183 // Create a new abstract complex type.
4185 Complex_type*
4186 Complex_type::create_abstract_complex_type()
4188 static Complex_type* abstract_type;
4189 if (abstract_type == NULL)
4190 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4191 return abstract_type;
4194 // Whether this type is identical with T.
4196 bool
4197 Complex_type::is_identical(const Complex_type *t) const
4199 if (this->bits_ != t->bits_)
4200 return false;
4201 return this->is_abstract_ == t->is_abstract_;
4204 // Hash code.
4206 unsigned int
4207 Complex_type::do_hash_for_method(Gogo*) const
4209 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4212 // Convert to the backend representation.
4214 Btype*
4215 Complex_type::do_get_backend(Gogo* gogo)
4217 return gogo->backend()->complex_type(this->bits_);
4220 // The type descriptor for a complex type. Complex types are always
4221 // named.
4223 Expression*
4224 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4226 go_assert(name != NULL || saw_errors());
4227 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4230 // We should not be asked for the reflection string of a basic type.
4232 void
4233 Complex_type::do_reflection(Gogo*, std::string*) const
4235 go_assert(saw_errors());
4238 // Make a complex type.
4240 Named_type*
4241 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4243 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4246 // Make an abstract complex type.
4248 Complex_type*
4249 Type::make_abstract_complex_type()
4251 return Complex_type::create_abstract_complex_type();
4254 // Look up a complex type.
4256 Named_type*
4257 Type::lookup_complex_type(const char* name)
4259 return Complex_type::lookup_complex_type(name);
4262 // Class String_type.
4264 // Convert String_type to the backend representation. A string is a
4265 // struct with two fields: a pointer to the characters and a length.
4267 Btype*
4268 String_type::do_get_backend(Gogo* gogo)
4270 static Btype* backend_string_type;
4271 if (backend_string_type == NULL)
4273 std::vector<Backend::Btyped_identifier> fields(2);
4275 Type* b = gogo->lookup_global("byte")->type_value();
4276 Type* pb = Type::make_pointer_type(b);
4278 // We aren't going to get back to this field to finish the
4279 // backend representation, so force it to be finished now.
4280 if (!gogo->named_types_are_converted())
4282 Btype* bt = pb->get_backend_placeholder(gogo);
4283 pb->finish_backend(gogo, bt);
4286 fields[0].name = "__data";
4287 fields[0].btype = pb->get_backend(gogo);
4288 fields[0].location = Linemap::predeclared_location();
4290 Type* int_type = Type::lookup_integer_type("int");
4291 fields[1].name = "__length";
4292 fields[1].btype = int_type->get_backend(gogo);
4293 fields[1].location = fields[0].location;
4295 backend_string_type = gogo->backend()->struct_type(fields);
4297 return backend_string_type;
4300 // The type descriptor for the string type.
4302 Expression*
4303 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4305 if (name != NULL)
4306 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4307 else
4309 Named_object* no = gogo->lookup_global("string");
4310 go_assert(no != NULL);
4311 return Type::type_descriptor(gogo, no->type_value());
4315 // We should not be asked for the reflection string of a basic type.
4317 void
4318 String_type::do_reflection(Gogo*, std::string* ret) const
4320 ret->append("string");
4323 // Make a string type.
4325 Type*
4326 Type::make_string_type()
4328 static String_type string_type;
4329 return &string_type;
4332 // The named type "string".
4334 static Named_type* named_string_type;
4336 // Get the named type "string".
4338 Named_type*
4339 Type::lookup_string_type()
4341 return named_string_type;
4344 // Make the named type string.
4346 Named_type*
4347 Type::make_named_string_type()
4349 Type* string_type = Type::make_string_type();
4350 Named_object* named_object =
4351 Named_object::make_type("string", NULL, string_type,
4352 Linemap::predeclared_location());
4353 Named_type* named_type = named_object->type_value();
4354 named_string_type = named_type;
4355 return named_type;
4358 // The sink type. This is the type of the blank identifier _. Any
4359 // type may be assigned to it.
4361 class Sink_type : public Type
4363 public:
4364 Sink_type()
4365 : Type(TYPE_SINK)
4368 protected:
4369 bool
4370 do_compare_is_identity(Gogo*)
4371 { return false; }
4373 Btype*
4374 do_get_backend(Gogo*)
4375 { go_unreachable(); }
4377 Expression*
4378 do_type_descriptor(Gogo*, Named_type*)
4379 { go_unreachable(); }
4381 void
4382 do_reflection(Gogo*, std::string*) const
4383 { go_unreachable(); }
4385 void
4386 do_mangled_name(Gogo*, std::string*) const
4387 { go_unreachable(); }
4390 // Make the sink type.
4392 Type*
4393 Type::make_sink_type()
4395 static Sink_type sink_type;
4396 return &sink_type;
4399 // Class Function_type.
4401 // Traversal.
4404 Function_type::do_traverse(Traverse* traverse)
4406 if (this->receiver_ != NULL
4407 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4408 return TRAVERSE_EXIT;
4409 if (this->parameters_ != NULL
4410 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4411 return TRAVERSE_EXIT;
4412 if (this->results_ != NULL
4413 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4414 return TRAVERSE_EXIT;
4415 return TRAVERSE_CONTINUE;
4418 // Returns whether T is a valid redeclaration of this type. If this
4419 // returns false, and REASON is not NULL, *REASON may be set to a
4420 // brief explanation of why it returned false.
4422 bool
4423 Function_type::is_valid_redeclaration(const Function_type* t,
4424 std::string* reason) const
4426 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4427 return false;
4429 // A redeclaration of a function is required to use the same names
4430 // for the receiver and parameters.
4431 if (this->receiver() != NULL
4432 && this->receiver()->name() != t->receiver()->name())
4434 if (reason != NULL)
4435 *reason = "receiver name changed";
4436 return false;
4439 const Typed_identifier_list* parms1 = this->parameters();
4440 const Typed_identifier_list* parms2 = t->parameters();
4441 if (parms1 != NULL)
4443 Typed_identifier_list::const_iterator p1 = parms1->begin();
4444 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4445 p2 != parms2->end();
4446 ++p2, ++p1)
4448 if (p1->name() != p2->name())
4450 if (reason != NULL)
4451 *reason = "parameter name changed";
4452 return false;
4455 // This is called at parse time, so we may have unknown
4456 // types.
4457 Type* t1 = p1->type()->forwarded();
4458 Type* t2 = p2->type()->forwarded();
4459 if (t1 != t2
4460 && t1->forward_declaration_type() != NULL
4461 && (t2->forward_declaration_type() == NULL
4462 || (t1->forward_declaration_type()->named_object()
4463 != t2->forward_declaration_type()->named_object())))
4464 return false;
4468 const Typed_identifier_list* results1 = this->results();
4469 const Typed_identifier_list* results2 = t->results();
4470 if (results1 != NULL)
4472 Typed_identifier_list::const_iterator res1 = results1->begin();
4473 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4474 res2 != results2->end();
4475 ++res2, ++res1)
4477 if (res1->name() != res2->name())
4479 if (reason != NULL)
4480 *reason = "result name changed";
4481 return false;
4484 // This is called at parse time, so we may have unknown
4485 // types.
4486 Type* t1 = res1->type()->forwarded();
4487 Type* t2 = res2->type()->forwarded();
4488 if (t1 != t2
4489 && t1->forward_declaration_type() != NULL
4490 && (t2->forward_declaration_type() == NULL
4491 || (t1->forward_declaration_type()->named_object()
4492 != t2->forward_declaration_type()->named_object())))
4493 return false;
4497 return true;
4500 // Check whether T is the same as this type.
4502 bool
4503 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4504 Cmp_tags cmp_tags, bool errors_are_identical,
4505 std::string* reason) const
4507 if (this->is_backend_function_type() != t->is_backend_function_type())
4508 return false;
4510 if (!ignore_receiver)
4512 const Typed_identifier* r1 = this->receiver();
4513 const Typed_identifier* r2 = t->receiver();
4514 if ((r1 != NULL) != (r2 != NULL))
4516 if (reason != NULL)
4517 *reason = _("different receiver types");
4518 return false;
4520 if (r1 != NULL)
4522 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4523 errors_are_identical, reason))
4525 if (reason != NULL && !reason->empty())
4526 *reason = "receiver: " + *reason;
4527 return false;
4532 const Typed_identifier_list* parms1 = this->parameters();
4533 if (parms1 != NULL && parms1->empty())
4534 parms1 = NULL;
4535 const Typed_identifier_list* parms2 = t->parameters();
4536 if (parms2 != NULL && parms2->empty())
4537 parms2 = NULL;
4538 if ((parms1 != NULL) != (parms2 != NULL))
4540 if (reason != NULL)
4541 *reason = _("different number of parameters");
4542 return false;
4544 if (parms1 != NULL)
4546 Typed_identifier_list::const_iterator p1 = parms1->begin();
4547 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4548 p2 != parms2->end();
4549 ++p2, ++p1)
4551 if (p1 == parms1->end())
4553 if (reason != NULL)
4554 *reason = _("different number of parameters");
4555 return false;
4558 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4559 errors_are_identical, NULL))
4561 if (reason != NULL)
4562 *reason = _("different parameter types");
4563 return false;
4566 if (p1 != parms1->end())
4568 if (reason != NULL)
4569 *reason = _("different number of parameters");
4570 return false;
4574 if (this->is_varargs() != t->is_varargs())
4576 if (reason != NULL)
4577 *reason = _("different varargs");
4578 return false;
4581 const Typed_identifier_list* results1 = this->results();
4582 if (results1 != NULL && results1->empty())
4583 results1 = NULL;
4584 const Typed_identifier_list* results2 = t->results();
4585 if (results2 != NULL && results2->empty())
4586 results2 = NULL;
4587 if ((results1 != NULL) != (results2 != NULL))
4589 if (reason != NULL)
4590 *reason = _("different number of results");
4591 return false;
4593 if (results1 != NULL)
4595 Typed_identifier_list::const_iterator res1 = results1->begin();
4596 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4597 res2 != results2->end();
4598 ++res2, ++res1)
4600 if (res1 == results1->end())
4602 if (reason != NULL)
4603 *reason = _("different number of results");
4604 return false;
4607 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4608 cmp_tags, errors_are_identical,
4609 NULL))
4611 if (reason != NULL)
4612 *reason = _("different result types");
4613 return false;
4616 if (res1 != results1->end())
4618 if (reason != NULL)
4619 *reason = _("different number of results");
4620 return false;
4624 return true;
4627 // Hash code.
4629 unsigned int
4630 Function_type::do_hash_for_method(Gogo* gogo) const
4632 unsigned int ret = 0;
4633 // We ignore the receiver type for hash codes, because we need to
4634 // get the same hash code for a method in an interface and a method
4635 // declared for a type. The former will not have a receiver.
4636 if (this->parameters_ != NULL)
4638 int shift = 1;
4639 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4640 p != this->parameters_->end();
4641 ++p, ++shift)
4642 ret += p->type()->hash_for_method(gogo) << shift;
4644 if (this->results_ != NULL)
4646 int shift = 2;
4647 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4648 p != this->results_->end();
4649 ++p, ++shift)
4650 ret += p->type()->hash_for_method(gogo) << shift;
4652 if (this->is_varargs_)
4653 ret += 1;
4654 ret <<= 4;
4655 return ret;
4658 // Hash result parameters.
4660 unsigned int
4661 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4663 unsigned int hash = 0;
4664 for (Typed_identifier_list::const_iterator p = t->begin();
4665 p != t->end();
4666 ++p)
4668 hash <<= 2;
4669 hash = Type::hash_string(p->name(), hash);
4670 hash += p->type()->hash_for_method(NULL);
4672 return hash;
4675 // Compare result parameters so that can map identical result
4676 // parameters to a single struct type.
4678 bool
4679 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4680 const Typed_identifier_list* b) const
4682 if (a->size() != b->size())
4683 return false;
4684 Typed_identifier_list::const_iterator pa = a->begin();
4685 for (Typed_identifier_list::const_iterator pb = b->begin();
4686 pb != b->end();
4687 ++pa, ++pb)
4689 if (pa->name() != pb->name()
4690 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4691 return false;
4693 return true;
4696 // Hash from results to a backend struct type.
4698 Function_type::Results_structs Function_type::results_structs;
4700 // Get the backend representation for a function type.
4702 Btype*
4703 Function_type::get_backend_fntype(Gogo* gogo)
4705 if (this->fnbtype_ == NULL)
4707 Backend::Btyped_identifier breceiver;
4708 if (this->receiver_ != NULL)
4710 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4712 // We always pass the address of the receiver parameter, in
4713 // order to make interface calls work with unknown types.
4714 Type* rtype = this->receiver_->type();
4715 if (rtype->points_to() == NULL)
4716 rtype = Type::make_pointer_type(rtype);
4717 breceiver.btype = rtype->get_backend(gogo);
4718 breceiver.location = this->receiver_->location();
4721 std::vector<Backend::Btyped_identifier> bparameters;
4722 if (this->parameters_ != NULL)
4724 bparameters.resize(this->parameters_->size());
4725 size_t i = 0;
4726 for (Typed_identifier_list::const_iterator p =
4727 this->parameters_->begin(); p != this->parameters_->end();
4728 ++p, ++i)
4730 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4731 bparameters[i].btype = p->type()->get_backend(gogo);
4732 bparameters[i].location = p->location();
4734 go_assert(i == bparameters.size());
4737 std::vector<Backend::Btyped_identifier> bresults;
4738 Btype* bresult_struct = NULL;
4739 if (this->results_ != NULL)
4741 bresults.resize(this->results_->size());
4742 size_t i = 0;
4743 for (Typed_identifier_list::const_iterator p =
4744 this->results_->begin();
4745 p != this->results_->end();
4746 ++p, ++i)
4748 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4749 bresults[i].btype = p->type()->get_backend(gogo);
4750 bresults[i].location = p->location();
4752 go_assert(i == bresults.size());
4754 if (this->results_->size() > 1)
4756 // Use the same results struct for all functions that
4757 // return the same set of results. This is useful to
4758 // unify calls to interface methods with other calls.
4759 std::pair<Typed_identifier_list*, Btype*> val;
4760 val.first = this->results_;
4761 val.second = NULL;
4762 std::pair<Results_structs::iterator, bool> ins =
4763 Function_type::results_structs.insert(val);
4764 if (ins.second)
4766 // Build a new struct type.
4767 Struct_field_list* sfl = new Struct_field_list;
4768 for (Typed_identifier_list::const_iterator p =
4769 this->results_->begin();
4770 p != this->results_->end();
4771 ++p)
4773 Typed_identifier tid = *p;
4774 if (tid.name().empty())
4775 tid = Typed_identifier("UNNAMED", tid.type(),
4776 tid.location());
4777 sfl->push_back(Struct_field(tid));
4779 Struct_type* st = Type::make_struct_type(sfl,
4780 this->location());
4781 st->set_is_struct_incomparable();
4782 ins.first->second = st->get_backend(gogo);
4784 bresult_struct = ins.first->second;
4788 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4789 bresults, bresult_struct,
4790 this->location());
4794 return this->fnbtype_;
4797 // Get the backend representation for a Go function type.
4799 Btype*
4800 Function_type::do_get_backend(Gogo* gogo)
4802 // When we do anything with a function value other than call it, it
4803 // is represented as a pointer to a struct whose first field is the
4804 // actual function. So that is what we return as the type of a Go
4805 // function.
4807 Location loc = this->location();
4808 Btype* struct_type =
4809 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4810 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4812 std::vector<Backend::Btyped_identifier> fields(1);
4813 fields[0].name = "code";
4814 fields[0].btype = this->get_backend_fntype(gogo);
4815 fields[0].location = loc;
4816 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4817 return gogo->backend()->error_type();
4818 return ptr_struct_type;
4821 // The type of a function type descriptor.
4823 Type*
4824 Function_type::make_function_type_descriptor_type()
4826 static Type* ret;
4827 if (ret == NULL)
4829 Type* tdt = Type::make_type_descriptor_type();
4830 Type* ptdt = Type::make_type_descriptor_ptr_type();
4832 Type* bool_type = Type::lookup_bool_type();
4834 Type* slice_type = Type::make_array_type(ptdt, NULL);
4836 Struct_type* s = Type::make_builtin_struct_type(4,
4837 "", tdt,
4838 "dotdotdot", bool_type,
4839 "in", slice_type,
4840 "out", slice_type);
4842 ret = Type::make_builtin_named_type("FuncType", s);
4845 return ret;
4848 // The type descriptor for a function type.
4850 Expression*
4851 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4853 Location bloc = Linemap::predeclared_location();
4855 Type* ftdt = Function_type::make_function_type_descriptor_type();
4857 const Struct_field_list* fields = ftdt->struct_type()->fields();
4859 Expression_list* vals = new Expression_list();
4860 vals->reserve(4);
4862 Struct_field_list::const_iterator p = fields->begin();
4863 go_assert(p->is_field_name("_type"));
4864 vals->push_back(this->type_descriptor_constructor(gogo,
4865 RUNTIME_TYPE_KIND_FUNC,
4866 name, NULL, true));
4868 ++p;
4869 go_assert(p->is_field_name("dotdotdot"));
4870 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4872 ++p;
4873 go_assert(p->is_field_name("in"));
4874 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4875 this->parameters()));
4877 ++p;
4878 go_assert(p->is_field_name("out"));
4879 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4880 this->results()));
4882 ++p;
4883 go_assert(p == fields->end());
4885 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4888 // Return a composite literal for the parameters or results of a type
4889 // descriptor.
4891 Expression*
4892 Function_type::type_descriptor_params(Type* params_type,
4893 const Typed_identifier* receiver,
4894 const Typed_identifier_list* params)
4896 Location bloc = Linemap::predeclared_location();
4898 if (receiver == NULL && params == NULL)
4899 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4901 Expression_list* vals = new Expression_list();
4902 vals->reserve((params == NULL ? 0 : params->size())
4903 + (receiver != NULL ? 1 : 0));
4905 if (receiver != NULL)
4906 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4908 if (params != NULL)
4910 for (Typed_identifier_list::const_iterator p = params->begin();
4911 p != params->end();
4912 ++p)
4913 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4916 return Expression::make_slice_composite_literal(params_type, vals, bloc);
4919 // The reflection string.
4921 void
4922 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4924 // FIXME: Turn this off until we straighten out the type of the
4925 // struct field used in a go statement which calls a method.
4926 // go_assert(this->receiver_ == NULL);
4928 ret->append("func");
4930 if (this->receiver_ != NULL)
4932 ret->push_back('(');
4933 this->append_reflection(this->receiver_->type(), gogo, ret);
4934 ret->push_back(')');
4937 ret->push_back('(');
4938 const Typed_identifier_list* params = this->parameters();
4939 if (params != NULL)
4941 bool is_varargs = this->is_varargs_;
4942 for (Typed_identifier_list::const_iterator p = params->begin();
4943 p != params->end();
4944 ++p)
4946 if (p != params->begin())
4947 ret->append(", ");
4948 if (!is_varargs || p + 1 != params->end())
4949 this->append_reflection(p->type(), gogo, ret);
4950 else
4952 ret->append("...");
4953 this->append_reflection(p->type()->array_type()->element_type(),
4954 gogo, ret);
4958 ret->push_back(')');
4960 const Typed_identifier_list* results = this->results();
4961 if (results != NULL && !results->empty())
4963 if (results->size() == 1)
4964 ret->push_back(' ');
4965 else
4966 ret->append(" (");
4967 for (Typed_identifier_list::const_iterator p = results->begin();
4968 p != results->end();
4969 ++p)
4971 if (p != results->begin())
4972 ret->append(", ");
4973 this->append_reflection(p->type(), gogo, ret);
4975 if (results->size() > 1)
4976 ret->push_back(')');
4980 // Export a function type.
4982 void
4983 Function_type::do_export(Export* exp) const
4985 // We don't write out the receiver. The only function types which
4986 // should have a receiver are the ones associated with explicitly
4987 // defined methods. For those the receiver type is written out by
4988 // Function::export_func.
4990 exp->write_c_string("(");
4991 bool first = true;
4992 if (this->parameters_ != NULL)
4994 bool is_varargs = this->is_varargs_;
4995 for (Typed_identifier_list::const_iterator p =
4996 this->parameters_->begin();
4997 p != this->parameters_->end();
4998 ++p)
5000 if (first)
5001 first = false;
5002 else
5003 exp->write_c_string(", ");
5004 exp->write_name(p->name());
5005 exp->write_c_string(" ");
5006 if (!is_varargs || p + 1 != this->parameters_->end())
5007 exp->write_type(p->type());
5008 else
5010 exp->write_c_string("...");
5011 exp->write_type(p->type()->array_type()->element_type());
5015 exp->write_c_string(")");
5017 const Typed_identifier_list* results = this->results_;
5018 if (results != NULL)
5020 exp->write_c_string(" ");
5021 if (results->size() == 1 && results->begin()->name().empty())
5022 exp->write_type(results->begin()->type());
5023 else
5025 first = true;
5026 exp->write_c_string("(");
5027 for (Typed_identifier_list::const_iterator p = results->begin();
5028 p != results->end();
5029 ++p)
5031 if (first)
5032 first = false;
5033 else
5034 exp->write_c_string(", ");
5035 exp->write_name(p->name());
5036 exp->write_c_string(" ");
5037 exp->write_type(p->type());
5039 exp->write_c_string(")");
5044 // Import a function type.
5046 Function_type*
5047 Function_type::do_import(Import* imp)
5049 imp->require_c_string("(");
5050 Typed_identifier_list* parameters;
5051 bool is_varargs = false;
5052 if (imp->peek_char() == ')')
5053 parameters = NULL;
5054 else
5056 parameters = new Typed_identifier_list();
5057 while (true)
5059 std::string name = imp->read_name();
5060 imp->require_c_string(" ");
5062 if (imp->match_c_string("..."))
5064 imp->advance(3);
5065 is_varargs = true;
5068 Type* ptype = imp->read_type();
5069 if (is_varargs)
5070 ptype = Type::make_array_type(ptype, NULL);
5071 parameters->push_back(Typed_identifier(name, ptype,
5072 imp->location()));
5073 if (imp->peek_char() != ',')
5074 break;
5075 go_assert(!is_varargs);
5076 imp->require_c_string(", ");
5079 imp->require_c_string(")");
5081 Typed_identifier_list* results;
5082 if (imp->peek_char() != ' ')
5083 results = NULL;
5084 else
5086 imp->advance(1);
5087 results = new Typed_identifier_list;
5088 if (imp->peek_char() != '(')
5090 Type* rtype = imp->read_type();
5091 results->push_back(Typed_identifier("", rtype, imp->location()));
5093 else
5095 imp->advance(1);
5096 while (true)
5098 std::string name = imp->read_name();
5099 imp->require_c_string(" ");
5100 Type* rtype = imp->read_type();
5101 results->push_back(Typed_identifier(name, rtype,
5102 imp->location()));
5103 if (imp->peek_char() != ',')
5104 break;
5105 imp->require_c_string(", ");
5107 imp->require_c_string(")");
5111 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5112 imp->location());
5113 if (is_varargs)
5114 ret->set_is_varargs();
5115 return ret;
5118 // Make a copy of a function type without a receiver.
5120 Function_type*
5121 Function_type::copy_without_receiver() const
5123 go_assert(this->is_method());
5124 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5125 this->results_,
5126 this->location_);
5127 if (this->is_varargs())
5128 ret->set_is_varargs();
5129 if (this->is_builtin())
5130 ret->set_is_builtin();
5131 return ret;
5134 // Make a copy of a function type with a receiver.
5136 Function_type*
5137 Function_type::copy_with_receiver(Type* receiver_type) const
5139 go_assert(!this->is_method());
5140 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5141 this->location_);
5142 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5143 this->results_,
5144 this->location_);
5145 if (this->is_varargs_)
5146 ret->set_is_varargs();
5147 return ret;
5150 // Make a copy of a function type with the receiver as the first
5151 // parameter.
5153 Function_type*
5154 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5156 go_assert(this->is_method());
5157 Typed_identifier_list* new_params = new Typed_identifier_list();
5158 Type* rtype = this->receiver_->type();
5159 if (want_pointer_receiver)
5160 rtype = Type::make_pointer_type(rtype);
5161 Typed_identifier receiver(this->receiver_->name(), rtype,
5162 this->receiver_->location());
5163 new_params->push_back(receiver);
5164 const Typed_identifier_list* orig_params = this->parameters_;
5165 if (orig_params != NULL && !orig_params->empty())
5167 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5168 p != orig_params->end();
5169 ++p)
5170 new_params->push_back(*p);
5172 return Type::make_function_type(NULL, new_params, this->results_,
5173 this->location_);
5176 // Make a copy of a function type ignoring any receiver and adding a
5177 // closure parameter.
5179 Function_type*
5180 Function_type::copy_with_names() const
5182 Typed_identifier_list* new_params = new Typed_identifier_list();
5183 const Typed_identifier_list* orig_params = this->parameters_;
5184 if (orig_params != NULL && !orig_params->empty())
5186 static int count;
5187 char buf[50];
5188 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5189 p != orig_params->end();
5190 ++p)
5192 snprintf(buf, sizeof buf, "pt.%u", count);
5193 ++count;
5194 new_params->push_back(Typed_identifier(buf, p->type(),
5195 p->location()));
5199 const Typed_identifier_list* orig_results = this->results_;
5200 Typed_identifier_list* new_results;
5201 if (orig_results == NULL || orig_results->empty())
5202 new_results = NULL;
5203 else
5205 new_results = new Typed_identifier_list();
5206 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5207 p != orig_results->end();
5208 ++p)
5209 new_results->push_back(Typed_identifier("", p->type(),
5210 p->location()));
5213 return Type::make_function_type(NULL, new_params, new_results,
5214 this->location());
5217 // Make a function type.
5219 Function_type*
5220 Type::make_function_type(Typed_identifier* receiver,
5221 Typed_identifier_list* parameters,
5222 Typed_identifier_list* results,
5223 Location location)
5225 return new Function_type(receiver, parameters, results, location);
5228 // Make a backend function type.
5230 Backend_function_type*
5231 Type::make_backend_function_type(Typed_identifier* receiver,
5232 Typed_identifier_list* parameters,
5233 Typed_identifier_list* results,
5234 Location location)
5236 return new Backend_function_type(receiver, parameters, results, location);
5239 // Class Pointer_type.
5241 // Traversal.
5244 Pointer_type::do_traverse(Traverse* traverse)
5246 return Type::traverse(this->to_type_, traverse);
5249 // Hash code.
5251 unsigned int
5252 Pointer_type::do_hash_for_method(Gogo* gogo) const
5254 return this->to_type_->hash_for_method(gogo) << 4;
5257 // Get the backend representation for a pointer type.
5259 Btype*
5260 Pointer_type::do_get_backend(Gogo* gogo)
5262 Btype* to_btype = this->to_type_->get_backend(gogo);
5263 return gogo->backend()->pointer_type(to_btype);
5266 // The type of a pointer type descriptor.
5268 Type*
5269 Pointer_type::make_pointer_type_descriptor_type()
5271 static Type* ret;
5272 if (ret == NULL)
5274 Type* tdt = Type::make_type_descriptor_type();
5275 Type* ptdt = Type::make_type_descriptor_ptr_type();
5277 Struct_type* s = Type::make_builtin_struct_type(2,
5278 "", tdt,
5279 "elem", ptdt);
5281 ret = Type::make_builtin_named_type("PtrType", s);
5284 return ret;
5287 // The type descriptor for a pointer type.
5289 Expression*
5290 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5292 if (this->is_unsafe_pointer_type())
5294 go_assert(name != NULL);
5295 return this->plain_type_descriptor(gogo,
5296 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5297 name);
5299 else
5301 Location bloc = Linemap::predeclared_location();
5303 const Methods* methods;
5304 Type* deref = this->points_to();
5305 if (deref->named_type() != NULL)
5306 methods = deref->named_type()->methods();
5307 else if (deref->struct_type() != NULL)
5308 methods = deref->struct_type()->methods();
5309 else
5310 methods = NULL;
5312 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5314 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5316 Expression_list* vals = new Expression_list();
5317 vals->reserve(2);
5319 Struct_field_list::const_iterator p = fields->begin();
5320 go_assert(p->is_field_name("_type"));
5321 vals->push_back(this->type_descriptor_constructor(gogo,
5322 RUNTIME_TYPE_KIND_PTR,
5323 name, methods, false));
5325 ++p;
5326 go_assert(p->is_field_name("elem"));
5327 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5329 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5333 // Reflection string.
5335 void
5336 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5338 ret->push_back('*');
5339 this->append_reflection(this->to_type_, gogo, ret);
5342 // Export.
5344 void
5345 Pointer_type::do_export(Export* exp) const
5347 exp->write_c_string("*");
5348 if (this->is_unsafe_pointer_type())
5349 exp->write_c_string("any");
5350 else
5351 exp->write_type(this->to_type_);
5354 // Import.
5356 Pointer_type*
5357 Pointer_type::do_import(Import* imp)
5359 imp->require_c_string("*");
5360 if (imp->match_c_string("any"))
5362 imp->advance(3);
5363 return Type::make_pointer_type(Type::make_void_type());
5365 Type* to = imp->read_type();
5366 return Type::make_pointer_type(to);
5369 // Cache of pointer types. Key is "to" type, value is pointer type
5370 // that points to key.
5372 Type::Pointer_type_table Type::pointer_types;
5374 // A list of placeholder pointer types. We keep this so we can ensure
5375 // they are finalized.
5377 std::vector<Pointer_type*> Type::placeholder_pointers;
5379 // Make a pointer type.
5381 Pointer_type*
5382 Type::make_pointer_type(Type* to_type)
5384 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5385 if (p != pointer_types.end())
5386 return p->second;
5387 Pointer_type* ret = new Pointer_type(to_type);
5388 pointer_types[to_type] = ret;
5389 return ret;
5392 // This helper is invoked immediately after named types have been
5393 // converted, to clean up any unresolved pointer types remaining in
5394 // the pointer type cache.
5396 // The motivation for this routine: occasionally the compiler creates
5397 // some specific pointer type as part of a lowering operation (ex:
5398 // pointer-to-void), then Type::backend_type_size() is invoked on the
5399 // type (which creates a Btype placeholder for it), that placeholder
5400 // passed somewhere along the line to the back end, but since there is
5401 // no reference to the type in user code, there is never a call to
5402 // Type::finish_backend for the type (hence the Btype remains as an
5403 // unresolved placeholder). Calling this routine will clean up such
5404 // instances.
5406 void
5407 Type::finish_pointer_types(Gogo* gogo)
5409 // We don't use begin() and end() because it is possible to add new
5410 // placeholder pointer types as we finalized existing ones.
5411 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5413 Pointer_type* pt = Type::placeholder_pointers[i];
5414 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5415 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5417 pt->finish_backend(gogo, tbti->second.btype);
5418 tbti->second.is_placeholder = false;
5423 // Class Nil_type.
5425 // Get the backend representation of a nil type. FIXME: Is this ever
5426 // actually called?
5428 Btype*
5429 Nil_type::do_get_backend(Gogo* gogo)
5431 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5434 // Make the nil type.
5436 Type*
5437 Type::make_nil_type()
5439 static Nil_type singleton_nil_type;
5440 return &singleton_nil_type;
5443 // The type of a function call which returns multiple values. This is
5444 // really a struct, but we don't want to confuse a function call which
5445 // returns a struct with a function call which returns multiple
5446 // values.
5448 class Call_multiple_result_type : public Type
5450 public:
5451 Call_multiple_result_type(Call_expression* call)
5452 : Type(TYPE_CALL_MULTIPLE_RESULT),
5453 call_(call)
5456 protected:
5457 bool
5458 do_has_pointer() const
5459 { return false; }
5461 bool
5462 do_compare_is_identity(Gogo*)
5463 { return false; }
5465 Btype*
5466 do_get_backend(Gogo* gogo)
5468 go_assert(saw_errors());
5469 return gogo->backend()->error_type();
5472 Expression*
5473 do_type_descriptor(Gogo*, Named_type*)
5475 go_assert(saw_errors());
5476 return Expression::make_error(Linemap::unknown_location());
5479 void
5480 do_reflection(Gogo*, std::string*) const
5481 { go_assert(saw_errors()); }
5483 void
5484 do_mangled_name(Gogo*, std::string*) const
5485 { go_assert(saw_errors()); }
5487 private:
5488 // The expression being called.
5489 Call_expression* call_;
5492 // Make a call result type.
5494 Type*
5495 Type::make_call_multiple_result_type(Call_expression* call)
5497 return new Call_multiple_result_type(call);
5500 // Class Struct_field.
5502 // Get the name of a field.
5504 const std::string&
5505 Struct_field::field_name() const
5507 const std::string& name(this->typed_identifier_.name());
5508 if (!name.empty())
5509 return name;
5510 else
5512 // This is called during parsing, before anything is lowered, so
5513 // we have to be pretty careful to avoid dereferencing an
5514 // unknown type name.
5515 Type* t = this->typed_identifier_.type();
5516 Type* dt = t;
5517 if (t->classification() == Type::TYPE_POINTER)
5519 // Very ugly.
5520 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5521 dt = ptype->points_to();
5523 if (dt->forward_declaration_type() != NULL)
5524 return dt->forward_declaration_type()->name();
5525 else if (dt->named_type() != NULL)
5527 // Note that this can be an alias name.
5528 return dt->named_type()->name();
5530 else if (t->is_error_type() || dt->is_error_type())
5532 static const std::string error_string = "*error*";
5533 return error_string;
5535 else
5537 // Avoid crashing in the erroneous case where T is named but
5538 // DT is not.
5539 go_assert(t != dt);
5540 if (t->forward_declaration_type() != NULL)
5541 return t->forward_declaration_type()->name();
5542 else if (t->named_type() != NULL)
5543 return t->named_type()->name();
5544 else
5545 go_unreachable();
5550 // Return whether this field is named NAME.
5552 bool
5553 Struct_field::is_field_name(const std::string& name) const
5555 const std::string& me(this->typed_identifier_.name());
5556 if (!me.empty())
5557 return me == name;
5558 else
5560 Type* t = this->typed_identifier_.type();
5561 if (t->points_to() != NULL)
5562 t = t->points_to();
5563 Named_type* nt = t->named_type();
5564 if (nt != NULL && nt->name() == name)
5565 return true;
5567 // This is a horrible hack caused by the fact that we don't pack
5568 // the names of builtin types. FIXME.
5569 if (!this->is_imported_
5570 && nt != NULL
5571 && nt->is_builtin()
5572 && nt->name() == Gogo::unpack_hidden_name(name))
5573 return true;
5575 return false;
5579 // Return whether this field is an unexported field named NAME.
5581 bool
5582 Struct_field::is_unexported_field_name(Gogo* gogo,
5583 const std::string& name) const
5585 const std::string& field_name(this->field_name());
5586 if (Gogo::is_hidden_name(field_name)
5587 && name == Gogo::unpack_hidden_name(field_name)
5588 && gogo->pack_hidden_name(name, false) != field_name)
5589 return true;
5591 // Check for the name of a builtin type. This is like the test in
5592 // is_field_name, only there we return false if this->is_imported_,
5593 // and here we return true.
5594 if (this->is_imported_ && this->is_anonymous())
5596 Type* t = this->typed_identifier_.type();
5597 if (t->points_to() != NULL)
5598 t = t->points_to();
5599 Named_type* nt = t->named_type();
5600 if (nt != NULL
5601 && nt->is_builtin()
5602 && nt->name() == Gogo::unpack_hidden_name(name))
5603 return true;
5606 return false;
5609 // Return whether this field is an embedded built-in type.
5611 bool
5612 Struct_field::is_embedded_builtin(Gogo* gogo) const
5614 const std::string& name(this->field_name());
5615 // We know that a field is an embedded type if it is anonymous.
5616 // We can decide if it is a built-in type by checking to see if it is
5617 // registered globally under the field's name.
5618 // This allows us to distinguish between embedded built-in types and
5619 // embedded types that are aliases to built-in types.
5620 return (this->is_anonymous()
5621 && !Gogo::is_hidden_name(name)
5622 && gogo->lookup_global(name.c_str()) != NULL);
5625 // Class Struct_type.
5627 // A hash table used to find identical unnamed structs so that they
5628 // share method tables.
5630 Struct_type::Identical_structs Struct_type::identical_structs;
5632 // A hash table used to merge method sets for identical unnamed
5633 // structs.
5635 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5637 // Traversal.
5640 Struct_type::do_traverse(Traverse* traverse)
5642 Struct_field_list* fields = this->fields_;
5643 if (fields != NULL)
5645 for (Struct_field_list::iterator p = fields->begin();
5646 p != fields->end();
5647 ++p)
5649 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5650 return TRAVERSE_EXIT;
5653 return TRAVERSE_CONTINUE;
5656 // Verify that the struct type is complete and valid.
5658 bool
5659 Struct_type::do_verify()
5661 Struct_field_list* fields = this->fields_;
5662 if (fields == NULL)
5663 return true;
5664 for (Struct_field_list::iterator p = fields->begin();
5665 p != fields->end();
5666 ++p)
5668 Type* t = p->type();
5669 if (p->is_anonymous())
5671 if ((t->named_type() != NULL && t->points_to() != NULL)
5672 || (t->named_type() == NULL && t->points_to() != NULL
5673 && t->points_to()->points_to() != NULL))
5675 go_error_at(p->location(), "embedded type may not be a pointer");
5676 p->set_type(Type::make_error_type());
5678 else if (t->points_to() != NULL
5679 && t->points_to()->interface_type() != NULL)
5681 go_error_at(p->location(),
5682 "embedded type may not be pointer to interface");
5683 p->set_type(Type::make_error_type());
5687 return true;
5690 // Whether this contains a pointer.
5692 bool
5693 Struct_type::do_has_pointer() const
5695 const Struct_field_list* fields = this->fields();
5696 if (fields == NULL)
5697 return false;
5698 for (Struct_field_list::const_iterator p = fields->begin();
5699 p != fields->end();
5700 ++p)
5702 if (p->type()->has_pointer())
5703 return true;
5705 return false;
5708 // Whether this type is identical to T.
5710 bool
5711 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5712 bool errors_are_identical) const
5714 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5715 return false;
5716 const Struct_field_list* fields1 = this->fields();
5717 const Struct_field_list* fields2 = t->fields();
5718 if (fields1 == NULL || fields2 == NULL)
5719 return fields1 == fields2;
5720 Struct_field_list::const_iterator pf2 = fields2->begin();
5721 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5722 pf1 != fields1->end();
5723 ++pf1, ++pf2)
5725 if (pf2 == fields2->end())
5726 return false;
5727 if (pf1->field_name() != pf2->field_name())
5728 return false;
5729 if (pf1->is_anonymous() != pf2->is_anonymous()
5730 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5731 errors_are_identical, NULL))
5732 return false;
5733 if (cmp_tags == COMPARE_TAGS)
5735 if (!pf1->has_tag())
5737 if (pf2->has_tag())
5738 return false;
5740 else
5742 if (!pf2->has_tag())
5743 return false;
5744 if (pf1->tag() != pf2->tag())
5745 return false;
5749 if (pf2 != fields2->end())
5750 return false;
5751 return true;
5754 // Whether comparisons of this struct type are simple identity
5755 // comparisons.
5757 bool
5758 Struct_type::do_compare_is_identity(Gogo* gogo)
5760 const Struct_field_list* fields = this->fields_;
5761 if (fields == NULL)
5762 return true;
5763 int64_t offset = 0;
5764 for (Struct_field_list::const_iterator pf = fields->begin();
5765 pf != fields->end();
5766 ++pf)
5768 if (Gogo::is_sink_name(pf->field_name()))
5769 return false;
5771 if (!pf->type()->compare_is_identity(gogo))
5772 return false;
5774 int64_t field_align;
5775 if (!pf->type()->backend_type_align(gogo, &field_align))
5776 return false;
5777 if ((offset & (field_align - 1)) != 0)
5779 // This struct has padding. We don't guarantee that that
5780 // padding is zero-initialized for a stack variable, so we
5781 // can't use memcmp to compare struct values.
5782 return false;
5785 int64_t field_size;
5786 if (!pf->type()->backend_type_size(gogo, &field_size))
5787 return false;
5788 offset += field_size;
5791 int64_t struct_size;
5792 if (!this->backend_type_size(gogo, &struct_size))
5793 return false;
5794 if (offset != struct_size)
5796 // Trailing padding may not be zero when on the stack.
5797 return false;
5800 return true;
5803 // Return whether this struct type is reflexive--whether a value of
5804 // this type is always equal to itself.
5806 bool
5807 Struct_type::do_is_reflexive()
5809 const Struct_field_list* fields = this->fields_;
5810 if (fields == NULL)
5811 return true;
5812 for (Struct_field_list::const_iterator pf = fields->begin();
5813 pf != fields->end();
5814 ++pf)
5816 if (!pf->type()->is_reflexive())
5817 return false;
5819 return true;
5822 // Return whether this struct type needs a key update when used as a
5823 // map key.
5825 bool
5826 Struct_type::do_needs_key_update()
5828 const Struct_field_list* fields = this->fields_;
5829 if (fields == NULL)
5830 return false;
5831 for (Struct_field_list::const_iterator pf = fields->begin();
5832 pf != fields->end();
5833 ++pf)
5835 if (pf->type()->needs_key_update())
5836 return true;
5838 return false;
5841 // Return whether this struct type is permitted to be in the heap.
5843 bool
5844 Struct_type::do_in_heap()
5846 const Struct_field_list* fields = this->fields_;
5847 if (fields == NULL)
5848 return true;
5849 for (Struct_field_list::const_iterator pf = fields->begin();
5850 pf != fields->end();
5851 ++pf)
5853 if (!pf->type()->in_heap())
5854 return false;
5856 return true;
5859 // Build identity and hash functions for this struct.
5861 // Hash code.
5863 unsigned int
5864 Struct_type::do_hash_for_method(Gogo* gogo) const
5866 unsigned int ret = 0;
5867 if (this->fields() != NULL)
5869 for (Struct_field_list::const_iterator pf = this->fields()->begin();
5870 pf != this->fields()->end();
5871 ++pf)
5872 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5874 ret <<= 2;
5875 if (this->is_struct_incomparable_)
5876 ret <<= 1;
5877 return ret;
5880 // Find the local field NAME.
5882 const Struct_field*
5883 Struct_type::find_local_field(const std::string& name,
5884 unsigned int *pindex) const
5886 const Struct_field_list* fields = this->fields_;
5887 if (fields == NULL)
5888 return NULL;
5889 unsigned int i = 0;
5890 for (Struct_field_list::const_iterator pf = fields->begin();
5891 pf != fields->end();
5892 ++pf, ++i)
5894 if (pf->is_field_name(name))
5896 if (pindex != NULL)
5897 *pindex = i;
5898 return &*pf;
5901 return NULL;
5904 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5906 Field_reference_expression*
5907 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5908 Location location) const
5910 unsigned int depth;
5911 return this->field_reference_depth(struct_expr, name, location, NULL,
5912 &depth);
5915 // Return an expression for a field, along with the depth at which it
5916 // was found.
5918 Field_reference_expression*
5919 Struct_type::field_reference_depth(Expression* struct_expr,
5920 const std::string& name,
5921 Location location,
5922 Saw_named_type* saw,
5923 unsigned int* depth) const
5925 const Struct_field_list* fields = this->fields_;
5926 if (fields == NULL)
5927 return NULL;
5929 // Look for a field with this name.
5930 unsigned int i = 0;
5931 for (Struct_field_list::const_iterator pf = fields->begin();
5932 pf != fields->end();
5933 ++pf, ++i)
5935 if (pf->is_field_name(name))
5937 *depth = 0;
5938 return Expression::make_field_reference(struct_expr, i, location);
5942 // Look for an anonymous field which contains a field with this
5943 // name.
5944 unsigned int found_depth = 0;
5945 Field_reference_expression* ret = NULL;
5946 i = 0;
5947 for (Struct_field_list::const_iterator pf = fields->begin();
5948 pf != fields->end();
5949 ++pf, ++i)
5951 if (!pf->is_anonymous())
5952 continue;
5954 Struct_type* st = pf->type()->deref()->struct_type();
5955 if (st == NULL)
5956 continue;
5958 Saw_named_type* hold_saw = saw;
5959 Saw_named_type saw_here;
5960 Named_type* nt = pf->type()->named_type();
5961 if (nt == NULL)
5962 nt = pf->type()->deref()->named_type();
5963 if (nt != NULL)
5965 Saw_named_type* q;
5966 for (q = saw; q != NULL; q = q->next)
5968 if (q->nt == nt)
5970 // If this is an error, it will be reported
5971 // elsewhere.
5972 break;
5975 if (q != NULL)
5976 continue;
5977 saw_here.next = saw;
5978 saw_here.nt = nt;
5979 saw = &saw_here;
5982 // Look for a reference using a NULL struct expression. If we
5983 // find one, fill in the struct expression with a reference to
5984 // this field.
5985 unsigned int subdepth;
5986 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
5987 location,
5988 saw,
5989 &subdepth);
5991 saw = hold_saw;
5993 if (sub == NULL)
5994 continue;
5996 if (ret == NULL || subdepth < found_depth)
5998 if (ret != NULL)
5999 delete ret;
6000 ret = sub;
6001 found_depth = subdepth;
6002 Expression* here = Expression::make_field_reference(struct_expr, i,
6003 location);
6004 if (pf->type()->points_to() != NULL)
6005 here = Expression::make_dereference(here,
6006 Expression::NIL_CHECK_DEFAULT,
6007 location);
6008 while (sub->expr() != NULL)
6010 sub = sub->expr()->deref()->field_reference_expression();
6011 go_assert(sub != NULL);
6013 sub->set_struct_expression(here);
6014 sub->set_implicit(true);
6016 else if (subdepth > found_depth)
6017 delete sub;
6018 else
6020 // We do not handle ambiguity here--it should be handled by
6021 // Type::bind_field_or_method.
6022 delete sub;
6023 found_depth = 0;
6024 ret = NULL;
6028 if (ret != NULL)
6029 *depth = found_depth + 1;
6031 return ret;
6034 // Return the total number of fields, including embedded fields.
6036 unsigned int
6037 Struct_type::total_field_count() const
6039 if (this->fields_ == NULL)
6040 return 0;
6041 unsigned int ret = 0;
6042 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6043 pf != this->fields_->end();
6044 ++pf)
6046 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6047 ++ret;
6048 else
6049 ret += pf->type()->struct_type()->total_field_count();
6051 return ret;
6054 // Return whether NAME is an unexported field, for better error reporting.
6056 bool
6057 Struct_type::is_unexported_local_field(Gogo* gogo,
6058 const std::string& name) const
6060 const Struct_field_list* fields = this->fields_;
6061 if (fields != NULL)
6063 for (Struct_field_list::const_iterator pf = fields->begin();
6064 pf != fields->end();
6065 ++pf)
6066 if (pf->is_unexported_field_name(gogo, name))
6067 return true;
6069 return false;
6072 // Finalize the methods of an unnamed struct.
6074 void
6075 Struct_type::finalize_methods(Gogo* gogo)
6077 if (this->all_methods_ != NULL)
6078 return;
6080 // It is possible to have multiple identical structs that have
6081 // methods. We want them to share method tables. Otherwise we will
6082 // emit identical methods more than once, which is bad since they
6083 // will even have the same names.
6084 std::pair<Identical_structs::iterator, bool> ins =
6085 Struct_type::identical_structs.insert(std::make_pair(this, this));
6086 if (!ins.second)
6088 // An identical struct was already entered into the hash table.
6089 // Note that finalize_methods is, fortunately, not recursive.
6090 this->all_methods_ = ins.first->second->all_methods_;
6091 return;
6094 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6097 // Return the method NAME, or NULL if there isn't one or if it is
6098 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6099 // ambiguous.
6101 Method*
6102 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6104 return Type::method_function(this->all_methods_, name, is_ambiguous);
6107 // Return a pointer to the interface method table for this type for
6108 // the interface INTERFACE. IS_POINTER is true if this is for a
6109 // pointer to THIS.
6111 Expression*
6112 Struct_type::interface_method_table(Interface_type* interface,
6113 bool is_pointer)
6115 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6116 val(this, NULL);
6117 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6118 Struct_type::struct_method_tables.insert(val);
6120 Struct_method_table_pair* smtp;
6121 if (!ins.second)
6122 smtp = ins.first->second;
6123 else
6125 smtp = new Struct_method_table_pair();
6126 smtp->first = NULL;
6127 smtp->second = NULL;
6128 ins.first->second = smtp;
6131 return Type::interface_method_table(this, interface, is_pointer,
6132 &smtp->first, &smtp->second);
6135 // Convert struct fields to the backend representation. This is not
6136 // declared in types.h so that types.h doesn't have to #include
6137 // backend.h.
6139 static void
6140 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6141 bool use_placeholder,
6142 std::vector<Backend::Btyped_identifier>* bfields)
6144 bfields->resize(fields->size());
6145 size_t i = 0;
6146 for (Struct_field_list::const_iterator p = fields->begin();
6147 p != fields->end();
6148 ++p, ++i)
6150 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6151 (*bfields)[i].btype = (use_placeholder
6152 ? p->type()->get_backend_placeholder(gogo)
6153 : p->type()->get_backend(gogo));
6154 (*bfields)[i].location = p->location();
6156 go_assert(i == fields->size());
6159 // Get the backend representation for a struct type.
6161 Btype*
6162 Struct_type::do_get_backend(Gogo* gogo)
6164 std::vector<Backend::Btyped_identifier> bfields;
6165 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6166 return gogo->backend()->struct_type(bfields);
6169 // Finish the backend representation of the fields of a struct.
6171 void
6172 Struct_type::finish_backend_fields(Gogo* gogo)
6174 const Struct_field_list* fields = this->fields_;
6175 if (fields != NULL)
6177 for (Struct_field_list::const_iterator p = fields->begin();
6178 p != fields->end();
6179 ++p)
6180 p->type()->get_backend(gogo);
6184 // The type of a struct type descriptor.
6186 Type*
6187 Struct_type::make_struct_type_descriptor_type()
6189 static Type* ret;
6190 if (ret == NULL)
6192 Type* tdt = Type::make_type_descriptor_type();
6193 Type* ptdt = Type::make_type_descriptor_ptr_type();
6195 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6196 Type* string_type = Type::lookup_string_type();
6197 Type* pointer_string_type = Type::make_pointer_type(string_type);
6199 Struct_type* sf =
6200 Type::make_builtin_struct_type(5,
6201 "name", pointer_string_type,
6202 "pkgPath", pointer_string_type,
6203 "typ", ptdt,
6204 "tag", pointer_string_type,
6205 "offsetAnon", uintptr_type);
6206 Type* nsf = Type::make_builtin_named_type("structField", sf);
6208 Type* slice_type = Type::make_array_type(nsf, NULL);
6210 Struct_type* s = Type::make_builtin_struct_type(2,
6211 "", tdt,
6212 "fields", slice_type);
6214 ret = Type::make_builtin_named_type("StructType", s);
6217 return ret;
6220 // Build a type descriptor for a struct type.
6222 Expression*
6223 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6225 Location bloc = Linemap::predeclared_location();
6227 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6229 const Struct_field_list* fields = stdt->struct_type()->fields();
6231 Expression_list* vals = new Expression_list();
6232 vals->reserve(2);
6234 const Methods* methods = this->methods();
6235 // A named struct should not have methods--the methods should attach
6236 // to the named type.
6237 go_assert(methods == NULL || name == NULL);
6239 Struct_field_list::const_iterator ps = fields->begin();
6240 go_assert(ps->is_field_name("_type"));
6241 vals->push_back(this->type_descriptor_constructor(gogo,
6242 RUNTIME_TYPE_KIND_STRUCT,
6243 name, methods, true));
6245 ++ps;
6246 go_assert(ps->is_field_name("fields"));
6248 Expression_list* elements = new Expression_list();
6249 elements->reserve(this->fields_->size());
6250 Type* element_type = ps->type()->array_type()->element_type();
6251 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6252 pf != this->fields_->end();
6253 ++pf)
6255 const Struct_field_list* f = element_type->struct_type()->fields();
6257 Expression_list* fvals = new Expression_list();
6258 fvals->reserve(5);
6260 Struct_field_list::const_iterator q = f->begin();
6261 go_assert(q->is_field_name("name"));
6262 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6263 Expression* s = Expression::make_string(n, bloc);
6264 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6266 ++q;
6267 go_assert(q->is_field_name("pkgPath"));
6268 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6269 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6270 fvals->push_back(Expression::make_nil(bloc));
6271 else
6273 std::string n;
6274 if (is_embedded_builtin)
6275 n = gogo->package_name();
6276 else
6277 n = Gogo::hidden_name_pkgpath(pf->field_name());
6278 Expression* s = Expression::make_string(n, bloc);
6279 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6282 ++q;
6283 go_assert(q->is_field_name("typ"));
6284 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6286 ++q;
6287 go_assert(q->is_field_name("tag"));
6288 if (!pf->has_tag())
6289 fvals->push_back(Expression::make_nil(bloc));
6290 else
6292 Expression* s = Expression::make_string(pf->tag(), bloc);
6293 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6296 ++q;
6297 go_assert(q->is_field_name("offsetAnon"));
6298 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6299 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6300 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6301 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6302 int av = pf->is_anonymous() ? 1 : 0;
6303 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6304 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6305 fvals->push_back(o);
6307 Expression* v = Expression::make_struct_composite_literal(element_type,
6308 fvals, bloc);
6309 elements->push_back(v);
6312 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6313 elements, bloc));
6315 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6318 // Write the hash function for a struct which can not use the identity
6319 // function.
6321 void
6322 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6323 Function_type* hash_fntype,
6324 Function_type* equal_fntype)
6326 Location bloc = Linemap::predeclared_location();
6328 // The pointer to the struct that we are going to hash. This is an
6329 // argument to the hash function we are implementing here.
6330 Named_object* key_arg = gogo->lookup("key", NULL);
6331 go_assert(key_arg != NULL);
6332 Type* key_arg_type = key_arg->var_value()->type();
6334 // The seed argument to the hash function.
6335 Named_object* seed_arg = gogo->lookup("seed", NULL);
6336 go_assert(seed_arg != NULL);
6338 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6340 // Make a temporary to hold the return value, initialized to the seed.
6341 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6342 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6343 bloc);
6344 gogo->add_statement(retval);
6346 // Make a temporary to hold the key as a uintptr.
6347 ref = Expression::make_var_reference(key_arg, bloc);
6348 ref = Expression::make_cast(uintptr_type, ref, bloc);
6349 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6350 bloc);
6351 gogo->add_statement(key);
6353 // Loop over the struct fields.
6354 const Struct_field_list* fields = this->fields_;
6355 for (Struct_field_list::const_iterator pf = fields->begin();
6356 pf != fields->end();
6357 ++pf)
6359 if (Gogo::is_sink_name(pf->field_name()))
6360 continue;
6362 // Get a pointer to the value of this field.
6363 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6364 ref = Expression::make_temporary_reference(key, bloc);
6365 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6366 bloc);
6367 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6369 // Get the hash function to use for the type of this field.
6370 Named_object* hash_fn;
6371 Named_object* equal_fn;
6372 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6373 equal_fntype, &hash_fn, &equal_fn);
6375 // Call the hash function for the field, passing retval as the seed.
6376 ref = Expression::make_temporary_reference(retval, bloc);
6377 Expression_list* args = new Expression_list();
6378 args->push_back(subkey);
6379 args->push_back(ref);
6380 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6381 Expression* call = Expression::make_call(func, args, false, bloc);
6383 // Set retval to the result.
6384 Temporary_reference_expression* tref =
6385 Expression::make_temporary_reference(retval, bloc);
6386 tref->set_is_lvalue();
6387 Statement* s = Statement::make_assignment(tref, call, bloc);
6388 gogo->add_statement(s);
6391 // Return retval to the caller of the hash function.
6392 Expression_list* vals = new Expression_list();
6393 ref = Expression::make_temporary_reference(retval, bloc);
6394 vals->push_back(ref);
6395 Statement* s = Statement::make_return_statement(vals, bloc);
6396 gogo->add_statement(s);
6399 // Write the equality function for a struct which can not use the
6400 // identity function.
6402 void
6403 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6405 Location bloc = Linemap::predeclared_location();
6407 // The pointers to the structs we are going to compare.
6408 Named_object* key1_arg = gogo->lookup("key1", NULL);
6409 Named_object* key2_arg = gogo->lookup("key2", NULL);
6410 go_assert(key1_arg != NULL && key2_arg != NULL);
6412 // Build temporaries with the right types.
6413 Type* pt = Type::make_pointer_type(name != NULL
6414 ? static_cast<Type*>(name)
6415 : static_cast<Type*>(this));
6417 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6418 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6419 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6420 gogo->add_statement(p1);
6422 ref = Expression::make_var_reference(key2_arg, bloc);
6423 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6424 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6425 gogo->add_statement(p2);
6427 const Struct_field_list* fields = this->fields_;
6428 unsigned int field_index = 0;
6429 for (Struct_field_list::const_iterator pf = fields->begin();
6430 pf != fields->end();
6431 ++pf, ++field_index)
6433 if (Gogo::is_sink_name(pf->field_name()))
6434 continue;
6436 // Compare one field in both P1 and P2.
6437 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6438 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6439 bloc);
6440 f1 = Expression::make_field_reference(f1, field_index, bloc);
6442 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6443 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6444 bloc);
6445 f2 = Expression::make_field_reference(f2, field_index, bloc);
6447 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6449 // If the values are not equal, return false.
6450 gogo->start_block(bloc);
6451 Expression_list* vals = new Expression_list();
6452 vals->push_back(Expression::make_boolean(false, bloc));
6453 Statement* s = Statement::make_return_statement(vals, bloc);
6454 gogo->add_statement(s);
6455 Block* then_block = gogo->finish_block(bloc);
6457 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6458 gogo->add_statement(s);
6461 // All the fields are equal, so return true.
6462 Expression_list* vals = new Expression_list();
6463 vals->push_back(Expression::make_boolean(true, bloc));
6464 Statement* s = Statement::make_return_statement(vals, bloc);
6465 gogo->add_statement(s);
6468 // Reflection string.
6470 void
6471 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6473 ret->append("struct {");
6475 for (Struct_field_list::const_iterator p = this->fields_->begin();
6476 p != this->fields_->end();
6477 ++p)
6479 if (p != this->fields_->begin())
6480 ret->push_back(';');
6481 ret->push_back(' ');
6482 if (!p->is_anonymous())
6484 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6485 ret->push_back(' ');
6487 if (p->is_anonymous()
6488 && p->type()->named_type() != NULL
6489 && p->type()->named_type()->is_alias())
6490 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6491 else
6492 this->append_reflection(p->type(), gogo, ret);
6494 if (p->has_tag())
6496 const std::string& tag(p->tag());
6497 ret->append(" \"");
6498 for (std::string::const_iterator p = tag.begin();
6499 p != tag.end();
6500 ++p)
6502 if (*p == '\0')
6503 ret->append("\\x00");
6504 else if (*p == '\n')
6505 ret->append("\\n");
6506 else if (*p == '\t')
6507 ret->append("\\t");
6508 else if (*p == '"')
6509 ret->append("\\\"");
6510 else if (*p == '\\')
6511 ret->append("\\\\");
6512 else
6513 ret->push_back(*p);
6515 ret->push_back('"');
6519 if (!this->fields_->empty())
6520 ret->push_back(' ');
6522 ret->push_back('}');
6525 // If the offset of field INDEX in the backend implementation can be
6526 // determined, set *POFFSET to the offset in bytes and return true.
6527 // Otherwise, return false.
6529 bool
6530 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6531 int64_t* poffset)
6533 if (!this->is_backend_type_size_known(gogo))
6534 return false;
6535 Btype* bt = this->get_backend_placeholder(gogo);
6536 *poffset = gogo->backend()->type_field_offset(bt, index);
6537 return true;
6540 // Export.
6542 void
6543 Struct_type::do_export(Export* exp) const
6545 exp->write_c_string("struct { ");
6546 const Struct_field_list* fields = this->fields_;
6547 go_assert(fields != NULL);
6548 for (Struct_field_list::const_iterator p = fields->begin();
6549 p != fields->end();
6550 ++p)
6552 if (p->is_anonymous())
6553 exp->write_string("? ");
6554 else
6556 exp->write_string(p->field_name());
6557 exp->write_c_string(" ");
6559 exp->write_type(p->type());
6561 if (p->has_tag())
6563 exp->write_c_string(" ");
6564 Expression* expr =
6565 Expression::make_string(p->tag(), Linemap::predeclared_location());
6566 expr->export_expression(exp);
6567 delete expr;
6570 exp->write_c_string("; ");
6572 exp->write_c_string("}");
6575 // Import.
6577 Struct_type*
6578 Struct_type::do_import(Import* imp)
6580 imp->require_c_string("struct { ");
6581 Struct_field_list* fields = new Struct_field_list;
6582 if (imp->peek_char() != '}')
6584 while (true)
6586 std::string name;
6587 if (imp->match_c_string("? "))
6588 imp->advance(2);
6589 else
6591 name = imp->read_identifier();
6592 imp->require_c_string(" ");
6594 Type* ftype = imp->read_type();
6596 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6597 sf.set_is_imported();
6599 if (imp->peek_char() == ' ')
6601 imp->advance(1);
6602 Expression* expr = Expression::import_expression(imp);
6603 String_expression* sexpr = expr->string_expression();
6604 go_assert(sexpr != NULL);
6605 sf.set_tag(sexpr->val());
6606 delete sexpr;
6609 imp->require_c_string("; ");
6610 fields->push_back(sf);
6611 if (imp->peek_char() == '}')
6612 break;
6615 imp->require_c_string("}");
6617 return Type::make_struct_type(fields, imp->location());
6620 // Whether we can write this struct type to a C header file.
6621 // We can't if any of the fields are structs defined in a different package.
6623 bool
6624 Struct_type::can_write_to_c_header(
6625 std::vector<const Named_object*>* requires,
6626 std::vector<const Named_object*>* declare) const
6628 const Struct_field_list* fields = this->fields_;
6629 if (fields == NULL || fields->empty())
6630 return false;
6631 int sinks = 0;
6632 for (Struct_field_list::const_iterator p = fields->begin();
6633 p != fields->end();
6634 ++p)
6636 if (p->is_anonymous())
6637 return false;
6638 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6639 return false;
6640 if (Gogo::message_name(p->field_name()) == "_")
6641 sinks++;
6643 if (sinks > 1)
6644 return false;
6645 return true;
6648 // Whether we can write the type T to a C header file.
6650 bool
6651 Struct_type::can_write_type_to_c_header(
6652 const Type* t,
6653 std::vector<const Named_object*>* requires,
6654 std::vector<const Named_object*>* declare) const
6656 t = t->forwarded();
6657 switch (t->classification())
6659 case TYPE_ERROR:
6660 case TYPE_FORWARD:
6661 return false;
6663 case TYPE_VOID:
6664 case TYPE_BOOLEAN:
6665 case TYPE_INTEGER:
6666 case TYPE_FLOAT:
6667 case TYPE_COMPLEX:
6668 case TYPE_STRING:
6669 case TYPE_FUNCTION:
6670 case TYPE_MAP:
6671 case TYPE_CHANNEL:
6672 case TYPE_INTERFACE:
6673 return true;
6675 case TYPE_POINTER:
6676 // Don't try to handle a pointer to an array.
6677 if (t->points_to()->array_type() != NULL
6678 && !t->points_to()->is_slice_type())
6679 return false;
6681 if (t->points_to()->named_type() != NULL
6682 && t->points_to()->struct_type() != NULL)
6683 declare->push_back(t->points_to()->named_type()->named_object());
6684 return true;
6686 case TYPE_STRUCT:
6687 return t->struct_type()->can_write_to_c_header(requires, declare);
6689 case TYPE_ARRAY:
6690 if (t->is_slice_type())
6691 return true;
6692 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6693 requires, declare);
6695 case TYPE_NAMED:
6697 const Named_object* no = t->named_type()->named_object();
6698 if (no->package() != NULL)
6700 if (t->is_unsafe_pointer_type())
6701 return true;
6702 return false;
6704 if (t->struct_type() != NULL)
6706 requires->push_back(no);
6707 return t->struct_type()->can_write_to_c_header(requires, declare);
6709 return this->can_write_type_to_c_header(t->base(), requires, declare);
6712 case TYPE_CALL_MULTIPLE_RESULT:
6713 case TYPE_NIL:
6714 case TYPE_SINK:
6715 default:
6716 go_unreachable();
6720 // Write this struct to a C header file.
6722 void
6723 Struct_type::write_to_c_header(std::ostream& os) const
6725 const Struct_field_list* fields = this->fields_;
6726 for (Struct_field_list::const_iterator p = fields->begin();
6727 p != fields->end();
6728 ++p)
6730 os << '\t';
6731 this->write_field_to_c_header(os, p->field_name(), p->type());
6732 os << ';' << std::endl;
6736 // Write the type of a struct field to a C header file.
6738 void
6739 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6740 const Type *t) const
6742 bool print_name = true;
6743 t = t->forwarded();
6744 switch (t->classification())
6746 case TYPE_VOID:
6747 os << "void";
6748 break;
6750 case TYPE_BOOLEAN:
6751 os << "_Bool";
6752 break;
6754 case TYPE_INTEGER:
6756 const Integer_type* it = t->integer_type();
6757 if (it->is_unsigned())
6758 os << 'u';
6759 os << "int" << it->bits() << "_t";
6761 break;
6763 case TYPE_FLOAT:
6764 switch (t->float_type()->bits())
6766 case 32:
6767 os << "float";
6768 break;
6769 case 64:
6770 os << "double";
6771 break;
6772 default:
6773 go_unreachable();
6775 break;
6777 case TYPE_COMPLEX:
6778 switch (t->complex_type()->bits())
6780 case 64:
6781 os << "float _Complex";
6782 break;
6783 case 128:
6784 os << "double _Complex";
6785 break;
6786 default:
6787 go_unreachable();
6789 break;
6791 case TYPE_STRING:
6792 os << "String";
6793 break;
6795 case TYPE_FUNCTION:
6796 os << "FuncVal*";
6797 break;
6799 case TYPE_POINTER:
6801 std::vector<const Named_object*> requires;
6802 std::vector<const Named_object*> declare;
6803 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6804 &declare))
6805 os << "void*";
6806 else
6808 this->write_field_to_c_header(os, "", t->points_to());
6809 os << '*';
6812 break;
6814 case TYPE_MAP:
6815 os << "Map*";
6816 break;
6818 case TYPE_CHANNEL:
6819 os << "Chan*";
6820 break;
6822 case TYPE_INTERFACE:
6823 if (t->interface_type()->is_empty())
6824 os << "Eface";
6825 else
6826 os << "Iface";
6827 break;
6829 case TYPE_STRUCT:
6830 os << "struct {" << std::endl;
6831 t->struct_type()->write_to_c_header(os);
6832 os << "\t}";
6833 break;
6835 case TYPE_ARRAY:
6836 if (t->is_slice_type())
6837 os << "Slice";
6838 else
6840 const Type *ele = t;
6841 std::vector<const Type*> array_types;
6842 while (ele->array_type() != NULL && !ele->is_slice_type())
6844 array_types.push_back(ele);
6845 ele = ele->array_type()->element_type();
6847 this->write_field_to_c_header(os, "", ele);
6848 os << ' ' << Gogo::message_name(name);
6849 print_name = false;
6850 while (!array_types.empty())
6852 ele = array_types.back();
6853 array_types.pop_back();
6854 os << '[';
6855 Numeric_constant nc;
6856 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6857 go_unreachable();
6858 mpz_t val;
6859 if (!nc.to_int(&val))
6860 go_unreachable();
6861 char* s = mpz_get_str(NULL, 10, val);
6862 os << s;
6863 free(s);
6864 mpz_clear(val);
6865 os << ']';
6868 break;
6870 case TYPE_NAMED:
6872 const Named_object* no = t->named_type()->named_object();
6873 if (t->struct_type() != NULL)
6874 os << "struct " << no->message_name();
6875 else if (t->is_unsafe_pointer_type())
6876 os << "void*";
6877 else if (t == Type::lookup_integer_type("uintptr"))
6878 os << "uintptr_t";
6879 else
6881 this->write_field_to_c_header(os, name, t->base());
6882 print_name = false;
6885 break;
6887 case TYPE_ERROR:
6888 case TYPE_FORWARD:
6889 case TYPE_CALL_MULTIPLE_RESULT:
6890 case TYPE_NIL:
6891 case TYPE_SINK:
6892 default:
6893 go_unreachable();
6896 if (print_name && !name.empty())
6897 os << ' ' << Gogo::message_name(name);
6900 // Make a struct type.
6902 Struct_type*
6903 Type::make_struct_type(Struct_field_list* fields,
6904 Location location)
6906 return new Struct_type(fields, location);
6909 // Class Array_type.
6911 // Store the length of an array as an int64_t into *PLEN. Return
6912 // false if the length can not be determined. This will assert if
6913 // called for a slice.
6915 bool
6916 Array_type::int_length(int64_t* plen)
6918 go_assert(this->length_ != NULL);
6919 Numeric_constant nc;
6920 if (!this->length_->numeric_constant_value(&nc))
6921 return false;
6922 return nc.to_memory_size(plen);
6925 // Whether two array types are identical.
6927 bool
6928 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6929 bool errors_are_identical) const
6931 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6932 cmp_tags, errors_are_identical, NULL))
6933 return false;
6935 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6936 return false;
6938 Expression* l1 = this->length();
6939 Expression* l2 = t->length();
6941 // Slices of the same element type are identical.
6942 if (l1 == NULL && l2 == NULL)
6943 return true;
6945 // Arrays of the same element type are identical if they have the
6946 // same length.
6947 if (l1 != NULL && l2 != NULL)
6949 if (l1 == l2)
6950 return true;
6952 // Try to determine the lengths. If we can't, assume the arrays
6953 // are not identical.
6954 bool ret = false;
6955 Numeric_constant nc1, nc2;
6956 if (l1->numeric_constant_value(&nc1)
6957 && l2->numeric_constant_value(&nc2))
6959 mpz_t v1;
6960 if (nc1.to_int(&v1))
6962 mpz_t v2;
6963 if (nc2.to_int(&v2))
6965 ret = mpz_cmp(v1, v2) == 0;
6966 mpz_clear(v2);
6968 mpz_clear(v1);
6971 return ret;
6974 // Otherwise the arrays are not identical.
6975 return false;
6978 // Traversal.
6981 Array_type::do_traverse(Traverse* traverse)
6983 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
6984 return TRAVERSE_EXIT;
6985 if (this->length_ != NULL
6986 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
6987 return TRAVERSE_EXIT;
6988 return TRAVERSE_CONTINUE;
6991 // Check that the length is valid.
6993 bool
6994 Array_type::verify_length()
6996 if (this->length_ == NULL)
6997 return true;
6999 Type_context context(Type::lookup_integer_type("int"), false);
7000 this->length_->determine_type(&context);
7002 if (!this->length_->is_constant())
7004 go_error_at(this->length_->location(), "array bound is not constant");
7005 return false;
7008 Numeric_constant nc;
7009 if (!this->length_->numeric_constant_value(&nc))
7011 if (this->length_->type()->integer_type() != NULL
7012 || this->length_->type()->float_type() != NULL)
7013 go_error_at(this->length_->location(), "array bound is not constant");
7014 else
7015 go_error_at(this->length_->location(), "array bound is not numeric");
7016 return false;
7019 Type* int_type = Type::lookup_integer_type("int");
7020 unsigned int tbits = int_type->integer_type()->bits();
7021 unsigned long val;
7022 switch (nc.to_unsigned_long(&val))
7024 case Numeric_constant::NC_UL_VALID:
7025 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7027 go_error_at(this->length_->location(), "array bound overflows");
7028 return false;
7030 break;
7031 case Numeric_constant::NC_UL_NOTINT:
7032 go_error_at(this->length_->location(), "array bound truncated to integer");
7033 return false;
7034 case Numeric_constant::NC_UL_NEGATIVE:
7035 go_error_at(this->length_->location(), "negative array bound");
7036 return false;
7037 case Numeric_constant::NC_UL_BIG:
7039 mpz_t val;
7040 if (!nc.to_int(&val))
7041 go_unreachable();
7042 unsigned int bits = mpz_sizeinbase(val, 2);
7043 mpz_clear(val);
7044 if (bits >= tbits)
7046 go_error_at(this->length_->location(), "array bound overflows");
7047 return false;
7050 break;
7051 default:
7052 go_unreachable();
7055 return true;
7058 // Verify the type.
7060 bool
7061 Array_type::do_verify()
7063 if (this->element_type()->is_error_type())
7064 return false;
7065 if (!this->verify_length())
7066 this->length_ = Expression::make_error(this->length_->location());
7067 return true;
7070 // Whether the type contains pointers. This is always true for a
7071 // slice. For an array it is true if the element type has pointers
7072 // and the length is greater than zero.
7074 bool
7075 Array_type::do_has_pointer() const
7077 if (this->length_ == NULL)
7078 return true;
7079 if (!this->element_type_->has_pointer())
7080 return false;
7082 Numeric_constant nc;
7083 if (!this->length_->numeric_constant_value(&nc))
7085 // Error reported elsewhere.
7086 return false;
7089 unsigned long val;
7090 switch (nc.to_unsigned_long(&val))
7092 case Numeric_constant::NC_UL_VALID:
7093 return val > 0;
7094 case Numeric_constant::NC_UL_BIG:
7095 return true;
7096 default:
7097 // Error reported elsewhere.
7098 return false;
7102 // Whether we can use memcmp to compare this array.
7104 bool
7105 Array_type::do_compare_is_identity(Gogo* gogo)
7107 if (this->length_ == NULL)
7108 return false;
7110 // Check for [...], which indicates that this is not a real type.
7111 if (this->length_->is_nil_expression())
7112 return false;
7114 if (!this->element_type_->compare_is_identity(gogo))
7115 return false;
7117 // If there is any padding, then we can't use memcmp.
7118 int64_t size;
7119 int64_t align;
7120 if (!this->element_type_->backend_type_size(gogo, &size)
7121 || !this->element_type_->backend_type_align(gogo, &align))
7122 return false;
7123 if ((size & (align - 1)) != 0)
7124 return false;
7126 return true;
7129 // Array type hash code.
7131 unsigned int
7132 Array_type::do_hash_for_method(Gogo* gogo) const
7134 unsigned int ret;
7136 // There is no very convenient way to get a hash code for the
7137 // length.
7138 ret = this->element_type_->hash_for_method(gogo) + 1;
7139 if (this->is_array_incomparable_)
7140 ret <<= 1;
7141 return ret;
7144 // Write the hash function for an array which can not use the identify
7145 // function.
7147 void
7148 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7149 Function_type* hash_fntype,
7150 Function_type* equal_fntype)
7152 Location bloc = Linemap::predeclared_location();
7154 // The pointer to the array that we are going to hash. This is an
7155 // argument to the hash function we are implementing here.
7156 Named_object* key_arg = gogo->lookup("key", NULL);
7157 go_assert(key_arg != NULL);
7158 Type* key_arg_type = key_arg->var_value()->type();
7160 // The seed argument to the hash function.
7161 Named_object* seed_arg = gogo->lookup("seed", NULL);
7162 go_assert(seed_arg != NULL);
7164 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7166 // Make a temporary to hold the return value, initialized to the seed.
7167 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7168 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7169 bloc);
7170 gogo->add_statement(retval);
7172 // Make a temporary to hold the key as a uintptr.
7173 ref = Expression::make_var_reference(key_arg, bloc);
7174 ref = Expression::make_cast(uintptr_type, ref, bloc);
7175 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7176 bloc);
7177 gogo->add_statement(key);
7179 // Loop over the array elements.
7180 // for i = range a
7181 Type* int_type = Type::lookup_integer_type("int");
7182 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7183 gogo->add_statement(index);
7185 Expression* iref = Expression::make_temporary_reference(index, bloc);
7186 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7187 Type* pt = Type::make_pointer_type(name != NULL
7188 ? static_cast<Type*>(name)
7189 : static_cast<Type*>(this));
7190 aref = Expression::make_cast(pt, aref, bloc);
7191 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7192 NULL,
7193 aref,
7194 bloc);
7196 gogo->start_block(bloc);
7198 // Get the hash function for the element type.
7199 Named_object* hash_fn;
7200 Named_object* equal_fn;
7201 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7202 hash_fntype, equal_fntype, &hash_fn,
7203 &equal_fn);
7205 // Get a pointer to this element in the loop.
7206 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7207 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7209 // Get the size of each element.
7210 Expression* ele_size = Expression::make_type_info(this->element_type_,
7211 Expression::TYPE_INFO_SIZE);
7213 // Get the hash of this element, passing retval as the seed.
7214 ref = Expression::make_temporary_reference(retval, bloc);
7215 Expression_list* args = new Expression_list();
7216 args->push_back(subkey);
7217 args->push_back(ref);
7218 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7219 Expression* call = Expression::make_call(func, args, false, bloc);
7221 // Set retval to the result.
7222 Temporary_reference_expression* tref =
7223 Expression::make_temporary_reference(retval, bloc);
7224 tref->set_is_lvalue();
7225 Statement* s = Statement::make_assignment(tref, call, bloc);
7226 gogo->add_statement(s);
7228 // Increase the element pointer.
7229 tref = Expression::make_temporary_reference(key, bloc);
7230 tref->set_is_lvalue();
7231 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7232 bloc);
7233 Block* statements = gogo->finish_block(bloc);
7235 for_range->add_statements(statements);
7236 gogo->add_statement(for_range);
7238 // Return retval to the caller of the hash function.
7239 Expression_list* vals = new Expression_list();
7240 ref = Expression::make_temporary_reference(retval, bloc);
7241 vals->push_back(ref);
7242 s = Statement::make_return_statement(vals, bloc);
7243 gogo->add_statement(s);
7246 // Write the equality function for an array which can not use the
7247 // identity function.
7249 void
7250 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7252 Location bloc = Linemap::predeclared_location();
7254 // The pointers to the arrays we are going to compare.
7255 Named_object* key1_arg = gogo->lookup("key1", NULL);
7256 Named_object* key2_arg = gogo->lookup("key2", NULL);
7257 go_assert(key1_arg != NULL && key2_arg != NULL);
7259 // Build temporaries for the keys with the right types.
7260 Type* pt = Type::make_pointer_type(name != NULL
7261 ? static_cast<Type*>(name)
7262 : static_cast<Type*>(this));
7264 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7265 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7266 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7267 gogo->add_statement(p1);
7269 ref = Expression::make_var_reference(key2_arg, bloc);
7270 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7271 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7272 gogo->add_statement(p2);
7274 // Loop over the array elements.
7275 // for i = range a
7276 Type* int_type = Type::lookup_integer_type("int");
7277 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7278 gogo->add_statement(index);
7280 Expression* iref = Expression::make_temporary_reference(index, bloc);
7281 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7282 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7283 NULL,
7284 aref,
7285 bloc);
7287 gogo->start_block(bloc);
7289 // Compare element in P1 and P2.
7290 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7291 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7292 ref = Expression::make_temporary_reference(index, bloc);
7293 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7295 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7296 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7297 ref = Expression::make_temporary_reference(index, bloc);
7298 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7300 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7302 // If the elements are not equal, return false.
7303 gogo->start_block(bloc);
7304 Expression_list* vals = new Expression_list();
7305 vals->push_back(Expression::make_boolean(false, bloc));
7306 Statement* s = Statement::make_return_statement(vals, bloc);
7307 gogo->add_statement(s);
7308 Block* then_block = gogo->finish_block(bloc);
7310 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7311 gogo->add_statement(s);
7313 Block* statements = gogo->finish_block(bloc);
7315 for_range->add_statements(statements);
7316 gogo->add_statement(for_range);
7318 // All the elements are equal, so return true.
7319 vals = new Expression_list();
7320 vals->push_back(Expression::make_boolean(true, bloc));
7321 s = Statement::make_return_statement(vals, bloc);
7322 gogo->add_statement(s);
7325 // Get the backend representation of the fields of a slice. This is
7326 // not declared in types.h so that types.h doesn't have to #include
7327 // backend.h.
7329 // We use int for the count and capacity fields. This matches 6g.
7330 // The language more or less assumes that we can't allocate space of a
7331 // size which does not fit in int.
7333 static void
7334 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7335 std::vector<Backend::Btyped_identifier>* bfields)
7337 bfields->resize(3);
7339 Type* pet = Type::make_pointer_type(type->element_type());
7340 Btype* pbet = (use_placeholder
7341 ? pet->get_backend_placeholder(gogo)
7342 : pet->get_backend(gogo));
7343 Location ploc = Linemap::predeclared_location();
7345 Backend::Btyped_identifier* p = &(*bfields)[0];
7346 p->name = "__values";
7347 p->btype = pbet;
7348 p->location = ploc;
7350 Type* int_type = Type::lookup_integer_type("int");
7352 p = &(*bfields)[1];
7353 p->name = "__count";
7354 p->btype = int_type->get_backend(gogo);
7355 p->location = ploc;
7357 p = &(*bfields)[2];
7358 p->name = "__capacity";
7359 p->btype = int_type->get_backend(gogo);
7360 p->location = ploc;
7363 // Get the backend representation for the type of this array. A fixed array is
7364 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7365 // just like an array in C. An open array is a struct with three
7366 // fields: a data pointer, the length, and the capacity.
7368 Btype*
7369 Array_type::do_get_backend(Gogo* gogo)
7371 if (this->length_ == NULL)
7373 std::vector<Backend::Btyped_identifier> bfields;
7374 get_backend_slice_fields(gogo, this, false, &bfields);
7375 return gogo->backend()->struct_type(bfields);
7377 else
7379 Btype* element = this->get_backend_element(gogo, false);
7380 Bexpression* len = this->get_backend_length(gogo);
7381 return gogo->backend()->array_type(element, len);
7385 // Return the backend representation of the element type.
7387 Btype*
7388 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7390 if (use_placeholder)
7391 return this->element_type_->get_backend_placeholder(gogo);
7392 else
7393 return this->element_type_->get_backend(gogo);
7396 // Return the backend representation of the length. The length may be
7397 // computed using a function call, so we must only evaluate it once.
7399 Bexpression*
7400 Array_type::get_backend_length(Gogo* gogo)
7402 go_assert(this->length_ != NULL);
7403 if (this->blength_ == NULL)
7405 if (this->length_->is_error_expression())
7407 this->blength_ = gogo->backend()->error_expression();
7408 return this->blength_;
7410 Numeric_constant nc;
7411 mpz_t val;
7412 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7414 if (mpz_sgn(val) < 0)
7416 this->blength_ = gogo->backend()->error_expression();
7417 return this->blength_;
7419 Type* t = nc.type();
7420 if (t == NULL)
7421 t = Type::lookup_integer_type("int");
7422 else if (t->is_abstract())
7423 t = t->make_non_abstract_type();
7424 Btype* btype = t->get_backend(gogo);
7425 this->blength_ =
7426 gogo->backend()->integer_constant_expression(btype, val);
7427 mpz_clear(val);
7429 else
7431 // Make up a translation context for the array length
7432 // expression. FIXME: This won't work in general.
7433 Translate_context context(gogo, NULL, NULL, NULL);
7434 this->blength_ = this->length_->get_backend(&context);
7436 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7437 this->blength_ =
7438 gogo->backend()->convert_expression(ibtype, this->blength_,
7439 this->length_->location());
7442 return this->blength_;
7445 // Finish backend representation of the array.
7447 void
7448 Array_type::finish_backend_element(Gogo* gogo)
7450 Type* et = this->array_type()->element_type();
7451 et->get_backend(gogo);
7452 if (this->is_slice_type())
7454 // This relies on the fact that we always use the same
7455 // structure for a pointer to any given type.
7456 Type* pet = Type::make_pointer_type(et);
7457 pet->get_backend(gogo);
7461 // Return an expression for a pointer to the values in ARRAY.
7463 Expression*
7464 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7466 if (this->length() != NULL)
7468 // Fixed array.
7469 go_assert(array->type()->array_type() != NULL);
7470 Type* etype = array->type()->array_type()->element_type();
7471 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7472 return Expression::make_cast(Type::make_pointer_type(etype), array,
7473 array->location());
7476 // Slice.
7478 if (is_lvalue)
7480 Temporary_reference_expression* tref =
7481 array->temporary_reference_expression();
7482 Var_expression* ve = array->var_expression();
7483 if (tref != NULL)
7485 tref = tref->copy()->temporary_reference_expression();
7486 tref->set_is_lvalue();
7487 array = tref;
7489 else if (ve != NULL)
7491 ve = new Var_expression(ve->named_object(), ve->location());
7492 array = ve;
7496 return Expression::make_slice_info(array,
7497 Expression::SLICE_INFO_VALUE_POINTER,
7498 array->location());
7501 // Return an expression for the length of the array ARRAY which has this
7502 // type.
7504 Expression*
7505 Array_type::get_length(Gogo*, Expression* array) const
7507 if (this->length_ != NULL)
7508 return this->length_;
7510 // This is a slice. We need to read the length field.
7511 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7512 array->location());
7515 // Return an expression for the capacity of the array ARRAY which has this
7516 // type.
7518 Expression*
7519 Array_type::get_capacity(Gogo*, Expression* array) const
7521 if (this->length_ != NULL)
7522 return this->length_;
7524 // This is a slice. We need to read the capacity field.
7525 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7526 array->location());
7529 // Export.
7531 void
7532 Array_type::do_export(Export* exp) const
7534 exp->write_c_string("[");
7535 if (this->length_ != NULL)
7536 this->length_->export_expression(exp);
7537 exp->write_c_string("] ");
7538 exp->write_type(this->element_type_);
7541 // Import.
7543 Array_type*
7544 Array_type::do_import(Import* imp)
7546 imp->require_c_string("[");
7547 Expression* length;
7548 if (imp->peek_char() == ']')
7549 length = NULL;
7550 else
7551 length = Expression::import_expression(imp);
7552 imp->require_c_string("] ");
7553 Type* element_type = imp->read_type();
7554 return Type::make_array_type(element_type, length);
7557 // The type of an array type descriptor.
7559 Type*
7560 Array_type::make_array_type_descriptor_type()
7562 static Type* ret;
7563 if (ret == NULL)
7565 Type* tdt = Type::make_type_descriptor_type();
7566 Type* ptdt = Type::make_type_descriptor_ptr_type();
7568 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7570 Struct_type* sf =
7571 Type::make_builtin_struct_type(4,
7572 "", tdt,
7573 "elem", ptdt,
7574 "slice", ptdt,
7575 "len", uintptr_type);
7577 ret = Type::make_builtin_named_type("ArrayType", sf);
7580 return ret;
7583 // The type of an slice type descriptor.
7585 Type*
7586 Array_type::make_slice_type_descriptor_type()
7588 static Type* ret;
7589 if (ret == NULL)
7591 Type* tdt = Type::make_type_descriptor_type();
7592 Type* ptdt = Type::make_type_descriptor_ptr_type();
7594 Struct_type* sf =
7595 Type::make_builtin_struct_type(2,
7596 "", tdt,
7597 "elem", ptdt);
7599 ret = Type::make_builtin_named_type("SliceType", sf);
7602 return ret;
7605 // Build a type descriptor for an array/slice type.
7607 Expression*
7608 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7610 if (this->length_ != NULL)
7611 return this->array_type_descriptor(gogo, name);
7612 else
7613 return this->slice_type_descriptor(gogo, name);
7616 // Build a type descriptor for an array type.
7618 Expression*
7619 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7621 Location bloc = Linemap::predeclared_location();
7623 Type* atdt = Array_type::make_array_type_descriptor_type();
7625 const Struct_field_list* fields = atdt->struct_type()->fields();
7627 Expression_list* vals = new Expression_list();
7628 vals->reserve(3);
7630 Struct_field_list::const_iterator p = fields->begin();
7631 go_assert(p->is_field_name("_type"));
7632 vals->push_back(this->type_descriptor_constructor(gogo,
7633 RUNTIME_TYPE_KIND_ARRAY,
7634 name, NULL, true));
7636 ++p;
7637 go_assert(p->is_field_name("elem"));
7638 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7640 ++p;
7641 go_assert(p->is_field_name("slice"));
7642 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7643 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7645 ++p;
7646 go_assert(p->is_field_name("len"));
7647 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7649 ++p;
7650 go_assert(p == fields->end());
7652 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7655 // Build a type descriptor for a slice type.
7657 Expression*
7658 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7660 Location bloc = Linemap::predeclared_location();
7662 Type* stdt = Array_type::make_slice_type_descriptor_type();
7664 const Struct_field_list* fields = stdt->struct_type()->fields();
7666 Expression_list* vals = new Expression_list();
7667 vals->reserve(2);
7669 Struct_field_list::const_iterator p = fields->begin();
7670 go_assert(p->is_field_name("_type"));
7671 vals->push_back(this->type_descriptor_constructor(gogo,
7672 RUNTIME_TYPE_KIND_SLICE,
7673 name, NULL, true));
7675 ++p;
7676 go_assert(p->is_field_name("elem"));
7677 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7679 ++p;
7680 go_assert(p == fields->end());
7682 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7685 // Reflection string.
7687 void
7688 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7690 ret->push_back('[');
7691 if (this->length_ != NULL)
7693 Numeric_constant nc;
7694 if (!this->length_->numeric_constant_value(&nc))
7696 go_assert(saw_errors());
7697 return;
7699 mpz_t val;
7700 if (!nc.to_int(&val))
7702 go_assert(saw_errors());
7703 return;
7705 char* s = mpz_get_str(NULL, 10, val);
7706 ret->append(s);
7707 free(s);
7708 mpz_clear(val);
7710 ret->push_back(']');
7712 this->append_reflection(this->element_type_, gogo, ret);
7715 // Make an array type.
7717 Array_type*
7718 Type::make_array_type(Type* element_type, Expression* length)
7720 return new Array_type(element_type, length);
7723 // Class Map_type.
7725 Named_object* Map_type::zero_value;
7726 int64_t Map_type::zero_value_size;
7727 int64_t Map_type::zero_value_align;
7729 // If this map requires the "fat" functions, return the pointer to
7730 // pass as the zero value to those functions. Otherwise, in the
7731 // normal case, return NULL. The map requires the "fat" functions if
7732 // the value size is larger than max_zero_size bytes. max_zero_size
7733 // must match maxZero in libgo/go/runtime/hashmap.go.
7735 Expression*
7736 Map_type::fat_zero_value(Gogo* gogo)
7738 int64_t valsize;
7739 if (!this->val_type_->backend_type_size(gogo, &valsize))
7741 go_assert(saw_errors());
7742 return NULL;
7744 if (valsize <= Map_type::max_zero_size)
7745 return NULL;
7747 if (Map_type::zero_value_size < valsize)
7748 Map_type::zero_value_size = valsize;
7750 int64_t valalign;
7751 if (!this->val_type_->backend_type_align(gogo, &valalign))
7753 go_assert(saw_errors());
7754 return NULL;
7757 if (Map_type::zero_value_align < valalign)
7758 Map_type::zero_value_align = valalign;
7760 Location bloc = Linemap::predeclared_location();
7762 if (Map_type::zero_value == NULL)
7764 // The final type will be set in backend_zero_value.
7765 Type* uint8_type = Type::lookup_integer_type("uint8");
7766 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7767 Array_type* array_type = Type::make_array_type(uint8_type, size);
7768 array_type->set_is_array_incomparable();
7769 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7770 std::string name = gogo->map_zero_value_name();
7771 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7774 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7775 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7776 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7777 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7778 return z;
7781 // Return whether VAR is the map zero value.
7783 bool
7784 Map_type::is_zero_value(Variable* var)
7786 return (Map_type::zero_value != NULL
7787 && Map_type::zero_value->var_value() == var);
7790 // Return the backend representation for the zero value.
7792 Bvariable*
7793 Map_type::backend_zero_value(Gogo* gogo)
7795 Location bloc = Linemap::predeclared_location();
7797 go_assert(Map_type::zero_value != NULL);
7799 Type* uint8_type = Type::lookup_integer_type("uint8");
7800 Btype* buint8_type = uint8_type->get_backend(gogo);
7802 Type* int_type = Type::lookup_integer_type("int");
7804 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7805 int_type, bloc);
7806 Translate_context context(gogo, NULL, NULL, NULL);
7807 Bexpression* blength = e->get_backend(&context);
7809 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7811 std::string zname = Map_type::zero_value->name();
7812 std::string asm_name(go_selectively_encode_id(zname));
7813 Bvariable* zvar =
7814 gogo->backend()->implicit_variable(zname, asm_name,
7815 barray_type, false, false, true,
7816 Map_type::zero_value_align);
7817 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7818 false, false, true, NULL);
7819 return zvar;
7822 // Traversal.
7825 Map_type::do_traverse(Traverse* traverse)
7827 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7828 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7829 return TRAVERSE_EXIT;
7830 return TRAVERSE_CONTINUE;
7833 // Check that the map type is OK.
7835 bool
7836 Map_type::do_verify()
7838 // The runtime support uses "map[void]void".
7839 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7840 go_error_at(this->location_, "invalid map key type");
7841 if (!this->key_type_->in_heap())
7842 go_error_at(this->location_, "go:notinheap map key not allowed");
7843 if (!this->val_type_->in_heap())
7844 go_error_at(this->location_, "go:notinheap map value not allowed");
7845 return true;
7848 // Whether two map types are identical.
7850 bool
7851 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7852 bool errors_are_identical) const
7854 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7855 cmp_tags, errors_are_identical, NULL)
7856 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7857 cmp_tags, errors_are_identical,
7858 NULL));
7861 // Hash code.
7863 unsigned int
7864 Map_type::do_hash_for_method(Gogo* gogo) const
7866 return (this->key_type_->hash_for_method(gogo)
7867 + this->val_type_->hash_for_method(gogo)
7868 + 2);
7871 // Get the backend representation for a map type. A map type is
7872 // represented as a pointer to a struct. The struct is hmap in
7873 // runtime/hashmap.go.
7875 Btype*
7876 Map_type::do_get_backend(Gogo* gogo)
7878 static Btype* backend_map_type;
7879 if (backend_map_type == NULL)
7881 std::vector<Backend::Btyped_identifier> bfields(9);
7883 Location bloc = Linemap::predeclared_location();
7885 Type* int_type = Type::lookup_integer_type("int");
7886 bfields[0].name = "count";
7887 bfields[0].btype = int_type->get_backend(gogo);
7888 bfields[0].location = bloc;
7890 Type* uint8_type = Type::lookup_integer_type("uint8");
7891 bfields[1].name = "flags";
7892 bfields[1].btype = uint8_type->get_backend(gogo);
7893 bfields[1].location = bloc;
7895 bfields[2].name = "B";
7896 bfields[2].btype = bfields[1].btype;
7897 bfields[2].location = bloc;
7899 Type* uint16_type = Type::lookup_integer_type("uint16");
7900 bfields[3].name = "noverflow";
7901 bfields[3].btype = uint16_type->get_backend(gogo);
7902 bfields[3].location = bloc;
7904 Type* uint32_type = Type::lookup_integer_type("uint32");
7905 bfields[4].name = "hash0";
7906 bfields[4].btype = uint32_type->get_backend(gogo);
7907 bfields[4].location = bloc;
7909 Btype* bvt = gogo->backend()->void_type();
7910 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7911 bfields[5].name = "buckets";
7912 bfields[5].btype = bpvt;
7913 bfields[5].location = bloc;
7915 bfields[6].name = "oldbuckets";
7916 bfields[6].btype = bpvt;
7917 bfields[6].location = bloc;
7919 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7920 bfields[7].name = "nevacuate";
7921 bfields[7].btype = uintptr_type->get_backend(gogo);
7922 bfields[7].location = bloc;
7924 bfields[8].name = "extra";
7925 bfields[8].btype = bpvt;
7926 bfields[8].location = bloc;
7928 Btype *bt = gogo->backend()->struct_type(bfields);
7929 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7930 backend_map_type = gogo->backend()->pointer_type(bt);
7932 return backend_map_type;
7935 // The type of a map type descriptor.
7937 Type*
7938 Map_type::make_map_type_descriptor_type()
7940 static Type* ret;
7941 if (ret == NULL)
7943 Type* tdt = Type::make_type_descriptor_type();
7944 Type* ptdt = Type::make_type_descriptor_ptr_type();
7945 Type* uint8_type = Type::lookup_integer_type("uint8");
7946 Type* uint16_type = Type::lookup_integer_type("uint16");
7947 Type* bool_type = Type::lookup_bool_type();
7949 Struct_type* sf =
7950 Type::make_builtin_struct_type(12,
7951 "", tdt,
7952 "key", ptdt,
7953 "elem", ptdt,
7954 "bucket", ptdt,
7955 "hmap", ptdt,
7956 "keysize", uint8_type,
7957 "indirectkey", bool_type,
7958 "valuesize", uint8_type,
7959 "indirectvalue", bool_type,
7960 "bucketsize", uint16_type,
7961 "reflexivekey", bool_type,
7962 "needkeyupdate", bool_type);
7964 ret = Type::make_builtin_named_type("MapType", sf);
7967 return ret;
7970 // Build a type descriptor for a map type.
7972 Expression*
7973 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7975 Location bloc = Linemap::predeclared_location();
7977 Type* mtdt = Map_type::make_map_type_descriptor_type();
7978 Type* uint8_type = Type::lookup_integer_type("uint8");
7979 Type* uint16_type = Type::lookup_integer_type("uint16");
7981 int64_t keysize;
7982 if (!this->key_type_->backend_type_size(gogo, &keysize))
7984 go_error_at(this->location_, "error determining map key type size");
7985 return Expression::make_error(this->location_);
7988 int64_t valsize;
7989 if (!this->val_type_->backend_type_size(gogo, &valsize))
7991 go_error_at(this->location_, "error determining map value type size");
7992 return Expression::make_error(this->location_);
7995 int64_t ptrsize;
7996 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
7998 go_assert(saw_errors());
7999 return Expression::make_error(this->location_);
8002 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8003 if (bucket_type == NULL)
8005 go_assert(saw_errors());
8006 return Expression::make_error(this->location_);
8009 int64_t bucketsize;
8010 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8012 go_assert(saw_errors());
8013 return Expression::make_error(this->location_);
8016 const Struct_field_list* fields = mtdt->struct_type()->fields();
8018 Expression_list* vals = new Expression_list();
8019 vals->reserve(12);
8021 Struct_field_list::const_iterator p = fields->begin();
8022 go_assert(p->is_field_name("_type"));
8023 vals->push_back(this->type_descriptor_constructor(gogo,
8024 RUNTIME_TYPE_KIND_MAP,
8025 name, NULL, true));
8027 ++p;
8028 go_assert(p->is_field_name("key"));
8029 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8031 ++p;
8032 go_assert(p->is_field_name("elem"));
8033 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8035 ++p;
8036 go_assert(p->is_field_name("bucket"));
8037 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8039 ++p;
8040 go_assert(p->is_field_name("hmap"));
8041 Type* hmap_type = this->hmap_type(bucket_type);
8042 vals->push_back(Expression::make_type_descriptor(hmap_type, bloc));
8044 ++p;
8045 go_assert(p->is_field_name("keysize"));
8046 if (keysize > Map_type::max_key_size)
8047 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8048 else
8049 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8051 ++p;
8052 go_assert(p->is_field_name("indirectkey"));
8053 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8054 bloc));
8056 ++p;
8057 go_assert(p->is_field_name("valuesize"));
8058 if (valsize > Map_type::max_val_size)
8059 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8060 else
8061 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8063 ++p;
8064 go_assert(p->is_field_name("indirectvalue"));
8065 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8066 bloc));
8068 ++p;
8069 go_assert(p->is_field_name("bucketsize"));
8070 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8071 bloc));
8073 ++p;
8074 go_assert(p->is_field_name("reflexivekey"));
8075 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8076 bloc));
8078 ++p;
8079 go_assert(p->is_field_name("needkeyupdate"));
8080 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8081 bloc));
8083 ++p;
8084 go_assert(p == fields->end());
8086 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8089 // Return the bucket type to use for a map type. This must correspond
8090 // to libgo/go/runtime/hashmap.go.
8092 Type*
8093 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8095 if (this->bucket_type_ != NULL)
8096 return this->bucket_type_;
8098 Type* key_type = this->key_type_;
8099 if (keysize > Map_type::max_key_size)
8100 key_type = Type::make_pointer_type(key_type);
8102 Type* val_type = this->val_type_;
8103 if (valsize > Map_type::max_val_size)
8104 val_type = Type::make_pointer_type(val_type);
8106 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8107 NULL, this->location_);
8109 Type* uint8_type = Type::lookup_integer_type("uint8");
8110 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8111 topbits_type->set_is_array_incomparable();
8112 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8113 keys_type->set_is_array_incomparable();
8114 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8115 values_type->set_is_array_incomparable();
8117 // If keys and values have no pointers, the map implementation can
8118 // keep a list of overflow pointers on the side so that buckets can
8119 // be marked as having no pointers. Arrange for the bucket to have
8120 // no pointers by changing the type of the overflow field to uintptr
8121 // in this case. See comment on the hmap.overflow field in
8122 // libgo/go/runtime/hashmap.go.
8123 Type* overflow_type;
8124 if (!key_type->has_pointer() && !val_type->has_pointer())
8125 overflow_type = Type::lookup_integer_type("uintptr");
8126 else
8128 // This should really be a pointer to the bucket type itself,
8129 // but that would require us to construct a Named_type for it to
8130 // give it a way to refer to itself. Since nothing really cares
8131 // (except perhaps for someone using a debugger) just use an
8132 // unsafe pointer.
8133 overflow_type = Type::make_pointer_type(Type::make_void_type());
8136 // Make sure the overflow pointer is the last memory in the struct,
8137 // because the runtime assumes it can use size-ptrSize as the offset
8138 // of the overflow pointer. We double-check that property below
8139 // once the offsets and size are computed.
8141 int64_t topbits_field_size, topbits_field_align;
8142 int64_t keys_field_size, keys_field_align;
8143 int64_t values_field_size, values_field_align;
8144 int64_t overflow_field_size, overflow_field_align;
8145 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8146 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8147 || !keys_type->backend_type_size(gogo, &keys_field_size)
8148 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8149 || !values_type->backend_type_size(gogo, &values_field_size)
8150 || !values_type->backend_type_field_align(gogo, &values_field_align)
8151 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8152 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8154 go_assert(saw_errors());
8155 return NULL;
8158 Struct_type* ret;
8159 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8160 values_field_align);
8161 if (max_align <= overflow_field_align)
8162 ret = make_builtin_struct_type(4,
8163 "topbits", topbits_type,
8164 "keys", keys_type,
8165 "values", values_type,
8166 "overflow", overflow_type);
8167 else
8169 size_t off = topbits_field_size;
8170 off = ((off + keys_field_align - 1)
8171 &~ static_cast<size_t>(keys_field_align - 1));
8172 off += keys_field_size;
8173 off = ((off + values_field_align - 1)
8174 &~ static_cast<size_t>(values_field_align - 1));
8175 off += values_field_size;
8177 int64_t padded_overflow_field_size =
8178 ((overflow_field_size + max_align - 1)
8179 &~ static_cast<size_t>(max_align - 1));
8181 size_t ovoff = off;
8182 ovoff = ((ovoff + max_align - 1)
8183 &~ static_cast<size_t>(max_align - 1));
8184 size_t pad = (ovoff - off
8185 + padded_overflow_field_size - overflow_field_size);
8187 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8188 this->location_);
8189 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8190 pad_type->set_is_array_incomparable();
8192 ret = make_builtin_struct_type(5,
8193 "topbits", topbits_type,
8194 "keys", keys_type,
8195 "values", values_type,
8196 "pad", pad_type,
8197 "overflow", overflow_type);
8200 // Verify that the overflow field is just before the end of the
8201 // bucket type.
8203 Btype* btype = ret->get_backend(gogo);
8204 int64_t offset = gogo->backend()->type_field_offset(btype,
8205 ret->field_count() - 1);
8206 int64_t size;
8207 if (!ret->backend_type_size(gogo, &size))
8209 go_assert(saw_errors());
8210 return NULL;
8213 int64_t ptr_size;
8214 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8216 go_assert(saw_errors());
8217 return NULL;
8220 go_assert(offset + ptr_size == size);
8222 ret->set_is_struct_incomparable();
8224 this->bucket_type_ = ret;
8225 return ret;
8228 // Return the hashmap type for a map type.
8230 Type*
8231 Map_type::hmap_type(Type* bucket_type)
8233 if (this->hmap_type_ != NULL)
8234 return this->hmap_type_;
8236 Type* int_type = Type::lookup_integer_type("int");
8237 Type* uint8_type = Type::lookup_integer_type("uint8");
8238 Type* uint16_type = Type::lookup_integer_type("uint16");
8239 Type* uint32_type = Type::lookup_integer_type("uint32");
8240 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8241 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8243 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8245 Struct_type* ret = make_builtin_struct_type(9,
8246 "count", int_type,
8247 "flags", uint8_type,
8248 "B", uint8_type,
8249 "noverflow", uint16_type,
8250 "hash0", uint32_type,
8251 "buckets", ptr_bucket_type,
8252 "oldbuckets", ptr_bucket_type,
8253 "nevacuate", uintptr_type,
8254 "extra", void_ptr_type);
8255 ret->set_is_struct_incomparable();
8256 this->hmap_type_ = ret;
8257 return ret;
8260 // Return the iterator type for a map type. This is the type of the
8261 // value used when doing a range over a map.
8263 Type*
8264 Map_type::hiter_type(Gogo* gogo)
8266 if (this->hiter_type_ != NULL)
8267 return this->hiter_type_;
8269 int64_t keysize, valsize;
8270 if (!this->key_type_->backend_type_size(gogo, &keysize)
8271 || !this->val_type_->backend_type_size(gogo, &valsize))
8273 go_assert(saw_errors());
8274 return NULL;
8277 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8278 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8279 Type* uint8_type = Type::lookup_integer_type("uint8");
8280 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8281 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8282 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8283 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8284 Type* hmap_type = this->hmap_type(bucket_type);
8285 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8286 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8287 Type* bool_type = Type::lookup_bool_type();
8289 Struct_type* ret = make_builtin_struct_type(15,
8290 "key", key_ptr_type,
8291 "val", val_ptr_type,
8292 "t", uint8_ptr_type,
8293 "h", hmap_ptr_type,
8294 "buckets", bucket_ptr_type,
8295 "bptr", bucket_ptr_type,
8296 "overflow", void_ptr_type,
8297 "oldoverflow", void_ptr_type,
8298 "startBucket", uintptr_type,
8299 "offset", uint8_type,
8300 "wrapped", bool_type,
8301 "B", uint8_type,
8302 "i", uint8_type,
8303 "bucket", uintptr_type,
8304 "checkBucket", uintptr_type);
8305 ret->set_is_struct_incomparable();
8306 this->hiter_type_ = ret;
8307 return ret;
8310 // Reflection string for a map.
8312 void
8313 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8315 ret->append("map[");
8316 this->append_reflection(this->key_type_, gogo, ret);
8317 ret->append("]");
8318 this->append_reflection(this->val_type_, gogo, ret);
8321 // Export a map type.
8323 void
8324 Map_type::do_export(Export* exp) const
8326 exp->write_c_string("map [");
8327 exp->write_type(this->key_type_);
8328 exp->write_c_string("] ");
8329 exp->write_type(this->val_type_);
8332 // Import a map type.
8334 Map_type*
8335 Map_type::do_import(Import* imp)
8337 imp->require_c_string("map [");
8338 Type* key_type = imp->read_type();
8339 imp->require_c_string("] ");
8340 Type* val_type = imp->read_type();
8341 return Type::make_map_type(key_type, val_type, imp->location());
8344 // Make a map type.
8346 Map_type*
8347 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8349 return new Map_type(key_type, val_type, location);
8352 // Class Channel_type.
8354 // Verify.
8356 bool
8357 Channel_type::do_verify()
8359 // We have no location for this error, but this is not something the
8360 // ordinary user will see.
8361 if (!this->element_type_->in_heap())
8362 go_error_at(Linemap::unknown_location(),
8363 "chan of go:notinheap type not allowed");
8364 return true;
8367 // Hash code.
8369 unsigned int
8370 Channel_type::do_hash_for_method(Gogo* gogo) const
8372 unsigned int ret = 0;
8373 if (this->may_send_)
8374 ret += 1;
8375 if (this->may_receive_)
8376 ret += 2;
8377 if (this->element_type_ != NULL)
8378 ret += this->element_type_->hash_for_method(gogo) << 2;
8379 return ret << 3;
8382 // Whether this type is the same as T.
8384 bool
8385 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8386 bool errors_are_identical) const
8388 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8389 cmp_tags, errors_are_identical, NULL))
8390 return false;
8391 return (this->may_send_ == t->may_send_
8392 && this->may_receive_ == t->may_receive_);
8395 // Return the backend representation for a channel type. A channel is a pointer
8396 // to a __go_channel struct. The __go_channel struct is defined in
8397 // libgo/runtime/channel.h.
8399 Btype*
8400 Channel_type::do_get_backend(Gogo* gogo)
8402 static Btype* backend_channel_type;
8403 if (backend_channel_type == NULL)
8405 std::vector<Backend::Btyped_identifier> bfields;
8406 Btype* bt = gogo->backend()->struct_type(bfields);
8407 bt = gogo->backend()->named_type("__go_channel", bt,
8408 Linemap::predeclared_location());
8409 backend_channel_type = gogo->backend()->pointer_type(bt);
8411 return backend_channel_type;
8414 // Build a type descriptor for a channel type.
8416 Type*
8417 Channel_type::make_chan_type_descriptor_type()
8419 static Type* ret;
8420 if (ret == NULL)
8422 Type* tdt = Type::make_type_descriptor_type();
8423 Type* ptdt = Type::make_type_descriptor_ptr_type();
8425 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8427 Struct_type* sf =
8428 Type::make_builtin_struct_type(3,
8429 "", tdt,
8430 "elem", ptdt,
8431 "dir", uintptr_type);
8433 ret = Type::make_builtin_named_type("ChanType", sf);
8436 return ret;
8439 // Build a type descriptor for a map type.
8441 Expression*
8442 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8444 Location bloc = Linemap::predeclared_location();
8446 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8448 const Struct_field_list* fields = ctdt->struct_type()->fields();
8450 Expression_list* vals = new Expression_list();
8451 vals->reserve(3);
8453 Struct_field_list::const_iterator p = fields->begin();
8454 go_assert(p->is_field_name("_type"));
8455 vals->push_back(this->type_descriptor_constructor(gogo,
8456 RUNTIME_TYPE_KIND_CHAN,
8457 name, NULL, true));
8459 ++p;
8460 go_assert(p->is_field_name("elem"));
8461 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8463 ++p;
8464 go_assert(p->is_field_name("dir"));
8465 // These bits must match the ones in libgo/runtime/go-type.h.
8466 int val = 0;
8467 if (this->may_receive_)
8468 val |= 1;
8469 if (this->may_send_)
8470 val |= 2;
8471 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8473 ++p;
8474 go_assert(p == fields->end());
8476 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8479 // Reflection string.
8481 void
8482 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8484 if (!this->may_send_)
8485 ret->append("<-");
8486 ret->append("chan");
8487 if (!this->may_receive_)
8488 ret->append("<-");
8489 ret->push_back(' ');
8490 this->append_reflection(this->element_type_, gogo, ret);
8493 // Export.
8495 void
8496 Channel_type::do_export(Export* exp) const
8498 exp->write_c_string("chan ");
8499 if (this->may_send_ && !this->may_receive_)
8500 exp->write_c_string("-< ");
8501 else if (this->may_receive_ && !this->may_send_)
8502 exp->write_c_string("<- ");
8503 exp->write_type(this->element_type_);
8506 // Import.
8508 Channel_type*
8509 Channel_type::do_import(Import* imp)
8511 imp->require_c_string("chan ");
8513 bool may_send;
8514 bool may_receive;
8515 if (imp->match_c_string("-< "))
8517 imp->advance(3);
8518 may_send = true;
8519 may_receive = false;
8521 else if (imp->match_c_string("<- "))
8523 imp->advance(3);
8524 may_receive = true;
8525 may_send = false;
8527 else
8529 may_send = true;
8530 may_receive = true;
8533 Type* element_type = imp->read_type();
8535 return Type::make_channel_type(may_send, may_receive, element_type);
8538 // Return the type to manage a select statement with ncases case
8539 // statements. A value of this type is allocated on the stack. This
8540 // must match the type hselect in libgo/go/runtime/select.go.
8542 Type*
8543 Channel_type::select_type(int ncases)
8545 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
8546 Type* uint16_type = Type::lookup_integer_type("uint16");
8548 static Struct_type* scase_type;
8549 if (scase_type == NULL)
8551 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8552 Type* uint64_type = Type::lookup_integer_type("uint64");
8553 scase_type =
8554 Type::make_builtin_struct_type(7,
8555 "elem", unsafe_pointer_type,
8556 "chan", unsafe_pointer_type,
8557 "pc", uintptr_type,
8558 "kind", uint16_type,
8559 "index", uint16_type,
8560 "receivedp", unsafe_pointer_type,
8561 "releasetime", uint64_type);
8562 scase_type->set_is_struct_incomparable();
8565 Expression* ncases_expr =
8566 Expression::make_integer_ul(ncases, NULL, Linemap::predeclared_location());
8567 Array_type* scases = Type::make_array_type(scase_type, ncases_expr);
8568 scases->set_is_array_incomparable();
8569 Array_type* order = Type::make_array_type(uint16_type, ncases_expr);
8570 order->set_is_array_incomparable();
8572 Struct_type* ret =
8573 Type::make_builtin_struct_type(7,
8574 "tcase", uint16_type,
8575 "ncase", uint16_type,
8576 "pollorder", unsafe_pointer_type,
8577 "lockorder", unsafe_pointer_type,
8578 "scase", scases,
8579 "lockorderarr", order,
8580 "pollorderarr", order);
8581 ret->set_is_struct_incomparable();
8582 return ret;
8585 // Make a new channel type.
8587 Channel_type*
8588 Type::make_channel_type(bool send, bool receive, Type* element_type)
8590 return new Channel_type(send, receive, element_type);
8593 // Class Interface_type.
8595 // Return the list of methods.
8597 const Typed_identifier_list*
8598 Interface_type::methods() const
8600 go_assert(this->methods_are_finalized_ || saw_errors());
8601 return this->all_methods_;
8604 // Return the number of methods.
8606 size_t
8607 Interface_type::method_count() const
8609 go_assert(this->methods_are_finalized_ || saw_errors());
8610 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
8613 // Traversal.
8616 Interface_type::do_traverse(Traverse* traverse)
8618 Typed_identifier_list* methods = (this->methods_are_finalized_
8619 ? this->all_methods_
8620 : this->parse_methods_);
8621 if (methods == NULL)
8622 return TRAVERSE_CONTINUE;
8623 return methods->traverse(traverse);
8626 // Finalize the methods. This handles interface inheritance.
8628 void
8629 Interface_type::finalize_methods()
8631 if (this->methods_are_finalized_)
8632 return;
8633 this->methods_are_finalized_ = true;
8634 if (this->parse_methods_ == NULL)
8635 return;
8637 this->all_methods_ = new Typed_identifier_list();
8638 this->all_methods_->reserve(this->parse_methods_->size());
8639 Typed_identifier_list inherit;
8640 for (Typed_identifier_list::const_iterator pm =
8641 this->parse_methods_->begin();
8642 pm != this->parse_methods_->end();
8643 ++pm)
8645 const Typed_identifier* p = &*pm;
8646 if (p->name().empty())
8647 inherit.push_back(*p);
8648 else if (this->find_method(p->name()) == NULL)
8649 this->all_methods_->push_back(*p);
8650 else
8651 go_error_at(p->location(), "duplicate method %qs",
8652 Gogo::message_name(p->name()).c_str());
8655 std::vector<Named_type*> seen;
8656 seen.reserve(inherit.size());
8657 bool issued_recursive_error = false;
8658 while (!inherit.empty())
8660 Type* t = inherit.back().type();
8661 Location tl = inherit.back().location();
8662 inherit.pop_back();
8664 Interface_type* it = t->interface_type();
8665 if (it == NULL)
8667 if (!t->is_error())
8668 go_error_at(tl, "interface contains embedded non-interface");
8669 continue;
8671 if (it == this)
8673 if (!issued_recursive_error)
8675 go_error_at(tl, "invalid recursive interface");
8676 issued_recursive_error = true;
8678 continue;
8681 Named_type* nt = t->named_type();
8682 if (nt != NULL && it->parse_methods_ != NULL)
8684 std::vector<Named_type*>::const_iterator q;
8685 for (q = seen.begin(); q != seen.end(); ++q)
8687 if (*q == nt)
8689 go_error_at(tl, "inherited interface loop");
8690 break;
8693 if (q != seen.end())
8694 continue;
8695 seen.push_back(nt);
8698 const Typed_identifier_list* imethods = it->parse_methods_;
8699 if (imethods == NULL)
8700 continue;
8701 for (Typed_identifier_list::const_iterator q = imethods->begin();
8702 q != imethods->end();
8703 ++q)
8705 if (q->name().empty())
8706 inherit.push_back(*q);
8707 else if (this->find_method(q->name()) == NULL)
8708 this->all_methods_->push_back(Typed_identifier(q->name(),
8709 q->type(), tl));
8710 else
8711 go_error_at(tl, "inherited method %qs is ambiguous",
8712 Gogo::message_name(q->name()).c_str());
8716 if (!this->all_methods_->empty())
8717 this->all_methods_->sort_by_name();
8718 else
8720 delete this->all_methods_;
8721 this->all_methods_ = NULL;
8725 // Return the method NAME, or NULL.
8727 const Typed_identifier*
8728 Interface_type::find_method(const std::string& name) const
8730 go_assert(this->methods_are_finalized_);
8731 if (this->all_methods_ == NULL)
8732 return NULL;
8733 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8734 p != this->all_methods_->end();
8735 ++p)
8736 if (p->name() == name)
8737 return &*p;
8738 return NULL;
8741 // Return the method index.
8743 size_t
8744 Interface_type::method_index(const std::string& name) const
8746 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
8747 size_t ret = 0;
8748 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8749 p != this->all_methods_->end();
8750 ++p, ++ret)
8751 if (p->name() == name)
8752 return ret;
8753 go_unreachable();
8756 // Return whether NAME is an unexported method, for better error
8757 // reporting.
8759 bool
8760 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
8762 go_assert(this->methods_are_finalized_);
8763 if (this->all_methods_ == NULL)
8764 return false;
8765 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8766 p != this->all_methods_->end();
8767 ++p)
8769 const std::string& method_name(p->name());
8770 if (Gogo::is_hidden_name(method_name)
8771 && name == Gogo::unpack_hidden_name(method_name)
8772 && gogo->pack_hidden_name(name, false) != method_name)
8773 return true;
8775 return false;
8778 // Whether this type is identical with T.
8780 bool
8781 Interface_type::is_identical(const Interface_type* t, Cmp_tags cmp_tags,
8782 bool errors_are_identical) const
8784 // If methods have not been finalized, then we are asking whether
8785 // func redeclarations are the same. This is an error, so for
8786 // simplicity we say they are never the same.
8787 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
8788 return false;
8790 // We require the same methods with the same types. The methods
8791 // have already been sorted.
8792 if (this->all_methods_ == NULL || t->all_methods_ == NULL)
8793 return this->all_methods_ == t->all_methods_;
8795 if (this->assume_identical(this, t) || t->assume_identical(t, this))
8796 return true;
8798 Assume_identical* hold_ai = this->assume_identical_;
8799 Assume_identical ai;
8800 ai.t1 = this;
8801 ai.t2 = t;
8802 ai.next = hold_ai;
8803 this->assume_identical_ = &ai;
8805 Typed_identifier_list::const_iterator p1 = this->all_methods_->begin();
8806 Typed_identifier_list::const_iterator p2;
8807 for (p2 = t->all_methods_->begin(); p2 != t->all_methods_->end(); ++p1, ++p2)
8809 if (p1 == this->all_methods_->end())
8810 break;
8811 if (p1->name() != p2->name()
8812 || !Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
8813 errors_are_identical, NULL))
8814 break;
8817 this->assume_identical_ = hold_ai;
8819 return p1 == this->all_methods_->end() && p2 == t->all_methods_->end();
8822 // Return true if T1 and T2 are assumed to be identical during a type
8823 // comparison.
8825 bool
8826 Interface_type::assume_identical(const Interface_type* t1,
8827 const Interface_type* t2) const
8829 for (Assume_identical* p = this->assume_identical_;
8830 p != NULL;
8831 p = p->next)
8832 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
8833 return true;
8834 return false;
8837 // Whether we can assign the interface type T to this type. The types
8838 // are known to not be identical. An interface assignment is only
8839 // permitted if T is known to implement all methods in THIS.
8840 // Otherwise a type guard is required.
8842 bool
8843 Interface_type::is_compatible_for_assign(const Interface_type* t,
8844 std::string* reason) const
8846 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
8847 if (this->all_methods_ == NULL)
8848 return true;
8849 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8850 p != this->all_methods_->end();
8851 ++p)
8853 const Typed_identifier* m = t->find_method(p->name());
8854 if (m == NULL)
8856 if (reason != NULL)
8858 char buf[200];
8859 snprintf(buf, sizeof buf,
8860 _("need explicit conversion; missing method %s%s%s"),
8861 go_open_quote(), Gogo::message_name(p->name()).c_str(),
8862 go_close_quote());
8863 reason->assign(buf);
8865 return false;
8868 std::string subreason;
8869 if (!Type::are_identical(p->type(), m->type(), true, &subreason))
8871 if (reason != NULL)
8873 std::string n = Gogo::message_name(p->name());
8874 size_t len = 100 + n.length() + subreason.length();
8875 char* buf = new char[len];
8876 if (subreason.empty())
8877 snprintf(buf, len, _("incompatible type for method %s%s%s"),
8878 go_open_quote(), n.c_str(), go_close_quote());
8879 else
8880 snprintf(buf, len,
8881 _("incompatible type for method %s%s%s (%s)"),
8882 go_open_quote(), n.c_str(), go_close_quote(),
8883 subreason.c_str());
8884 reason->assign(buf);
8885 delete[] buf;
8887 return false;
8891 return true;
8894 // Hash code.
8896 unsigned int
8897 Interface_type::do_hash_for_method(Gogo*) const
8899 go_assert(this->methods_are_finalized_);
8900 unsigned int ret = 0;
8901 if (this->all_methods_ != NULL)
8903 for (Typed_identifier_list::const_iterator p =
8904 this->all_methods_->begin();
8905 p != this->all_methods_->end();
8906 ++p)
8908 ret = Type::hash_string(p->name(), ret);
8909 // We don't use the method type in the hash, to avoid
8910 // infinite recursion if an interface method uses a type
8911 // which is an interface which inherits from the interface
8912 // itself.
8913 // type T interface { F() interface {T}}
8914 ret <<= 1;
8917 return ret;
8920 // Return true if T implements the interface. If it does not, and
8921 // REASON is not NULL, set *REASON to a useful error message.
8923 bool
8924 Interface_type::implements_interface(const Type* t, std::string* reason) const
8926 go_assert(this->methods_are_finalized_);
8927 if (this->all_methods_ == NULL)
8928 return true;
8930 bool is_pointer = false;
8931 const Named_type* nt = t->named_type();
8932 const Struct_type* st = t->struct_type();
8933 // If we start with a named type, we don't dereference it to find
8934 // methods.
8935 if (nt == NULL)
8937 const Type* pt = t->points_to();
8938 if (pt != NULL)
8940 // If T is a pointer to a named type, then we need to look at
8941 // the type to which it points.
8942 is_pointer = true;
8943 nt = pt->named_type();
8944 st = pt->struct_type();
8948 // If we have a named type, get the methods from it rather than from
8949 // any struct type.
8950 if (nt != NULL)
8951 st = NULL;
8953 // Only named and struct types have methods.
8954 if (nt == NULL && st == NULL)
8956 if (reason != NULL)
8958 if (t->points_to() != NULL
8959 && t->points_to()->interface_type() != NULL)
8960 reason->assign(_("pointer to interface type has no methods"));
8961 else
8962 reason->assign(_("type has no methods"));
8964 return false;
8967 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
8969 if (reason != NULL)
8971 if (t->points_to() != NULL
8972 && t->points_to()->interface_type() != NULL)
8973 reason->assign(_("pointer to interface type has no methods"));
8974 else
8975 reason->assign(_("type has no methods"));
8977 return false;
8980 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
8981 p != this->all_methods_->end();
8982 ++p)
8984 bool is_ambiguous = false;
8985 Method* m = (nt != NULL
8986 ? nt->method_function(p->name(), &is_ambiguous)
8987 : st->method_function(p->name(), &is_ambiguous));
8988 if (m == NULL)
8990 if (reason != NULL)
8992 std::string n = Gogo::message_name(p->name());
8993 size_t len = n.length() + 100;
8994 char* buf = new char[len];
8995 if (is_ambiguous)
8996 snprintf(buf, len, _("ambiguous method %s%s%s"),
8997 go_open_quote(), n.c_str(), go_close_quote());
8998 else
8999 snprintf(buf, len, _("missing method %s%s%s"),
9000 go_open_quote(), n.c_str(), go_close_quote());
9001 reason->assign(buf);
9002 delete[] buf;
9004 return false;
9007 Function_type *p_fn_type = p->type()->function_type();
9008 Function_type* m_fn_type = m->type()->function_type();
9009 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9010 std::string subreason;
9011 if (!p_fn_type->is_identical(m_fn_type, true, COMPARE_TAGS, true,
9012 &subreason))
9014 if (reason != NULL)
9016 std::string n = Gogo::message_name(p->name());
9017 size_t len = 100 + n.length() + subreason.length();
9018 char* buf = new char[len];
9019 if (subreason.empty())
9020 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9021 go_open_quote(), n.c_str(), go_close_quote());
9022 else
9023 snprintf(buf, len,
9024 _("incompatible type for method %s%s%s (%s)"),
9025 go_open_quote(), n.c_str(), go_close_quote(),
9026 subreason.c_str());
9027 reason->assign(buf);
9028 delete[] buf;
9030 return false;
9033 if (!is_pointer && !m->is_value_method())
9035 if (reason != NULL)
9037 std::string n = Gogo::message_name(p->name());
9038 size_t len = 100 + n.length();
9039 char* buf = new char[len];
9040 snprintf(buf, len,
9041 _("method %s%s%s requires a pointer receiver"),
9042 go_open_quote(), n.c_str(), go_close_quote());
9043 reason->assign(buf);
9044 delete[] buf;
9046 return false;
9049 // If the magic //go:nointerface comment was used, the method
9050 // may not be used to implement interfaces.
9051 if (m->nointerface())
9053 if (reason != NULL)
9055 std::string n = Gogo::message_name(p->name());
9056 size_t len = 100 + n.length();
9057 char* buf = new char[len];
9058 snprintf(buf, len,
9059 _("method %s%s%s is marked go:nointerface"),
9060 go_open_quote(), n.c_str(), go_close_quote());
9061 reason->assign(buf);
9062 delete[] buf;
9064 return false;
9068 return true;
9071 // Return the backend representation of the empty interface type. We
9072 // use the same struct for all empty interfaces.
9074 Btype*
9075 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9077 static Btype* empty_interface_type;
9078 if (empty_interface_type == NULL)
9080 std::vector<Backend::Btyped_identifier> bfields(2);
9082 Location bloc = Linemap::predeclared_location();
9084 Type* pdt = Type::make_type_descriptor_ptr_type();
9085 bfields[0].name = "__type_descriptor";
9086 bfields[0].btype = pdt->get_backend(gogo);
9087 bfields[0].location = bloc;
9089 Type* vt = Type::make_pointer_type(Type::make_void_type());
9090 bfields[1].name = "__object";
9091 bfields[1].btype = vt->get_backend(gogo);
9092 bfields[1].location = bloc;
9094 empty_interface_type = gogo->backend()->struct_type(bfields);
9096 return empty_interface_type;
9099 Interface_type::Bmethods_map Interface_type::bmethods_map;
9101 // Return a pointer to the backend representation of the method table.
9103 Btype*
9104 Interface_type::get_backend_methods(Gogo* gogo)
9106 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9107 return this->bmethods_;
9109 std::pair<Interface_type*, Bmethods_map_entry> val;
9110 val.first = this;
9111 val.second.btype = NULL;
9112 val.second.is_placeholder = false;
9113 std::pair<Bmethods_map::iterator, bool> ins =
9114 Interface_type::bmethods_map.insert(val);
9115 if (!ins.second
9116 && ins.first->second.btype != NULL
9117 && !ins.first->second.is_placeholder)
9119 this->bmethods_ = ins.first->second.btype;
9120 this->bmethods_is_placeholder_ = false;
9121 return this->bmethods_;
9124 Location loc = this->location();
9126 std::vector<Backend::Btyped_identifier>
9127 mfields(this->all_methods_->size() + 1);
9129 Type* pdt = Type::make_type_descriptor_ptr_type();
9130 mfields[0].name = "__type_descriptor";
9131 mfields[0].btype = pdt->get_backend(gogo);
9132 mfields[0].location = loc;
9134 std::string last_name = "";
9135 size_t i = 1;
9136 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9137 p != this->all_methods_->end();
9138 ++p, ++i)
9140 // The type of the method in Go only includes the parameters.
9141 // The actual method also has a receiver, which is always a
9142 // pointer. We need to add that pointer type here in order to
9143 // generate the correct type for the backend.
9144 Function_type* ft = p->type()->function_type();
9145 go_assert(ft->receiver() == NULL);
9147 const Typed_identifier_list* params = ft->parameters();
9148 Typed_identifier_list* mparams = new Typed_identifier_list();
9149 if (params != NULL)
9150 mparams->reserve(params->size() + 1);
9151 Type* vt = Type::make_pointer_type(Type::make_void_type());
9152 mparams->push_back(Typed_identifier("", vt, ft->location()));
9153 if (params != NULL)
9155 for (Typed_identifier_list::const_iterator pp = params->begin();
9156 pp != params->end();
9157 ++pp)
9158 mparams->push_back(*pp);
9161 Typed_identifier_list* mresults = (ft->results() == NULL
9162 ? NULL
9163 : ft->results()->copy());
9164 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9165 ft->location());
9167 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9168 mfields[i].btype = mft->get_backend_fntype(gogo);
9169 mfields[i].location = loc;
9171 // Sanity check: the names should be sorted.
9172 go_assert(Gogo::unpack_hidden_name(p->name())
9173 > Gogo::unpack_hidden_name(last_name));
9174 last_name = p->name();
9177 Btype* st = gogo->backend()->struct_type(mfields);
9178 Btype* ret = gogo->backend()->pointer_type(st);
9180 if (ins.first->second.btype != NULL
9181 && ins.first->second.is_placeholder)
9182 gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9183 ret);
9184 this->bmethods_ = ret;
9185 ins.first->second.btype = ret;
9186 this->bmethods_is_placeholder_ = false;
9187 ins.first->second.is_placeholder = false;
9188 return ret;
9191 // Return a placeholder for the pointer to the backend methods table.
9193 Btype*
9194 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9196 if (this->bmethods_ == NULL)
9198 std::pair<Interface_type*, Bmethods_map_entry> val;
9199 val.first = this;
9200 val.second.btype = NULL;
9201 val.second.is_placeholder = false;
9202 std::pair<Bmethods_map::iterator, bool> ins =
9203 Interface_type::bmethods_map.insert(val);
9204 if (!ins.second && ins.first->second.btype != NULL)
9206 this->bmethods_ = ins.first->second.btype;
9207 this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9208 return this->bmethods_;
9211 Location loc = this->location();
9212 Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9213 this->bmethods_ = bt;
9214 ins.first->second.btype = bt;
9215 this->bmethods_is_placeholder_ = true;
9216 ins.first->second.is_placeholder = true;
9218 return this->bmethods_;
9221 // Return the fields of a non-empty interface type. This is not
9222 // declared in types.h so that types.h doesn't have to #include
9223 // backend.h.
9225 static void
9226 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9227 bool use_placeholder,
9228 std::vector<Backend::Btyped_identifier>* bfields)
9230 Location loc = type->location();
9232 bfields->resize(2);
9234 (*bfields)[0].name = "__methods";
9235 (*bfields)[0].btype = (use_placeholder
9236 ? type->get_backend_methods_placeholder(gogo)
9237 : type->get_backend_methods(gogo));
9238 (*bfields)[0].location = loc;
9240 Type* vt = Type::make_pointer_type(Type::make_void_type());
9241 (*bfields)[1].name = "__object";
9242 (*bfields)[1].btype = vt->get_backend(gogo);
9243 (*bfields)[1].location = Linemap::predeclared_location();
9246 // Return the backend representation for an interface type. An interface is a
9247 // pointer to a struct. The struct has three fields. The first field is a
9248 // pointer to the type descriptor for the dynamic type of the object.
9249 // The second field is a pointer to a table of methods for the
9250 // interface to be used with the object. The third field is the value
9251 // of the object itself.
9253 Btype*
9254 Interface_type::do_get_backend(Gogo* gogo)
9256 if (this->is_empty())
9257 return Interface_type::get_backend_empty_interface_type(gogo);
9258 else
9260 if (this->interface_btype_ != NULL)
9261 return this->interface_btype_;
9262 this->interface_btype_ =
9263 gogo->backend()->placeholder_struct_type("", this->location_);
9264 std::vector<Backend::Btyped_identifier> bfields;
9265 get_backend_interface_fields(gogo, this, false, &bfields);
9266 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
9267 bfields))
9268 this->interface_btype_ = gogo->backend()->error_type();
9269 return this->interface_btype_;
9273 // Finish the backend representation of the methods.
9275 void
9276 Interface_type::finish_backend_methods(Gogo* gogo)
9278 if (!this->is_empty())
9280 const Typed_identifier_list* methods = this->methods();
9281 if (methods != NULL)
9283 for (Typed_identifier_list::const_iterator p = methods->begin();
9284 p != methods->end();
9285 ++p)
9286 p->type()->get_backend(gogo);
9289 // Getting the backend methods now will set the placeholder
9290 // pointer.
9291 this->get_backend_methods(gogo);
9295 // The type of an interface type descriptor.
9297 Type*
9298 Interface_type::make_interface_type_descriptor_type()
9300 static Type* ret;
9301 if (ret == NULL)
9303 Type* tdt = Type::make_type_descriptor_type();
9304 Type* ptdt = Type::make_type_descriptor_ptr_type();
9306 Type* string_type = Type::lookup_string_type();
9307 Type* pointer_string_type = Type::make_pointer_type(string_type);
9309 Struct_type* sm =
9310 Type::make_builtin_struct_type(3,
9311 "name", pointer_string_type,
9312 "pkgPath", pointer_string_type,
9313 "typ", ptdt);
9315 Type* nsm = Type::make_builtin_named_type("imethod", sm);
9317 Type* slice_nsm = Type::make_array_type(nsm, NULL);
9319 Struct_type* s = Type::make_builtin_struct_type(2,
9320 "", tdt,
9321 "methods", slice_nsm);
9323 ret = Type::make_builtin_named_type("InterfaceType", s);
9326 return ret;
9329 // Build a type descriptor for an interface type.
9331 Expression*
9332 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9334 Location bloc = Linemap::predeclared_location();
9336 Type* itdt = Interface_type::make_interface_type_descriptor_type();
9338 const Struct_field_list* ifields = itdt->struct_type()->fields();
9340 Expression_list* ivals = new Expression_list();
9341 ivals->reserve(2);
9343 Struct_field_list::const_iterator pif = ifields->begin();
9344 go_assert(pif->is_field_name("_type"));
9345 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
9346 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
9347 true));
9349 ++pif;
9350 go_assert(pif->is_field_name("methods"));
9352 Expression_list* methods = new Expression_list();
9353 if (this->all_methods_ != NULL)
9355 Type* elemtype = pif->type()->array_type()->element_type();
9357 methods->reserve(this->all_methods_->size());
9358 for (Typed_identifier_list::const_iterator pm =
9359 this->all_methods_->begin();
9360 pm != this->all_methods_->end();
9361 ++pm)
9363 const Struct_field_list* mfields = elemtype->struct_type()->fields();
9365 Expression_list* mvals = new Expression_list();
9366 mvals->reserve(3);
9368 Struct_field_list::const_iterator pmf = mfields->begin();
9369 go_assert(pmf->is_field_name("name"));
9370 std::string s = Gogo::unpack_hidden_name(pm->name());
9371 Expression* e = Expression::make_string(s, bloc);
9372 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9374 ++pmf;
9375 go_assert(pmf->is_field_name("pkgPath"));
9376 if (!Gogo::is_hidden_name(pm->name()))
9377 mvals->push_back(Expression::make_nil(bloc));
9378 else
9380 s = Gogo::hidden_name_pkgpath(pm->name());
9381 e = Expression::make_string(s, bloc);
9382 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
9385 ++pmf;
9386 go_assert(pmf->is_field_name("typ"));
9387 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
9389 ++pmf;
9390 go_assert(pmf == mfields->end());
9392 e = Expression::make_struct_composite_literal(elemtype, mvals,
9393 bloc);
9394 methods->push_back(e);
9398 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
9399 methods, bloc));
9401 ++pif;
9402 go_assert(pif == ifields->end());
9404 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
9407 // Reflection string.
9409 void
9410 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
9412 ret->append("interface {");
9413 const Typed_identifier_list* methods = this->parse_methods_;
9414 if (methods != NULL)
9416 ret->push_back(' ');
9417 for (Typed_identifier_list::const_iterator p = methods->begin();
9418 p != methods->end();
9419 ++p)
9421 if (p != methods->begin())
9422 ret->append("; ");
9423 if (p->name().empty())
9424 this->append_reflection(p->type(), gogo, ret);
9425 else
9427 if (!Gogo::is_hidden_name(p->name()))
9428 ret->append(p->name());
9429 else if (gogo->pkgpath_from_option())
9430 ret->append(p->name().substr(1));
9431 else
9433 // If no -fgo-pkgpath option, backward compatibility
9434 // for how this used to work before -fgo-pkgpath was
9435 // introduced.
9436 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
9437 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
9438 ret->push_back('.');
9439 ret->append(Gogo::unpack_hidden_name(p->name()));
9441 std::string sub = p->type()->reflection(gogo);
9442 go_assert(sub.compare(0, 4, "func") == 0);
9443 sub = sub.substr(4);
9444 ret->append(sub);
9447 ret->push_back(' ');
9449 ret->append("}");
9452 // Export.
9454 void
9455 Interface_type::do_export(Export* exp) const
9457 exp->write_c_string("interface { ");
9459 const Typed_identifier_list* methods = this->parse_methods_;
9460 if (methods != NULL)
9462 for (Typed_identifier_list::const_iterator pm = methods->begin();
9463 pm != methods->end();
9464 ++pm)
9466 if (pm->name().empty())
9468 exp->write_c_string("? ");
9469 exp->write_type(pm->type());
9471 else
9473 exp->write_string(pm->name());
9474 exp->write_c_string(" (");
9476 const Function_type* fntype = pm->type()->function_type();
9478 bool first = true;
9479 const Typed_identifier_list* parameters = fntype->parameters();
9480 if (parameters != NULL)
9482 bool is_varargs = fntype->is_varargs();
9483 for (Typed_identifier_list::const_iterator pp =
9484 parameters->begin();
9485 pp != parameters->end();
9486 ++pp)
9488 if (first)
9489 first = false;
9490 else
9491 exp->write_c_string(", ");
9492 exp->write_name(pp->name());
9493 exp->write_c_string(" ");
9494 if (!is_varargs || pp + 1 != parameters->end())
9495 exp->write_type(pp->type());
9496 else
9498 exp->write_c_string("...");
9499 Type *pptype = pp->type();
9500 exp->write_type(pptype->array_type()->element_type());
9505 exp->write_c_string(")");
9507 const Typed_identifier_list* results = fntype->results();
9508 if (results != NULL)
9510 exp->write_c_string(" ");
9511 if (results->size() == 1 && results->begin()->name().empty())
9512 exp->write_type(results->begin()->type());
9513 else
9515 first = true;
9516 exp->write_c_string("(");
9517 for (Typed_identifier_list::const_iterator p =
9518 results->begin();
9519 p != results->end();
9520 ++p)
9522 if (first)
9523 first = false;
9524 else
9525 exp->write_c_string(", ");
9526 exp->write_name(p->name());
9527 exp->write_c_string(" ");
9528 exp->write_type(p->type());
9530 exp->write_c_string(")");
9535 exp->write_c_string("; ");
9539 exp->write_c_string("}");
9542 // Import an interface type.
9544 Interface_type*
9545 Interface_type::do_import(Import* imp)
9547 imp->require_c_string("interface { ");
9549 Typed_identifier_list* methods = new Typed_identifier_list;
9550 while (imp->peek_char() != '}')
9552 std::string name = imp->read_identifier();
9554 if (name == "?")
9556 imp->require_c_string(" ");
9557 Type* t = imp->read_type();
9558 methods->push_back(Typed_identifier("", t, imp->location()));
9559 imp->require_c_string("; ");
9560 continue;
9563 imp->require_c_string(" (");
9565 Typed_identifier_list* parameters;
9566 bool is_varargs = false;
9567 if (imp->peek_char() == ')')
9568 parameters = NULL;
9569 else
9571 parameters = new Typed_identifier_list;
9572 while (true)
9574 std::string name = imp->read_name();
9575 imp->require_c_string(" ");
9577 if (imp->match_c_string("..."))
9579 imp->advance(3);
9580 is_varargs = true;
9583 Type* ptype = imp->read_type();
9584 if (is_varargs)
9585 ptype = Type::make_array_type(ptype, NULL);
9586 parameters->push_back(Typed_identifier(name, ptype,
9587 imp->location()));
9588 if (imp->peek_char() != ',')
9589 break;
9590 go_assert(!is_varargs);
9591 imp->require_c_string(", ");
9594 imp->require_c_string(")");
9596 Typed_identifier_list* results;
9597 if (imp->peek_char() != ' ')
9598 results = NULL;
9599 else
9601 results = new Typed_identifier_list;
9602 imp->advance(1);
9603 if (imp->peek_char() != '(')
9605 Type* rtype = imp->read_type();
9606 results->push_back(Typed_identifier("", rtype, imp->location()));
9608 else
9610 imp->advance(1);
9611 while (true)
9613 std::string name = imp->read_name();
9614 imp->require_c_string(" ");
9615 Type* rtype = imp->read_type();
9616 results->push_back(Typed_identifier(name, rtype,
9617 imp->location()));
9618 if (imp->peek_char() != ',')
9619 break;
9620 imp->require_c_string(", ");
9622 imp->require_c_string(")");
9626 Function_type* fntype = Type::make_function_type(NULL, parameters,
9627 results,
9628 imp->location());
9629 if (is_varargs)
9630 fntype->set_is_varargs();
9631 methods->push_back(Typed_identifier(name, fntype, imp->location()));
9633 imp->require_c_string("; ");
9636 imp->require_c_string("}");
9638 if (methods->empty())
9640 delete methods;
9641 methods = NULL;
9644 Interface_type* ret = Type::make_interface_type(methods, imp->location());
9645 ret->package_ = imp->package();
9646 return ret;
9649 // Make an interface type.
9651 Interface_type*
9652 Type::make_interface_type(Typed_identifier_list* methods,
9653 Location location)
9655 return new Interface_type(methods, location);
9658 // Make an empty interface type.
9660 Interface_type*
9661 Type::make_empty_interface_type(Location location)
9663 Interface_type* ret = new Interface_type(NULL, location);
9664 ret->finalize_methods();
9665 return ret;
9668 // Class Method.
9670 // Bind a method to an object.
9672 Expression*
9673 Method::bind_method(Expression* expr, Location location) const
9675 if (this->stub_ == NULL)
9677 // When there is no stub object, the binding is determined by
9678 // the child class.
9679 return this->do_bind_method(expr, location);
9681 return Expression::make_bound_method(expr, this, this->stub_, location);
9684 // Return the named object associated with a method. This may only be
9685 // called after methods are finalized.
9687 Named_object*
9688 Method::named_object() const
9690 if (this->stub_ != NULL)
9691 return this->stub_;
9692 return this->do_named_object();
9695 // Class Named_method.
9697 // The type of the method.
9699 Function_type*
9700 Named_method::do_type() const
9702 if (this->named_object_->is_function())
9703 return this->named_object_->func_value()->type();
9704 else if (this->named_object_->is_function_declaration())
9705 return this->named_object_->func_declaration_value()->type();
9706 else
9707 go_unreachable();
9710 // Return the location of the method receiver.
9712 Location
9713 Named_method::do_receiver_location() const
9715 return this->do_type()->receiver()->location();
9718 // Bind a method to an object.
9720 Expression*
9721 Named_method::do_bind_method(Expression* expr, Location location) const
9723 Named_object* no = this->named_object_;
9724 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
9725 no, location);
9726 // If this is not a local method, and it does not use a stub, then
9727 // the real method expects a different type. We need to cast the
9728 // first argument.
9729 if (this->depth() > 0 && !this->needs_stub_method())
9731 Function_type* ftype = this->do_type();
9732 go_assert(ftype->is_method());
9733 Type* frtype = ftype->receiver()->type();
9734 bme->set_first_argument_type(frtype);
9736 return bme;
9739 // Return whether this method should not participate in interfaces.
9741 bool
9742 Named_method::do_nointerface() const
9744 Named_object* no = this->named_object_;
9745 if (no->is_function())
9746 return no->func_value()->nointerface();
9747 else if (no->is_function_declaration())
9748 return no->func_declaration_value()->nointerface();
9749 else
9750 go_unreachable();
9753 // Class Interface_method.
9755 // Bind a method to an object.
9757 Expression*
9758 Interface_method::do_bind_method(Expression* expr,
9759 Location location) const
9761 return Expression::make_interface_field_reference(expr, this->name_,
9762 location);
9765 // Class Methods.
9767 // Insert a new method. Return true if it was inserted, false
9768 // otherwise.
9770 bool
9771 Methods::insert(const std::string& name, Method* m)
9773 std::pair<Method_map::iterator, bool> ins =
9774 this->methods_.insert(std::make_pair(name, m));
9775 if (ins.second)
9776 return true;
9777 else
9779 Method* old_method = ins.first->second;
9780 if (m->depth() < old_method->depth())
9782 delete old_method;
9783 ins.first->second = m;
9784 return true;
9786 else
9788 if (m->depth() == old_method->depth())
9789 old_method->set_is_ambiguous();
9790 return false;
9795 // Return the number of unambiguous methods.
9797 size_t
9798 Methods::count() const
9800 size_t ret = 0;
9801 for (Method_map::const_iterator p = this->methods_.begin();
9802 p != this->methods_.end();
9803 ++p)
9804 if (!p->second->is_ambiguous())
9805 ++ret;
9806 return ret;
9809 // Class Named_type.
9811 // Return the name of the type.
9813 const std::string&
9814 Named_type::name() const
9816 return this->named_object_->name();
9819 // Return the name of the type to use in an error message.
9821 std::string
9822 Named_type::message_name() const
9824 return this->named_object_->message_name();
9827 // Return the base type for this type. We have to be careful about
9828 // circular type definitions, which are invalid but may be seen here.
9830 Type*
9831 Named_type::named_base()
9833 if (this->seen_)
9834 return this;
9835 this->seen_ = true;
9836 Type* ret = this->type_->base();
9837 this->seen_ = false;
9838 return ret;
9841 const Type*
9842 Named_type::named_base() const
9844 if (this->seen_)
9845 return this;
9846 this->seen_ = true;
9847 const Type* ret = this->type_->base();
9848 this->seen_ = false;
9849 return ret;
9852 // Return whether this is an error type. We have to be careful about
9853 // circular type definitions, which are invalid but may be seen here.
9855 bool
9856 Named_type::is_named_error_type() const
9858 if (this->seen_)
9859 return false;
9860 this->seen_ = true;
9861 bool ret = this->type_->is_error_type();
9862 this->seen_ = false;
9863 return ret;
9866 // Whether this type is comparable. We have to be careful about
9867 // circular type definitions.
9869 bool
9870 Named_type::named_type_is_comparable(std::string* reason) const
9872 if (this->seen_)
9873 return false;
9874 this->seen_ = true;
9875 bool ret = Type::are_compatible_for_comparison(true, this->type_,
9876 this->type_, reason);
9877 this->seen_ = false;
9878 return ret;
9881 // Add a method to this type.
9883 Named_object*
9884 Named_type::add_method(const std::string& name, Function* function)
9886 go_assert(!this->is_alias_);
9887 if (this->local_methods_ == NULL)
9888 this->local_methods_ = new Bindings(NULL);
9889 return this->local_methods_->add_function(name, NULL, function);
9892 // Add a method declaration to this type.
9894 Named_object*
9895 Named_type::add_method_declaration(const std::string& name, Package* package,
9896 Function_type* type,
9897 Location location)
9899 go_assert(!this->is_alias_);
9900 if (this->local_methods_ == NULL)
9901 this->local_methods_ = new Bindings(NULL);
9902 return this->local_methods_->add_function_declaration(name, package, type,
9903 location);
9906 // Add an existing method to this type.
9908 void
9909 Named_type::add_existing_method(Named_object* no)
9911 go_assert(!this->is_alias_);
9912 if (this->local_methods_ == NULL)
9913 this->local_methods_ = new Bindings(NULL);
9914 this->local_methods_->add_named_object(no);
9917 // Look for a local method NAME, and returns its named object, or NULL
9918 // if not there.
9920 Named_object*
9921 Named_type::find_local_method(const std::string& name) const
9923 if (this->is_error_)
9924 return NULL;
9925 if (this->is_alias_)
9927 Named_type* nt = this->type_->named_type();
9928 if (nt != NULL)
9930 if (this->seen_alias_)
9931 return NULL;
9932 this->seen_alias_ = true;
9933 Named_object* ret = nt->find_local_method(name);
9934 this->seen_alias_ = false;
9935 return ret;
9937 return NULL;
9939 if (this->local_methods_ == NULL)
9940 return NULL;
9941 return this->local_methods_->lookup(name);
9944 // Return the list of local methods.
9946 const Bindings*
9947 Named_type::local_methods() const
9949 if (this->is_error_)
9950 return NULL;
9951 if (this->is_alias_)
9953 Named_type* nt = this->type_->named_type();
9954 if (nt != NULL)
9956 if (this->seen_alias_)
9957 return NULL;
9958 this->seen_alias_ = true;
9959 const Bindings* ret = nt->local_methods();
9960 this->seen_alias_ = false;
9961 return ret;
9963 return NULL;
9965 return this->local_methods_;
9968 // Return whether NAME is an unexported field or method, for better
9969 // error reporting.
9971 bool
9972 Named_type::is_unexported_local_method(Gogo* gogo,
9973 const std::string& name) const
9975 if (this->is_error_)
9976 return false;
9977 if (this->is_alias_)
9979 Named_type* nt = this->type_->named_type();
9980 if (nt != NULL)
9982 if (this->seen_alias_)
9983 return false;
9984 this->seen_alias_ = true;
9985 bool ret = nt->is_unexported_local_method(gogo, name);
9986 this->seen_alias_ = false;
9987 return ret;
9989 return false;
9991 Bindings* methods = this->local_methods_;
9992 if (methods != NULL)
9994 for (Bindings::const_declarations_iterator p =
9995 methods->begin_declarations();
9996 p != methods->end_declarations();
9997 ++p)
9999 if (Gogo::is_hidden_name(p->first)
10000 && name == Gogo::unpack_hidden_name(p->first)
10001 && gogo->pack_hidden_name(name, false) != p->first)
10002 return true;
10005 return false;
10008 // Build the complete list of methods for this type, which means
10009 // recursively including all methods for anonymous fields. Create all
10010 // stub methods.
10012 void
10013 Named_type::finalize_methods(Gogo* gogo)
10015 if (this->is_alias_)
10016 return;
10017 if (this->all_methods_ != NULL)
10018 return;
10020 if (this->local_methods_ != NULL
10021 && (this->points_to() != NULL || this->interface_type() != NULL))
10023 const Bindings* lm = this->local_methods_;
10024 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10025 p != lm->end_declarations();
10026 ++p)
10027 go_error_at(p->second->location(),
10028 "invalid pointer or interface receiver type");
10029 delete this->local_methods_;
10030 this->local_methods_ = NULL;
10031 return;
10034 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10037 // Return whether this type has any methods.
10039 bool
10040 Named_type::has_any_methods() const
10042 if (this->is_error_)
10043 return false;
10044 if (this->is_alias_)
10046 if (this->type_->named_type() != NULL)
10048 if (this->seen_alias_)
10049 return false;
10050 this->seen_alias_ = true;
10051 bool ret = this->type_->named_type()->has_any_methods();
10052 this->seen_alias_ = false;
10053 return ret;
10055 if (this->type_->struct_type() != NULL)
10056 return this->type_->struct_type()->has_any_methods();
10057 return false;
10059 return this->all_methods_ != NULL;
10062 // Return the methods for this type.
10064 const Methods*
10065 Named_type::methods() const
10067 if (this->is_error_)
10068 return NULL;
10069 if (this->is_alias_)
10071 if (this->type_->named_type() != NULL)
10073 if (this->seen_alias_)
10074 return NULL;
10075 this->seen_alias_ = true;
10076 const Methods* ret = this->type_->named_type()->methods();
10077 this->seen_alias_ = false;
10078 return ret;
10080 if (this->type_->struct_type() != NULL)
10081 return this->type_->struct_type()->methods();
10082 return NULL;
10084 return this->all_methods_;
10087 // Return the method NAME, or NULL if there isn't one or if it is
10088 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10089 // ambiguous.
10091 Method*
10092 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10094 if (this->is_error_)
10095 return NULL;
10096 if (this->is_alias_)
10098 if (is_ambiguous != NULL)
10099 *is_ambiguous = false;
10100 if (this->type_->named_type() != NULL)
10102 if (this->seen_alias_)
10103 return NULL;
10104 this->seen_alias_ = true;
10105 Named_type* nt = this->type_->named_type();
10106 Method* ret = nt->method_function(name, is_ambiguous);
10107 this->seen_alias_ = false;
10108 return ret;
10110 if (this->type_->struct_type() != NULL)
10111 return this->type_->struct_type()->method_function(name, is_ambiguous);
10112 return NULL;
10114 return Type::method_function(this->all_methods_, name, is_ambiguous);
10117 // Return a pointer to the interface method table for this type for
10118 // the interface INTERFACE. IS_POINTER is true if this is for a
10119 // pointer to THIS.
10121 Expression*
10122 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10124 if (this->is_error_)
10125 return Expression::make_error(this->location_);
10126 if (this->is_alias_)
10128 if (this->type_->named_type() != NULL)
10130 if (this->seen_alias_)
10131 return Expression::make_error(this->location_);
10132 this->seen_alias_ = true;
10133 Named_type* nt = this->type_->named_type();
10134 Expression* ret = nt->interface_method_table(interface, is_pointer);
10135 this->seen_alias_ = false;
10136 return ret;
10138 if (this->type_->struct_type() != NULL)
10139 return this->type_->struct_type()->interface_method_table(interface,
10140 is_pointer);
10141 go_unreachable();
10143 return Type::interface_method_table(this, interface, is_pointer,
10144 &this->interface_method_tables_,
10145 &this->pointer_interface_method_tables_);
10148 // Look for a use of a complete type within another type. This is
10149 // used to check that we don't try to use a type within itself.
10151 class Find_type_use : public Traverse
10153 public:
10154 Find_type_use(Named_type* find_type)
10155 : Traverse(traverse_types),
10156 find_type_(find_type), found_(false)
10159 // Whether we found the type.
10160 bool
10161 found() const
10162 { return this->found_; }
10164 protected:
10166 type(Type*);
10168 private:
10169 // The type we are looking for.
10170 Named_type* find_type_;
10171 // Whether we found the type.
10172 bool found_;
10175 // Check for FIND_TYPE in TYPE.
10178 Find_type_use::type(Type* type)
10180 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10182 this->found_ = true;
10183 return TRAVERSE_EXIT;
10186 // It's OK if we see a reference to the type in any type which is
10187 // essentially a pointer: a pointer, a slice, a function, a map, or
10188 // a channel.
10189 if (type->points_to() != NULL
10190 || type->is_slice_type()
10191 || type->function_type() != NULL
10192 || type->map_type() != NULL
10193 || type->channel_type() != NULL)
10194 return TRAVERSE_SKIP_COMPONENTS;
10196 // For an interface, a reference to the type in a method type should
10197 // be ignored, but we have to consider direct inheritance. When
10198 // this is called, there may be cases of direct inheritance
10199 // represented as a method with no name.
10200 if (type->interface_type() != NULL)
10202 const Typed_identifier_list* methods = type->interface_type()->methods();
10203 if (methods != NULL)
10205 for (Typed_identifier_list::const_iterator p = methods->begin();
10206 p != methods->end();
10207 ++p)
10209 if (p->name().empty())
10211 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
10212 return TRAVERSE_EXIT;
10216 return TRAVERSE_SKIP_COMPONENTS;
10219 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
10220 // to convert TYPE to the backend representation before we convert
10221 // FIND_TYPE_.
10222 if (type->named_type() != NULL)
10224 switch (type->base()->classification())
10226 case Type::TYPE_ERROR:
10227 case Type::TYPE_BOOLEAN:
10228 case Type::TYPE_INTEGER:
10229 case Type::TYPE_FLOAT:
10230 case Type::TYPE_COMPLEX:
10231 case Type::TYPE_STRING:
10232 case Type::TYPE_NIL:
10233 break;
10235 case Type::TYPE_ARRAY:
10236 case Type::TYPE_STRUCT:
10237 this->find_type_->add_dependency(type->named_type());
10238 break;
10240 case Type::TYPE_NAMED:
10241 case Type::TYPE_FORWARD:
10242 go_assert(saw_errors());
10243 break;
10245 case Type::TYPE_VOID:
10246 case Type::TYPE_SINK:
10247 case Type::TYPE_FUNCTION:
10248 case Type::TYPE_POINTER:
10249 case Type::TYPE_CALL_MULTIPLE_RESULT:
10250 case Type::TYPE_MAP:
10251 case Type::TYPE_CHANNEL:
10252 case Type::TYPE_INTERFACE:
10253 default:
10254 go_unreachable();
10258 return TRAVERSE_CONTINUE;
10261 // Look for a circular reference of an alias.
10263 class Find_alias : public Traverse
10265 public:
10266 Find_alias(Named_type* find_type)
10267 : Traverse(traverse_types),
10268 find_type_(find_type), found_(false)
10271 // Whether we found the type.
10272 bool
10273 found() const
10274 { return this->found_; }
10276 protected:
10278 type(Type*);
10280 private:
10281 // The type we are looking for.
10282 Named_type* find_type_;
10283 // Whether we found the type.
10284 bool found_;
10288 Find_alias::type(Type* type)
10290 Named_type* nt = type->named_type();
10291 if (nt != NULL)
10293 if (nt == this->find_type_)
10295 this->found_ = true;
10296 return TRAVERSE_EXIT;
10299 // We started from `type T1 = T2`, where T1 is find_type_ and T2
10300 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
10301 // an alias itself, it's OK if whatever T2 is defined as refers
10302 // to T1.
10303 if (!nt->is_alias())
10304 return TRAVERSE_SKIP_COMPONENTS;
10307 return TRAVERSE_CONTINUE;
10310 // Verify that a named type does not refer to itself.
10312 bool
10313 Named_type::do_verify()
10315 if (this->is_verified_)
10316 return true;
10317 this->is_verified_ = true;
10319 if (this->is_error_)
10320 return false;
10322 if (this->is_alias_)
10324 Find_alias find(this);
10325 Type::traverse(this->type_, &find);
10326 if (find.found())
10328 go_error_at(this->location_, "invalid recursive alias %qs",
10329 this->message_name().c_str());
10330 this->is_error_ = true;
10331 return false;
10335 Find_type_use find(this);
10336 Type::traverse(this->type_, &find);
10337 if (find.found())
10339 go_error_at(this->location_, "invalid recursive type %qs",
10340 this->message_name().c_str());
10341 this->is_error_ = true;
10342 return false;
10345 // Check whether any of the local methods overloads an existing
10346 // struct field or interface method. We don't need to check the
10347 // list of methods against itself: that is handled by the Bindings
10348 // code.
10349 if (this->local_methods_ != NULL)
10351 Struct_type* st = this->type_->struct_type();
10352 if (st != NULL)
10354 for (Bindings::const_declarations_iterator p =
10355 this->local_methods_->begin_declarations();
10356 p != this->local_methods_->end_declarations();
10357 ++p)
10359 const std::string& name(p->first);
10360 if (st != NULL && st->find_local_field(name, NULL) != NULL)
10362 go_error_at(p->second->location(),
10363 "method %qs redeclares struct field name",
10364 Gogo::message_name(name).c_str());
10370 return true;
10373 // Return whether this type is or contains a pointer.
10375 bool
10376 Named_type::do_has_pointer() const
10378 if (this->seen_)
10379 return false;
10380 this->seen_ = true;
10381 bool ret = this->type_->has_pointer();
10382 this->seen_ = false;
10383 return ret;
10386 // Return whether comparisons for this type can use the identity
10387 // function.
10389 bool
10390 Named_type::do_compare_is_identity(Gogo* gogo)
10392 // We don't use this->seen_ here because compare_is_identity may
10393 // call base() later, and that will mess up if seen_ is set here.
10394 if (this->seen_in_compare_is_identity_)
10395 return false;
10396 this->seen_in_compare_is_identity_ = true;
10397 bool ret = this->type_->compare_is_identity(gogo);
10398 this->seen_in_compare_is_identity_ = false;
10399 return ret;
10402 // Return whether this type is reflexive--whether it is always equal
10403 // to itself.
10405 bool
10406 Named_type::do_is_reflexive()
10408 if (this->seen_in_compare_is_identity_)
10409 return false;
10410 this->seen_in_compare_is_identity_ = true;
10411 bool ret = this->type_->is_reflexive();
10412 this->seen_in_compare_is_identity_ = false;
10413 return ret;
10416 // Return whether this type needs a key update when used as a map key.
10418 bool
10419 Named_type::do_needs_key_update()
10421 if (this->seen_in_compare_is_identity_)
10422 return true;
10423 this->seen_in_compare_is_identity_ = true;
10424 bool ret = this->type_->needs_key_update();
10425 this->seen_in_compare_is_identity_ = false;
10426 return ret;
10429 // Return a hash code. This is used for method lookup. We simply
10430 // hash on the name itself.
10432 unsigned int
10433 Named_type::do_hash_for_method(Gogo* gogo) const
10435 if (this->is_error_)
10436 return 0;
10438 // Aliases are handled in Type::hash_for_method.
10439 go_assert(!this->is_alias_);
10441 const std::string& name(this->named_object()->name());
10442 unsigned int ret = Type::hash_string(name, 0);
10444 // GOGO will be NULL here when called from Type_hash_identical.
10445 // That is OK because that is only used for internal hash tables
10446 // where we are going to be comparing named types for equality. In
10447 // other cases, which are cases where the runtime is going to
10448 // compare hash codes to see if the types are the same, we need to
10449 // include the pkgpath in the hash.
10450 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
10452 const Package* package = this->named_object()->package();
10453 if (package == NULL)
10454 ret = Type::hash_string(gogo->pkgpath(), ret);
10455 else
10456 ret = Type::hash_string(package->pkgpath(), ret);
10459 return ret;
10462 // Convert a named type to the backend representation. In order to
10463 // get dependencies right, we fill in a dummy structure for this type,
10464 // then convert all the dependencies, then complete this type. When
10465 // this function is complete, the size of the type is known.
10467 void
10468 Named_type::convert(Gogo* gogo)
10470 if (this->is_error_ || this->is_converted_)
10471 return;
10473 this->create_placeholder(gogo);
10475 // If we are called to turn unsafe.Sizeof into a constant, we may
10476 // not have verified the type yet. We have to make sure it is
10477 // verified, since that sets the list of dependencies.
10478 this->verify();
10480 // Convert all the dependencies. If they refer indirectly back to
10481 // this type, they will pick up the intermediate representation we just
10482 // created.
10483 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
10484 p != this->dependencies_.end();
10485 ++p)
10486 (*p)->convert(gogo);
10488 // Complete this type.
10489 Btype* bt = this->named_btype_;
10490 Type* base = this->type_->base();
10491 switch (base->classification())
10493 case TYPE_VOID:
10494 case TYPE_BOOLEAN:
10495 case TYPE_INTEGER:
10496 case TYPE_FLOAT:
10497 case TYPE_COMPLEX:
10498 case TYPE_STRING:
10499 case TYPE_NIL:
10500 break;
10502 case TYPE_MAP:
10503 case TYPE_CHANNEL:
10504 break;
10506 case TYPE_FUNCTION:
10507 case TYPE_POINTER:
10508 // The size of these types is already correct. We don't worry
10509 // about filling them in until later, when we also track
10510 // circular references.
10511 break;
10513 case TYPE_STRUCT:
10515 std::vector<Backend::Btyped_identifier> bfields;
10516 get_backend_struct_fields(gogo, base->struct_type()->fields(),
10517 true, &bfields);
10518 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10519 bt = gogo->backend()->error_type();
10521 break;
10523 case TYPE_ARRAY:
10524 // Slice types were completed in create_placeholder.
10525 if (!base->is_slice_type())
10527 Btype* bet = base->array_type()->get_backend_element(gogo, true);
10528 Bexpression* blen = base->array_type()->get_backend_length(gogo);
10529 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
10530 bt = gogo->backend()->error_type();
10532 break;
10534 case TYPE_INTERFACE:
10535 // Interface types were completed in create_placeholder.
10536 break;
10538 case TYPE_ERROR:
10539 return;
10541 default:
10542 case TYPE_SINK:
10543 case TYPE_CALL_MULTIPLE_RESULT:
10544 case TYPE_NAMED:
10545 case TYPE_FORWARD:
10546 go_unreachable();
10549 this->named_btype_ = bt;
10550 this->is_converted_ = true;
10551 this->is_placeholder_ = false;
10554 // Create the placeholder for a named type. This is the first step in
10555 // converting to the backend representation.
10557 void
10558 Named_type::create_placeholder(Gogo* gogo)
10560 if (this->is_error_)
10561 this->named_btype_ = gogo->backend()->error_type();
10563 if (this->named_btype_ != NULL)
10564 return;
10566 // Create the structure for this type. Note that because we call
10567 // base() here, we don't attempt to represent a named type defined
10568 // as another named type. Instead both named types will point to
10569 // different base representations.
10570 Type* base = this->type_->base();
10571 Btype* bt;
10572 bool set_name = true;
10573 switch (base->classification())
10575 case TYPE_ERROR:
10576 this->is_error_ = true;
10577 this->named_btype_ = gogo->backend()->error_type();
10578 return;
10580 case TYPE_VOID:
10581 case TYPE_BOOLEAN:
10582 case TYPE_INTEGER:
10583 case TYPE_FLOAT:
10584 case TYPE_COMPLEX:
10585 case TYPE_STRING:
10586 case TYPE_NIL:
10587 // These are simple basic types, we can just create them
10588 // directly.
10589 bt = Type::get_named_base_btype(gogo, base);
10590 break;
10592 case TYPE_MAP:
10593 case TYPE_CHANNEL:
10594 // All maps and channels have the same backend representation.
10595 bt = Type::get_named_base_btype(gogo, base);
10596 break;
10598 case TYPE_FUNCTION:
10599 case TYPE_POINTER:
10601 bool for_function = base->classification() == TYPE_FUNCTION;
10602 bt = gogo->backend()->placeholder_pointer_type(this->name(),
10603 this->location_,
10604 for_function);
10605 set_name = false;
10607 break;
10609 case TYPE_STRUCT:
10610 bt = gogo->backend()->placeholder_struct_type(this->name(),
10611 this->location_);
10612 this->is_placeholder_ = true;
10613 set_name = false;
10614 break;
10616 case TYPE_ARRAY:
10617 if (base->is_slice_type())
10618 bt = gogo->backend()->placeholder_struct_type(this->name(),
10619 this->location_);
10620 else
10622 bt = gogo->backend()->placeholder_array_type(this->name(),
10623 this->location_);
10624 this->is_placeholder_ = true;
10626 set_name = false;
10627 break;
10629 case TYPE_INTERFACE:
10630 if (base->interface_type()->is_empty())
10631 bt = Interface_type::get_backend_empty_interface_type(gogo);
10632 else
10634 bt = gogo->backend()->placeholder_struct_type(this->name(),
10635 this->location_);
10636 set_name = false;
10638 break;
10640 default:
10641 case TYPE_SINK:
10642 case TYPE_CALL_MULTIPLE_RESULT:
10643 case TYPE_NAMED:
10644 case TYPE_FORWARD:
10645 go_unreachable();
10648 if (set_name)
10649 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
10651 this->named_btype_ = bt;
10653 if (base->is_slice_type())
10655 // We do not record slices as dependencies of other types,
10656 // because we can fill them in completely here with the final
10657 // size.
10658 std::vector<Backend::Btyped_identifier> bfields;
10659 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
10660 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10661 this->named_btype_ = gogo->backend()->error_type();
10663 else if (base->interface_type() != NULL
10664 && !base->interface_type()->is_empty())
10666 // We do not record interfaces as dependencies of other types,
10667 // because we can fill them in completely here with the final
10668 // size.
10669 std::vector<Backend::Btyped_identifier> bfields;
10670 get_backend_interface_fields(gogo, base->interface_type(), true,
10671 &bfields);
10672 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
10673 this->named_btype_ = gogo->backend()->error_type();
10677 // Get the backend representation for a named type.
10679 Btype*
10680 Named_type::do_get_backend(Gogo* gogo)
10682 if (this->is_error_)
10683 return gogo->backend()->error_type();
10685 Btype* bt = this->named_btype_;
10687 if (!gogo->named_types_are_converted())
10689 // We have not completed converting named types. NAMED_BTYPE_
10690 // is a placeholder and we shouldn't do anything further.
10691 if (bt != NULL)
10692 return bt;
10694 // We don't build dependencies for types whose sizes do not
10695 // change or are not relevant, so we may see them here while
10696 // converting types.
10697 this->create_placeholder(gogo);
10698 bt = this->named_btype_;
10699 go_assert(bt != NULL);
10700 return bt;
10703 // We are not converting types. This should only be called if the
10704 // type has already been converted.
10705 if (!this->is_converted_)
10707 go_assert(saw_errors());
10708 return gogo->backend()->error_type();
10711 go_assert(bt != NULL);
10713 // Complete the backend representation.
10714 Type* base = this->type_->base();
10715 Btype* bt1;
10716 switch (base->classification())
10718 case TYPE_ERROR:
10719 return gogo->backend()->error_type();
10721 case TYPE_VOID:
10722 case TYPE_BOOLEAN:
10723 case TYPE_INTEGER:
10724 case TYPE_FLOAT:
10725 case TYPE_COMPLEX:
10726 case TYPE_STRING:
10727 case TYPE_NIL:
10728 case TYPE_MAP:
10729 case TYPE_CHANNEL:
10730 return bt;
10732 case TYPE_STRUCT:
10733 if (!this->seen_in_get_backend_)
10735 this->seen_in_get_backend_ = true;
10736 base->struct_type()->finish_backend_fields(gogo);
10737 this->seen_in_get_backend_ = false;
10739 return bt;
10741 case TYPE_ARRAY:
10742 if (!this->seen_in_get_backend_)
10744 this->seen_in_get_backend_ = true;
10745 base->array_type()->finish_backend_element(gogo);
10746 this->seen_in_get_backend_ = false;
10748 return bt;
10750 case TYPE_INTERFACE:
10751 if (!this->seen_in_get_backend_)
10753 this->seen_in_get_backend_ = true;
10754 base->interface_type()->finish_backend_methods(gogo);
10755 this->seen_in_get_backend_ = false;
10757 return bt;
10759 case TYPE_FUNCTION:
10760 // Don't build a circular data structure. GENERIC can't handle
10761 // it.
10762 if (this->seen_in_get_backend_)
10764 this->is_circular_ = true;
10765 return gogo->backend()->circular_pointer_type(bt, true);
10767 this->seen_in_get_backend_ = true;
10768 bt1 = Type::get_named_base_btype(gogo, base);
10769 this->seen_in_get_backend_ = false;
10770 if (this->is_circular_)
10771 bt1 = gogo->backend()->circular_pointer_type(bt, true);
10772 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10773 bt = gogo->backend()->error_type();
10774 return bt;
10776 case TYPE_POINTER:
10777 // Don't build a circular data structure. GENERIC can't handle
10778 // it.
10779 if (this->seen_in_get_backend_)
10781 this->is_circular_ = true;
10782 return gogo->backend()->circular_pointer_type(bt, false);
10784 this->seen_in_get_backend_ = true;
10785 bt1 = Type::get_named_base_btype(gogo, base);
10786 this->seen_in_get_backend_ = false;
10787 if (this->is_circular_)
10788 bt1 = gogo->backend()->circular_pointer_type(bt, false);
10789 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10790 bt = gogo->backend()->error_type();
10791 return bt;
10793 default:
10794 case TYPE_SINK:
10795 case TYPE_CALL_MULTIPLE_RESULT:
10796 case TYPE_NAMED:
10797 case TYPE_FORWARD:
10798 go_unreachable();
10801 go_unreachable();
10804 // Build a type descriptor for a named type.
10806 Expression*
10807 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10809 if (this->is_error_)
10810 return Expression::make_error(this->location_);
10811 if (name == NULL && this->is_alias_)
10813 if (this->seen_alias_)
10814 return Expression::make_error(this->location_);
10815 this->seen_alias_ = true;
10816 Expression* ret = this->type_->type_descriptor(gogo, NULL);
10817 this->seen_alias_ = false;
10818 return ret;
10821 // If NAME is not NULL, then we don't really want the type
10822 // descriptor for this type; we want the descriptor for the
10823 // underlying type, giving it the name NAME.
10824 return this->named_type_descriptor(gogo, this->type_,
10825 name == NULL ? this : name);
10828 // Add to the reflection string. This is used mostly for the name of
10829 // the type used in a type descriptor, not for actual reflection
10830 // strings.
10832 void
10833 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10835 this->append_reflection_type_name(gogo, false, ret);
10838 // Add to the reflection string. For an alias we normally use the
10839 // real name, but if USE_ALIAS is true we use the alias name itself.
10841 void
10842 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10843 std::string* ret) const
10845 if (this->is_error_)
10846 return;
10847 if (this->is_alias_ && !use_alias)
10849 if (this->seen_alias_)
10850 return;
10851 this->seen_alias_ = true;
10852 this->append_reflection(this->type_, gogo, ret);
10853 this->seen_alias_ = false;
10854 return;
10856 if (!this->is_builtin())
10858 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10859 // make a unique reflection string, so that the type
10860 // canonicalization in the reflect package will work. In order
10861 // to be compatible with the gc compiler, we put tabs into the
10862 // package path, so that the reflect methods can discard it.
10863 const Package* package = this->named_object_->package();
10864 ret->push_back('\t');
10865 ret->append(package != NULL
10866 ? package->pkgpath_symbol()
10867 : gogo->pkgpath_symbol());
10868 ret->push_back('\t');
10869 ret->append(package != NULL
10870 ? package->package_name()
10871 : gogo->package_name());
10872 ret->push_back('.');
10874 if (this->in_function_ != NULL)
10876 ret->push_back('\t');
10877 const Typed_identifier* rcvr =
10878 this->in_function_->func_value()->type()->receiver();
10879 if (rcvr != NULL)
10881 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10882 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10883 ret->push_back('.');
10885 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10886 ret->push_back('$');
10887 if (this->in_function_index_ > 0)
10889 char buf[30];
10890 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10891 ret->append(buf);
10892 ret->push_back('$');
10894 ret->push_back('\t');
10896 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10899 // Export the type. This is called to export a global type.
10901 void
10902 Named_type::export_named_type(Export* exp, const std::string&) const
10904 // We don't need to write the name of the type here, because it will
10905 // be written by Export::write_type anyhow.
10906 exp->write_c_string("type ");
10907 exp->write_type(this);
10908 exp->write_c_string(";\n");
10911 // Import a named type.
10913 void
10914 Named_type::import_named_type(Import* imp, Named_type** ptype)
10916 imp->require_c_string("type ");
10917 Type *type = imp->read_type();
10918 *ptype = type->named_type();
10919 go_assert(*ptype != NULL);
10920 imp->require_c_string(";\n");
10923 // Export the type when it is referenced by another type. In this
10924 // case Export::export_type will already have issued the name.
10926 void
10927 Named_type::do_export(Export* exp) const
10929 exp->write_type(this->type_);
10931 // To save space, we only export the methods directly attached to
10932 // this type.
10933 Bindings* methods = this->local_methods_;
10934 if (methods == NULL)
10935 return;
10937 exp->write_c_string("\n");
10938 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10939 p != methods->end_definitions();
10940 ++p)
10942 exp->write_c_string(" ");
10943 (*p)->export_named_object(exp);
10946 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10947 p != methods->end_declarations();
10948 ++p)
10950 if (p->second->is_function_declaration())
10952 exp->write_c_string(" ");
10953 p->second->export_named_object(exp);
10958 // Make a named type.
10960 Named_type*
10961 Type::make_named_type(Named_object* named_object, Type* type,
10962 Location location)
10964 return new Named_type(named_object, type, location);
10967 // Finalize the methods for TYPE. It will be a named type or a struct
10968 // type. This sets *ALL_METHODS to the list of methods, and builds
10969 // all required stubs.
10971 void
10972 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10973 Methods** all_methods)
10975 *all_methods = new Methods();
10976 std::vector<const Named_type*> seen;
10977 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10978 if ((*all_methods)->empty())
10980 delete *all_methods;
10981 *all_methods = NULL;
10983 Type::build_stub_methods(gogo, type, *all_methods, location);
10986 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
10987 // build up the struct field indexes as we go. DEPTH is the depth of
10988 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
10989 // adding these methods for an anonymous field with pointer type.
10990 // NEEDS_STUB_METHOD is true if we need to use a stub method which
10991 // calls the real method. TYPES_SEEN is used to avoid infinite
10992 // recursion.
10994 void
10995 Type::add_methods_for_type(const Type* type,
10996 const Method::Field_indexes* field_indexes,
10997 unsigned int depth,
10998 bool is_embedded_pointer,
10999 bool needs_stub_method,
11000 std::vector<const Named_type*>* seen,
11001 Methods* methods)
11003 // Pointer types may not have methods.
11004 if (type->points_to() != NULL)
11005 return;
11007 const Named_type* nt = type->named_type();
11008 if (nt != NULL)
11010 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11011 p != seen->end();
11012 ++p)
11014 if (*p == nt)
11015 return;
11018 seen->push_back(nt);
11020 Type::add_local_methods_for_type(nt, field_indexes, depth,
11021 is_embedded_pointer, needs_stub_method,
11022 methods);
11025 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11026 is_embedded_pointer, needs_stub_method,
11027 seen, methods);
11029 // If we are called with depth > 0, then we are looking at an
11030 // anonymous field of a struct. If such a field has interface type,
11031 // then we need to add the interface methods. We don't want to add
11032 // them when depth == 0, because we will already handle them
11033 // following the usual rules for an interface type.
11034 if (depth > 0)
11035 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11037 if (nt != NULL)
11038 seen->pop_back();
11041 // Add the local methods for the named type NT to *METHODS. The
11042 // parameters are as for add_methods_to_type.
11044 void
11045 Type::add_local_methods_for_type(const Named_type* nt,
11046 const Method::Field_indexes* field_indexes,
11047 unsigned int depth,
11048 bool is_embedded_pointer,
11049 bool needs_stub_method,
11050 Methods* methods)
11052 const Bindings* local_methods = nt->local_methods();
11053 if (local_methods == NULL)
11054 return;
11056 for (Bindings::const_declarations_iterator p =
11057 local_methods->begin_declarations();
11058 p != local_methods->end_declarations();
11059 ++p)
11061 Named_object* no = p->second;
11062 bool is_value_method = (is_embedded_pointer
11063 || !Type::method_expects_pointer(no));
11064 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11065 (needs_stub_method || depth > 0));
11066 if (!methods->insert(no->name(), m))
11067 delete m;
11071 // Add the embedded methods for TYPE to *METHODS. These are the
11072 // methods attached to anonymous fields. The parameters are as for
11073 // add_methods_to_type.
11075 void
11076 Type::add_embedded_methods_for_type(const Type* type,
11077 const Method::Field_indexes* field_indexes,
11078 unsigned int depth,
11079 bool is_embedded_pointer,
11080 bool needs_stub_method,
11081 std::vector<const Named_type*>* seen,
11082 Methods* methods)
11084 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11085 // struct.
11086 const Struct_type* st = type->struct_type();
11087 if (st == NULL)
11088 return;
11090 const Struct_field_list* fields = st->fields();
11091 if (fields == NULL)
11092 return;
11094 unsigned int i = 0;
11095 for (Struct_field_list::const_iterator pf = fields->begin();
11096 pf != fields->end();
11097 ++pf, ++i)
11099 if (!pf->is_anonymous())
11100 continue;
11102 Type* ftype = pf->type();
11103 bool is_pointer = false;
11104 if (ftype->points_to() != NULL)
11106 ftype = ftype->points_to();
11107 is_pointer = true;
11109 Named_type* fnt = ftype->named_type();
11110 if (fnt == NULL)
11112 // This is an error, but it will be diagnosed elsewhere.
11113 continue;
11116 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11117 sub_field_indexes->next = field_indexes;
11118 sub_field_indexes->field_index = i;
11120 Methods tmp_methods;
11121 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11122 (is_embedded_pointer || is_pointer),
11123 (needs_stub_method
11124 || is_pointer
11125 || i > 0),
11126 seen,
11127 &tmp_methods);
11128 // Check if there are promoted methods that conflict with field names and
11129 // don't add them to the method map.
11130 for (Methods::const_iterator p = tmp_methods.begin();
11131 p != tmp_methods.end();
11132 ++p)
11134 bool found = false;
11135 for (Struct_field_list::const_iterator fp = fields->begin();
11136 fp != fields->end();
11137 ++fp)
11139 if (fp->field_name() == p->first)
11141 found = true;
11142 break;
11145 if (!found &&
11146 !methods->insert(p->first, p->second))
11147 delete p->second;
11152 // If TYPE is an interface type, then add its method to *METHODS.
11153 // This is for interface methods attached to an anonymous field. The
11154 // parameters are as for add_methods_for_type.
11156 void
11157 Type::add_interface_methods_for_type(const Type* type,
11158 const Method::Field_indexes* field_indexes,
11159 unsigned int depth,
11160 Methods* methods)
11162 const Interface_type* it = type->interface_type();
11163 if (it == NULL)
11164 return;
11166 const Typed_identifier_list* imethods = it->methods();
11167 if (imethods == NULL)
11168 return;
11170 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11171 pm != imethods->end();
11172 ++pm)
11174 Function_type* fntype = pm->type()->function_type();
11175 if (fntype == NULL)
11177 // This is an error, but it should be reported elsewhere
11178 // when we look at the methods for IT.
11179 continue;
11181 go_assert(!fntype->is_method());
11182 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11183 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11184 field_indexes, depth);
11185 if (!methods->insert(pm->name(), m))
11186 delete m;
11190 // Build stub methods for TYPE as needed. METHODS is the set of
11191 // methods for the type. A stub method may be needed when a type
11192 // inherits a method from an anonymous field. When we need the
11193 // address of the method, as in a type descriptor, we need to build a
11194 // little stub which does the required field dereferences and jumps to
11195 // the real method. LOCATION is the location of the type definition.
11197 void
11198 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11199 Location location)
11201 if (methods == NULL)
11202 return;
11203 for (Methods::const_iterator p = methods->begin();
11204 p != methods->end();
11205 ++p)
11207 Method* m = p->second;
11208 if (m->is_ambiguous() || !m->needs_stub_method())
11209 continue;
11211 const std::string& name(p->first);
11213 // Build a stub method.
11215 const Function_type* fntype = m->type();
11217 static unsigned int counter;
11218 char buf[100];
11219 snprintf(buf, sizeof buf, "$this%u", counter);
11220 ++counter;
11222 Type* receiver_type = const_cast<Type*>(type);
11223 if (!m->is_value_method())
11224 receiver_type = Type::make_pointer_type(receiver_type);
11225 Location receiver_location = m->receiver_location();
11226 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11227 receiver_location);
11229 const Typed_identifier_list* fnparams = fntype->parameters();
11230 Typed_identifier_list* stub_params;
11231 if (fnparams == NULL || fnparams->empty())
11232 stub_params = NULL;
11233 else
11235 // We give each stub parameter a unique name.
11236 stub_params = new Typed_identifier_list();
11237 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11238 pp != fnparams->end();
11239 ++pp)
11241 char pbuf[100];
11242 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11243 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11244 pp->location()));
11245 ++counter;
11249 const Typed_identifier_list* fnresults = fntype->results();
11250 Typed_identifier_list* stub_results;
11251 if (fnresults == NULL || fnresults->empty())
11252 stub_results = NULL;
11253 else
11255 // We create the result parameters without any names, since
11256 // we won't refer to them.
11257 stub_results = new Typed_identifier_list();
11258 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11259 pr != fnresults->end();
11260 ++pr)
11261 stub_results->push_back(Typed_identifier("", pr->type(),
11262 pr->location()));
11265 Function_type* stub_type = Type::make_function_type(receiver,
11266 stub_params,
11267 stub_results,
11268 fntype->location());
11269 if (fntype->is_varargs())
11270 stub_type->set_is_varargs();
11272 // We only create the function in the package which creates the
11273 // type.
11274 const Package* package;
11275 if (type->named_type() == NULL)
11276 package = NULL;
11277 else
11278 package = type->named_type()->named_object()->package();
11279 std::string stub_name = gogo->stub_method_name(package, name);
11280 Named_object* stub;
11281 if (package != NULL)
11282 stub = Named_object::make_function_declaration(stub_name, package,
11283 stub_type, location);
11284 else
11286 stub = gogo->start_function(stub_name, stub_type, false,
11287 fntype->location());
11288 Type::build_one_stub_method(gogo, m, buf, stub_params,
11289 fntype->is_varargs(), location);
11290 gogo->finish_function(fntype->location());
11292 if (type->named_type() == NULL && stub->is_function())
11293 stub->func_value()->set_is_unnamed_type_stub_method();
11294 if (m->nointerface() && stub->is_function())
11295 stub->func_value()->set_nointerface();
11298 m->set_stub_object(stub);
11302 // Build a stub method which adjusts the receiver as required to call
11303 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11304 // PARAMS is the list of function parameters.
11306 void
11307 Type::build_one_stub_method(Gogo* gogo, Method* method,
11308 const char* receiver_name,
11309 const Typed_identifier_list* params,
11310 bool is_varargs,
11311 Location location)
11313 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11314 go_assert(receiver_object != NULL);
11316 Expression* expr = Expression::make_var_reference(receiver_object, location);
11317 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11318 if (expr->type()->points_to() == NULL)
11319 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11321 Expression_list* arguments;
11322 if (params == NULL || params->empty())
11323 arguments = NULL;
11324 else
11326 arguments = new Expression_list();
11327 for (Typed_identifier_list::const_iterator p = params->begin();
11328 p != params->end();
11329 ++p)
11331 Named_object* param = gogo->lookup(p->name(), NULL);
11332 go_assert(param != NULL);
11333 Expression* param_ref = Expression::make_var_reference(param,
11334 location);
11335 arguments->push_back(param_ref);
11339 Expression* func = method->bind_method(expr, location);
11340 go_assert(func != NULL);
11341 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11342 location);
11344 gogo->add_statement(Statement::make_return_from_call(call, location));
11347 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11348 // in reverse order.
11350 Expression*
11351 Type::apply_field_indexes(Expression* expr,
11352 const Method::Field_indexes* field_indexes,
11353 Location location)
11355 if (field_indexes == NULL)
11356 return expr;
11357 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11358 Struct_type* stype = expr->type()->deref()->struct_type();
11359 go_assert(stype != NULL
11360 && field_indexes->field_index < stype->field_count());
11361 if (expr->type()->struct_type() == NULL)
11363 go_assert(expr->type()->points_to() != NULL);
11364 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11365 location);
11366 go_assert(expr->type()->struct_type() == stype);
11368 return Expression::make_field_reference(expr, field_indexes->field_index,
11369 location);
11372 // Return whether NO is a method for which the receiver is a pointer.
11374 bool
11375 Type::method_expects_pointer(const Named_object* no)
11377 const Function_type *fntype;
11378 if (no->is_function())
11379 fntype = no->func_value()->type();
11380 else if (no->is_function_declaration())
11381 fntype = no->func_declaration_value()->type();
11382 else
11383 go_unreachable();
11384 return fntype->receiver()->type()->points_to() != NULL;
11387 // Given a set of methods for a type, METHODS, return the method NAME,
11388 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11389 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11390 // but is ambiguous (and return NULL).
11392 Method*
11393 Type::method_function(const Methods* methods, const std::string& name,
11394 bool* is_ambiguous)
11396 if (is_ambiguous != NULL)
11397 *is_ambiguous = false;
11398 if (methods == NULL)
11399 return NULL;
11400 Methods::const_iterator p = methods->find(name);
11401 if (p == methods->end())
11402 return NULL;
11403 Method* m = p->second;
11404 if (m->is_ambiguous())
11406 if (is_ambiguous != NULL)
11407 *is_ambiguous = true;
11408 return NULL;
11410 return m;
11413 // Return a pointer to the interface method table for TYPE for the
11414 // interface INTERFACE.
11416 Expression*
11417 Type::interface_method_table(Type* type,
11418 Interface_type *interface,
11419 bool is_pointer,
11420 Interface_method_tables** method_tables,
11421 Interface_method_tables** pointer_tables)
11423 go_assert(!interface->is_empty());
11425 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11427 if (*pimt == NULL)
11428 *pimt = new Interface_method_tables(5);
11430 std::pair<Interface_type*, Expression*> val(interface, NULL);
11431 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11433 Location loc = Linemap::predeclared_location();
11434 if (ins.second)
11436 // This is a new entry in the hash table.
11437 go_assert(ins.first->second == NULL);
11438 ins.first->second =
11439 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11441 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11444 // Look for field or method NAME for TYPE. Return an Expression for
11445 // the field or method bound to EXPR. If there is no such field or
11446 // method, give an appropriate error and return an error expression.
11448 Expression*
11449 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11450 const std::string& name,
11451 Location location)
11453 if (type->deref()->is_error_type())
11454 return Expression::make_error(location);
11456 const Named_type* nt = type->deref()->named_type();
11457 const Struct_type* st = type->deref()->struct_type();
11458 const Interface_type* it = type->interface_type();
11460 // If this is a pointer to a pointer, then it is possible that the
11461 // pointed-to type has methods.
11462 bool dereferenced = false;
11463 if (nt == NULL
11464 && st == NULL
11465 && it == NULL
11466 && type->points_to() != NULL
11467 && type->points_to()->points_to() != NULL)
11469 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11470 location);
11471 type = type->points_to();
11472 if (type->deref()->is_error_type())
11473 return Expression::make_error(location);
11474 nt = type->points_to()->named_type();
11475 st = type->points_to()->struct_type();
11476 dereferenced = true;
11479 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11480 || expr->is_addressable());
11481 std::vector<const Named_type*> seen;
11482 bool is_method = false;
11483 bool found_pointer_method = false;
11484 std::string ambig1;
11485 std::string ambig2;
11486 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11487 &seen, NULL, &is_method,
11488 &found_pointer_method, &ambig1, &ambig2))
11490 Expression* ret;
11491 if (!is_method)
11493 go_assert(st != NULL);
11494 if (type->struct_type() == NULL)
11496 if (dereferenced)
11498 go_error_at(location, "pointer type has no field %qs",
11499 Gogo::message_name(name).c_str());
11500 return Expression::make_error(location);
11502 go_assert(type->points_to() != NULL);
11503 expr = Expression::make_dereference(expr,
11504 Expression::NIL_CHECK_DEFAULT,
11505 location);
11506 go_assert(expr->type()->struct_type() == st);
11508 ret = st->field_reference(expr, name, location);
11509 if (ret == NULL)
11511 go_error_at(location, "type has no field %qs",
11512 Gogo::message_name(name).c_str());
11513 return Expression::make_error(location);
11516 else if (it != NULL && it->find_method(name) != NULL)
11517 ret = Expression::make_interface_field_reference(expr, name,
11518 location);
11519 else
11521 Method* m;
11522 if (nt != NULL)
11523 m = nt->method_function(name, NULL);
11524 else if (st != NULL)
11525 m = st->method_function(name, NULL);
11526 else
11527 go_unreachable();
11528 go_assert(m != NULL);
11529 if (dereferenced)
11531 go_error_at(location,
11532 "calling method %qs requires explicit dereference",
11533 Gogo::message_name(name).c_str());
11534 return Expression::make_error(location);
11536 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11537 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11538 ret = m->bind_method(expr, location);
11540 go_assert(ret != NULL);
11541 return ret;
11543 else
11545 if (Gogo::is_erroneous_name(name))
11547 // An error was already reported.
11549 else if (!ambig1.empty())
11550 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11551 Gogo::message_name(name).c_str(), ambig1.c_str(),
11552 ambig2.c_str());
11553 else if (found_pointer_method)
11554 go_error_at(location, "method requires a pointer receiver");
11555 else if (nt == NULL && st == NULL && it == NULL)
11556 go_error_at(location,
11557 ("reference to field %qs in object which "
11558 "has no fields or methods"),
11559 Gogo::message_name(name).c_str());
11560 else
11562 bool is_unexported;
11563 // The test for 'a' and 'z' is to handle builtin names,
11564 // which are not hidden.
11565 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11566 is_unexported = false;
11567 else
11569 std::string unpacked = Gogo::unpack_hidden_name(name);
11570 seen.clear();
11571 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11572 unpacked,
11573 &seen);
11575 if (is_unexported)
11576 go_error_at(location, "reference to unexported field or method %qs",
11577 Gogo::message_name(name).c_str());
11578 else
11579 go_error_at(location, "reference to undefined field or method %qs",
11580 Gogo::message_name(name).c_str());
11582 return Expression::make_error(location);
11586 // Look in TYPE for a field or method named NAME, return true if one
11587 // is found. This looks through embedded anonymous fields and handles
11588 // ambiguity. If a method is found, sets *IS_METHOD to true;
11589 // otherwise, if a field is found, set it to false. If
11590 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11591 // whose address can not be taken. SEEN is used to avoid infinite
11592 // recursion on invalid types.
11594 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11595 // method we couldn't use because it requires a pointer. LEVEL is
11596 // used for recursive calls, and can be NULL for a non-recursive call.
11597 // When this function returns false because it finds that the name is
11598 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11599 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11600 // will be unchanged.
11602 // This function just returns whether or not there is a field or
11603 // method, and whether it is a field or method. It doesn't build an
11604 // expression to refer to it. If it is a method, we then look in the
11605 // list of all methods for the type. If it is a field, the search has
11606 // to be done again, looking only for fields, and building up the
11607 // expression as we go.
11609 bool
11610 Type::find_field_or_method(const Type* type,
11611 const std::string& name,
11612 bool receiver_can_be_pointer,
11613 std::vector<const Named_type*>* seen,
11614 int* level,
11615 bool* is_method,
11616 bool* found_pointer_method,
11617 std::string* ambig1,
11618 std::string* ambig2)
11620 // Named types can have locally defined methods.
11621 const Named_type* nt = type->unalias()->named_type();
11622 if (nt == NULL && type->points_to() != NULL)
11623 nt = type->points_to()->unalias()->named_type();
11624 if (nt != NULL)
11626 Named_object* no = nt->find_local_method(name);
11627 if (no != NULL)
11629 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11631 *is_method = true;
11632 return true;
11635 // Record that we have found a pointer method in order to
11636 // give a better error message if we don't find anything
11637 // else.
11638 *found_pointer_method = true;
11641 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11642 p != seen->end();
11643 ++p)
11645 if (*p == nt)
11647 // We've already seen this type when searching for methods.
11648 return false;
11653 // Interface types can have methods.
11654 const Interface_type* it = type->interface_type();
11655 if (it != NULL && it->find_method(name) != NULL)
11657 *is_method = true;
11658 return true;
11661 // Struct types can have fields. They can also inherit fields and
11662 // methods from anonymous fields.
11663 const Struct_type* st = type->deref()->struct_type();
11664 if (st == NULL)
11665 return false;
11666 const Struct_field_list* fields = st->fields();
11667 if (fields == NULL)
11668 return false;
11670 if (nt != NULL)
11671 seen->push_back(nt);
11673 int found_level = 0;
11674 bool found_is_method = false;
11675 std::string found_ambig1;
11676 std::string found_ambig2;
11677 const Struct_field* found_parent = NULL;
11678 for (Struct_field_list::const_iterator pf = fields->begin();
11679 pf != fields->end();
11680 ++pf)
11682 if (pf->is_field_name(name))
11684 *is_method = false;
11685 if (nt != NULL)
11686 seen->pop_back();
11687 return true;
11690 if (!pf->is_anonymous())
11691 continue;
11693 if (pf->type()->deref()->is_error_type()
11694 || pf->type()->deref()->is_undefined())
11695 continue;
11697 Named_type* fnt = pf->type()->named_type();
11698 if (fnt == NULL)
11699 fnt = pf->type()->deref()->named_type();
11700 go_assert(fnt != NULL);
11702 // Methods with pointer receivers on embedded field are
11703 // inherited by the pointer to struct, and also by the struct
11704 // type if the field itself is a pointer.
11705 bool can_be_pointer = (receiver_can_be_pointer
11706 || pf->type()->points_to() != NULL);
11707 int sublevel = level == NULL ? 1 : *level + 1;
11708 bool sub_is_method;
11709 std::string subambig1;
11710 std::string subambig2;
11711 bool subfound = Type::find_field_or_method(fnt,
11712 name,
11713 can_be_pointer,
11714 seen,
11715 &sublevel,
11716 &sub_is_method,
11717 found_pointer_method,
11718 &subambig1,
11719 &subambig2);
11720 if (!subfound)
11722 if (!subambig1.empty())
11724 // The name was found via this field, but is ambiguous.
11725 // if the ambiguity is lower or at the same level as
11726 // anything else we have already found, then we want to
11727 // pass the ambiguity back to the caller.
11728 if (found_level == 0 || sublevel <= found_level)
11730 found_ambig1 = (Gogo::message_name(pf->field_name())
11731 + '.' + subambig1);
11732 found_ambig2 = (Gogo::message_name(pf->field_name())
11733 + '.' + subambig2);
11734 found_level = sublevel;
11738 else
11740 // The name was found via this field. Use the level to see
11741 // if we want to use this one, or whether it introduces an
11742 // ambiguity.
11743 if (found_level == 0 || sublevel < found_level)
11745 found_level = sublevel;
11746 found_is_method = sub_is_method;
11747 found_ambig1.clear();
11748 found_ambig2.clear();
11749 found_parent = &*pf;
11751 else if (sublevel > found_level)
11753 else if (found_ambig1.empty())
11755 // We found an ambiguity.
11756 go_assert(found_parent != NULL);
11757 found_ambig1 = Gogo::message_name(found_parent->field_name());
11758 found_ambig2 = Gogo::message_name(pf->field_name());
11760 else
11762 // We found an ambiguity, but we already know of one.
11763 // Just report the earlier one.
11768 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
11769 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11770 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
11771 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11773 if (nt != NULL)
11774 seen->pop_back();
11776 if (found_level == 0)
11777 return false;
11778 else if (found_is_method
11779 && type->named_type() != NULL
11780 && type->points_to() != NULL)
11782 // If this is a method inherited from a struct field in a named pointer
11783 // type, it is invalid to automatically dereference the pointer to the
11784 // struct to find this method.
11785 if (level != NULL)
11786 *level = found_level;
11787 *is_method = true;
11788 return false;
11790 else if (!found_ambig1.empty())
11792 go_assert(!found_ambig1.empty());
11793 ambig1->assign(found_ambig1);
11794 ambig2->assign(found_ambig2);
11795 if (level != NULL)
11796 *level = found_level;
11797 return false;
11799 else
11801 if (level != NULL)
11802 *level = found_level;
11803 *is_method = found_is_method;
11804 return true;
11808 // Return whether NAME is an unexported field or method for TYPE.
11810 bool
11811 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11812 const std::string& name,
11813 std::vector<const Named_type*>* seen)
11815 const Named_type* nt = type->named_type();
11816 if (nt == NULL)
11817 nt = type->deref()->named_type();
11818 if (nt != NULL)
11820 if (nt->is_unexported_local_method(gogo, name))
11821 return true;
11823 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11824 p != seen->end();
11825 ++p)
11827 if (*p == nt)
11829 // We've already seen this type.
11830 return false;
11835 const Interface_type* it = type->interface_type();
11836 if (it != NULL && it->is_unexported_method(gogo, name))
11837 return true;
11839 type = type->deref();
11841 const Struct_type* st = type->struct_type();
11842 if (st != NULL && st->is_unexported_local_field(gogo, name))
11843 return true;
11845 if (st == NULL)
11846 return false;
11848 const Struct_field_list* fields = st->fields();
11849 if (fields == NULL)
11850 return false;
11852 if (nt != NULL)
11853 seen->push_back(nt);
11855 for (Struct_field_list::const_iterator pf = fields->begin();
11856 pf != fields->end();
11857 ++pf)
11859 if (pf->is_anonymous()
11860 && !pf->type()->deref()->is_error_type()
11861 && !pf->type()->deref()->is_undefined())
11863 Named_type* subtype = pf->type()->named_type();
11864 if (subtype == NULL)
11865 subtype = pf->type()->deref()->named_type();
11866 if (subtype == NULL)
11868 // This is an error, but it will be diagnosed elsewhere.
11869 continue;
11871 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11873 if (nt != NULL)
11874 seen->pop_back();
11875 return true;
11880 if (nt != NULL)
11881 seen->pop_back();
11883 return false;
11886 // Class Forward_declaration.
11888 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11889 : Type(TYPE_FORWARD),
11890 named_object_(named_object->resolve()), warned_(false)
11892 go_assert(this->named_object_->is_unknown()
11893 || this->named_object_->is_type_declaration());
11896 // Return the named object.
11898 Named_object*
11899 Forward_declaration_type::named_object()
11901 return this->named_object_->resolve();
11904 const Named_object*
11905 Forward_declaration_type::named_object() const
11907 return this->named_object_->resolve();
11910 // Return the name of the forward declared type.
11912 const std::string&
11913 Forward_declaration_type::name() const
11915 return this->named_object()->name();
11918 // Warn about a use of a type which has been declared but not defined.
11920 void
11921 Forward_declaration_type::warn() const
11923 Named_object* no = this->named_object_->resolve();
11924 if (no->is_unknown())
11926 // The name was not defined anywhere.
11927 if (!this->warned_)
11929 go_error_at(this->named_object_->location(),
11930 "use of undefined type %qs",
11931 no->message_name().c_str());
11932 this->warned_ = true;
11935 else if (no->is_type_declaration())
11937 // The name was seen as a type, but the type was never defined.
11938 if (no->type_declaration_value()->using_type())
11940 go_error_at(this->named_object_->location(),
11941 "use of undefined type %qs",
11942 no->message_name().c_str());
11943 this->warned_ = true;
11946 else
11948 // The name was defined, but not as a type.
11949 if (!this->warned_)
11951 go_error_at(this->named_object_->location(), "expected type");
11952 this->warned_ = true;
11957 // Get the base type of a declaration. This gives an error if the
11958 // type has not yet been defined.
11960 Type*
11961 Forward_declaration_type::real_type()
11963 if (this->is_defined())
11965 Named_type* nt = this->named_object()->type_value();
11966 if (!nt->is_valid())
11967 return Type::make_error_type();
11968 return this->named_object()->type_value();
11970 else
11972 this->warn();
11973 return Type::make_error_type();
11977 const Type*
11978 Forward_declaration_type::real_type() const
11980 if (this->is_defined())
11982 const Named_type* nt = this->named_object()->type_value();
11983 if (!nt->is_valid())
11984 return Type::make_error_type();
11985 return this->named_object()->type_value();
11987 else
11989 this->warn();
11990 return Type::make_error_type();
11994 // Return whether the base type is defined.
11996 bool
11997 Forward_declaration_type::is_defined() const
11999 return this->named_object()->is_type();
12002 // Add a method. This is used when methods are defined before the
12003 // type.
12005 Named_object*
12006 Forward_declaration_type::add_method(const std::string& name,
12007 Function* function)
12009 Named_object* no = this->named_object();
12010 if (no->is_unknown())
12011 no->declare_as_type();
12012 return no->type_declaration_value()->add_method(name, function);
12015 // Add a method declaration. This is used when methods are declared
12016 // before the type.
12018 Named_object*
12019 Forward_declaration_type::add_method_declaration(const std::string& name,
12020 Package* package,
12021 Function_type* type,
12022 Location location)
12024 Named_object* no = this->named_object();
12025 if (no->is_unknown())
12026 no->declare_as_type();
12027 Type_declaration* td = no->type_declaration_value();
12028 return td->add_method_declaration(name, package, type, location);
12031 // Add an already created object as a method.
12033 void
12034 Forward_declaration_type::add_existing_method(Named_object* nom)
12036 Named_object* no = this->named_object();
12037 if (no->is_unknown())
12038 no->declare_as_type();
12039 no->type_declaration_value()->add_existing_method(nom);
12042 // Traversal.
12045 Forward_declaration_type::do_traverse(Traverse* traverse)
12047 if (this->is_defined()
12048 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12049 return TRAVERSE_EXIT;
12050 return TRAVERSE_CONTINUE;
12053 // Verify the type.
12055 bool
12056 Forward_declaration_type::do_verify()
12058 if (!this->is_defined() && !this->is_nil_constant_as_type())
12060 this->warn();
12061 return false;
12063 return true;
12066 // Get the backend representation for the type.
12068 Btype*
12069 Forward_declaration_type::do_get_backend(Gogo* gogo)
12071 if (this->is_defined())
12072 return Type::get_named_base_btype(gogo, this->real_type());
12074 if (this->warned_)
12075 return gogo->backend()->error_type();
12077 // We represent an undefined type as a struct with no fields. That
12078 // should work fine for the backend, since the same case can arise
12079 // in C.
12080 std::vector<Backend::Btyped_identifier> fields;
12081 Btype* bt = gogo->backend()->struct_type(fields);
12082 return gogo->backend()->named_type(this->name(), bt,
12083 this->named_object()->location());
12086 // Build a type descriptor for a forwarded type.
12088 Expression*
12089 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12091 Location ploc = Linemap::predeclared_location();
12092 if (!this->is_defined())
12093 return Expression::make_error(ploc);
12094 else
12096 Type* t = this->real_type();
12097 if (name != NULL)
12098 return this->named_type_descriptor(gogo, t, name);
12099 else
12100 return Expression::make_error(this->named_object_->location());
12104 // The reflection string.
12106 void
12107 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12109 this->append_reflection(this->real_type(), gogo, ret);
12112 // Export a forward declaration. This can happen when a defined type
12113 // refers to a type which is only declared (and is presumably defined
12114 // in some other file in the same package).
12116 void
12117 Forward_declaration_type::do_export(Export*) const
12119 // If there is a base type, that should be exported instead of this.
12120 go_assert(!this->is_defined());
12122 // We don't output anything.
12125 // Make a forward declaration.
12127 Type*
12128 Type::make_forward_declaration(Named_object* named_object)
12130 return new Forward_declaration_type(named_object);
12133 // Class Typed_identifier_list.
12135 // Sort the entries by name.
12137 struct Typed_identifier_list_sort
12139 public:
12140 bool
12141 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12143 return (Gogo::unpack_hidden_name(t1.name())
12144 < Gogo::unpack_hidden_name(t2.name()));
12148 void
12149 Typed_identifier_list::sort_by_name()
12151 std::sort(this->entries_.begin(), this->entries_.end(),
12152 Typed_identifier_list_sort());
12155 // Traverse types.
12158 Typed_identifier_list::traverse(Traverse* traverse)
12160 for (Typed_identifier_list::const_iterator p = this->begin();
12161 p != this->end();
12162 ++p)
12164 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12165 return TRAVERSE_EXIT;
12167 return TRAVERSE_CONTINUE;
12170 // Copy the list.
12172 Typed_identifier_list*
12173 Typed_identifier_list::copy() const
12175 Typed_identifier_list* ret = new Typed_identifier_list();
12176 for (Typed_identifier_list::const_iterator p = this->begin();
12177 p != this->end();
12178 ++p)
12179 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12180 return ret;