compiler, runtime: call gcWriteBarrier instead of writebarrierptr
[official-gcc.git] / gcc / go / gofrontend / types.cc
blobcc07bfc25bdce9fdca475258f42059189f0cd370
1 // types.cc -- Go frontend types.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include <ostream>
11 #include "go-c.h"
12 #include "gogo.h"
13 #include "go-diagnostics.h"
14 #include "go-encode-id.h"
15 #include "operator.h"
16 #include "expressions.h"
17 #include "statements.h"
18 #include "export.h"
19 #include "import.h"
20 #include "backend.h"
21 #include "types.h"
23 // Forward declarations so that we don't have to make types.h #include
24 // backend.h.
26 static void
27 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
28 bool use_placeholder,
29 std::vector<Backend::Btyped_identifier>* bfields);
31 static void
32 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
33 std::vector<Backend::Btyped_identifier>* bfields);
35 static void
36 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
37 bool use_placeholder,
38 std::vector<Backend::Btyped_identifier>* bfields);
40 // Class Type.
42 Type::Type(Type_classification classification)
43 : classification_(classification), btype_(NULL), type_descriptor_var_(NULL),
44 gc_symbol_var_(NULL)
48 Type::~Type()
52 // Get the base type for a type--skip names and forward declarations.
54 Type*
55 Type::base()
57 switch (this->classification_)
59 case TYPE_NAMED:
60 return this->named_type()->named_base();
61 case TYPE_FORWARD:
62 return this->forward_declaration_type()->real_type()->base();
63 default:
64 return this;
68 const Type*
69 Type::base() const
71 switch (this->classification_)
73 case TYPE_NAMED:
74 return this->named_type()->named_base();
75 case TYPE_FORWARD:
76 return this->forward_declaration_type()->real_type()->base();
77 default:
78 return this;
82 // Skip defined forward declarations.
84 Type*
85 Type::forwarded()
87 Type* t = this;
88 Forward_declaration_type* ftype = t->forward_declaration_type();
89 while (ftype != NULL && ftype->is_defined())
91 t = ftype->real_type();
92 ftype = t->forward_declaration_type();
94 return t;
97 const Type*
98 Type::forwarded() const
100 const Type* t = this;
101 const Forward_declaration_type* ftype = t->forward_declaration_type();
102 while (ftype != NULL && ftype->is_defined())
104 t = ftype->real_type();
105 ftype = t->forward_declaration_type();
107 return t;
110 // Skip alias definitions.
112 Type*
113 Type::unalias()
115 Type* t = this->forwarded();
116 Named_type* nt = t->named_type();
117 while (nt != NULL && nt->is_alias())
119 t = nt->real_type()->forwarded();
120 nt = t->named_type();
122 return t;
125 const Type*
126 Type::unalias() const
128 const Type* t = this->forwarded();
129 const Named_type* nt = t->named_type();
130 while (nt != NULL && nt->is_alias())
132 t = nt->real_type()->forwarded();
133 nt = t->named_type();
135 return t;
138 // If this is a named type, return it. Otherwise, return NULL.
140 Named_type*
141 Type::named_type()
143 return this->forwarded()->convert_no_base<Named_type, TYPE_NAMED>();
146 const Named_type*
147 Type::named_type() const
149 return this->forwarded()->convert_no_base<const Named_type, TYPE_NAMED>();
152 // Return true if this type is not defined.
154 bool
155 Type::is_undefined() const
157 return this->forwarded()->forward_declaration_type() != NULL;
160 // Return true if this is a basic type: a type which is not composed
161 // of other types, and is not void.
163 bool
164 Type::is_basic_type() const
166 switch (this->classification_)
168 case TYPE_INTEGER:
169 case TYPE_FLOAT:
170 case TYPE_COMPLEX:
171 case TYPE_BOOLEAN:
172 case TYPE_STRING:
173 case TYPE_NIL:
174 return true;
176 case TYPE_ERROR:
177 case TYPE_VOID:
178 case TYPE_FUNCTION:
179 case TYPE_POINTER:
180 case TYPE_STRUCT:
181 case TYPE_ARRAY:
182 case TYPE_MAP:
183 case TYPE_CHANNEL:
184 case TYPE_INTERFACE:
185 return false;
187 case TYPE_NAMED:
188 case TYPE_FORWARD:
189 return this->base()->is_basic_type();
191 default:
192 go_unreachable();
196 // Return true if this is an abstract type.
198 bool
199 Type::is_abstract() const
201 switch (this->classification())
203 case TYPE_INTEGER:
204 return this->integer_type()->is_abstract();
205 case TYPE_FLOAT:
206 return this->float_type()->is_abstract();
207 case TYPE_COMPLEX:
208 return this->complex_type()->is_abstract();
209 case TYPE_STRING:
210 return this->is_abstract_string_type();
211 case TYPE_BOOLEAN:
212 return this->is_abstract_boolean_type();
213 default:
214 return false;
218 // Return a non-abstract version of an abstract type.
220 Type*
221 Type::make_non_abstract_type()
223 go_assert(this->is_abstract());
224 switch (this->classification())
226 case TYPE_INTEGER:
227 if (this->integer_type()->is_rune())
228 return Type::lookup_integer_type("int32");
229 else
230 return Type::lookup_integer_type("int");
231 case TYPE_FLOAT:
232 return Type::lookup_float_type("float64");
233 case TYPE_COMPLEX:
234 return Type::lookup_complex_type("complex128");
235 case TYPE_STRING:
236 return Type::lookup_string_type();
237 case TYPE_BOOLEAN:
238 return Type::lookup_bool_type();
239 default:
240 go_unreachable();
244 // Return true if this is an error type. Don't give an error if we
245 // try to dereference an undefined forwarding type, as this is called
246 // in the parser when the type may legitimately be undefined.
248 bool
249 Type::is_error_type() const
251 const Type* t = this->forwarded();
252 // Note that we return false for an undefined forward type.
253 switch (t->classification_)
255 case TYPE_ERROR:
256 return true;
257 case TYPE_NAMED:
258 return t->named_type()->is_named_error_type();
259 default:
260 return false;
264 // If this is a pointer type, return the type to which it points.
265 // Otherwise, return NULL.
267 Type*
268 Type::points_to() const
270 const Pointer_type* ptype = this->convert<const Pointer_type,
271 TYPE_POINTER>();
272 return ptype == NULL ? NULL : ptype->points_to();
275 // Return whether this is a slice type.
277 bool
278 Type::is_slice_type() const
280 return this->array_type() != NULL && this->array_type()->length() == NULL;
283 // Return whether this is the predeclared constant nil being used as a
284 // type.
286 bool
287 Type::is_nil_constant_as_type() const
289 const Type* t = this->forwarded();
290 if (t->forward_declaration_type() != NULL)
292 const Named_object* no = t->forward_declaration_type()->named_object();
293 if (no->is_unknown())
294 no = no->unknown_value()->real_named_object();
295 if (no != NULL
296 && no->is_const()
297 && no->const_value()->expr()->is_nil_expression())
298 return true;
300 return false;
303 // Traverse a type.
306 Type::traverse(Type* type, Traverse* traverse)
308 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
309 || (traverse->traverse_mask()
310 & Traverse::traverse_expressions) != 0);
311 if (traverse->remember_type(type))
313 // We have already traversed this type.
314 return TRAVERSE_CONTINUE;
316 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
318 int t = traverse->type(type);
319 if (t == TRAVERSE_EXIT)
320 return TRAVERSE_EXIT;
321 else if (t == TRAVERSE_SKIP_COMPONENTS)
322 return TRAVERSE_CONTINUE;
324 // An array type has an expression which we need to traverse if
325 // traverse_expressions is set.
326 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
327 return TRAVERSE_EXIT;
328 return TRAVERSE_CONTINUE;
331 // Default implementation for do_traverse for child class.
334 Type::do_traverse(Traverse*)
336 return TRAVERSE_CONTINUE;
339 // Return whether two types are identical. If ERRORS_ARE_IDENTICAL,
340 // then return true for all erroneous types; this is used to avoid
341 // cascading errors. If REASON is not NULL, optionally set *REASON to
342 // the reason the types are not identical.
344 bool
345 Type::are_identical(const Type* t1, const Type* t2, bool errors_are_identical,
346 std::string* reason)
348 return Type::are_identical_cmp_tags(t1, t2, COMPARE_TAGS,
349 errors_are_identical, reason);
352 // Like are_identical, but with a CMP_TAGS parameter.
354 bool
355 Type::are_identical_cmp_tags(const Type* t1, const Type* t2, Cmp_tags cmp_tags,
356 bool errors_are_identical, std::string* reason)
358 if (t1 == NULL || t2 == NULL)
360 // Something is wrong.
361 return errors_are_identical ? true : t1 == t2;
364 // Skip defined forward declarations. Ignore aliases.
365 t1 = t1->unalias();
366 t2 = t2->unalias();
368 if (t1 == t2)
369 return true;
371 // An undefined forward declaration is an error.
372 if (t1->forward_declaration_type() != NULL
373 || t2->forward_declaration_type() != NULL)
374 return errors_are_identical;
376 // Avoid cascading errors with error types.
377 if (t1->is_error_type() || t2->is_error_type())
379 if (errors_are_identical)
380 return true;
381 return t1->is_error_type() && t2->is_error_type();
384 // Get a good reason for the sink type. Note that the sink type on
385 // the left hand side of an assignment is handled in are_assignable.
386 if (t1->is_sink_type() || t2->is_sink_type())
388 if (reason != NULL)
389 *reason = "invalid use of _";
390 return false;
393 // A named type is only identical to itself.
394 if (t1->named_type() != NULL || t2->named_type() != NULL)
395 return false;
397 // Check type shapes.
398 if (t1->classification() != t2->classification())
399 return false;
401 switch (t1->classification())
403 case TYPE_VOID:
404 case TYPE_BOOLEAN:
405 case TYPE_STRING:
406 case TYPE_NIL:
407 // These types are always identical.
408 return true;
410 case TYPE_INTEGER:
411 return t1->integer_type()->is_identical(t2->integer_type());
413 case TYPE_FLOAT:
414 return t1->float_type()->is_identical(t2->float_type());
416 case TYPE_COMPLEX:
417 return t1->complex_type()->is_identical(t2->complex_type());
419 case TYPE_FUNCTION:
420 return t1->function_type()->is_identical(t2->function_type(),
421 false,
422 cmp_tags,
423 errors_are_identical,
424 reason);
426 case TYPE_POINTER:
427 return Type::are_identical_cmp_tags(t1->points_to(), t2->points_to(),
428 cmp_tags, errors_are_identical,
429 reason);
431 case TYPE_STRUCT:
432 return t1->struct_type()->is_identical(t2->struct_type(), cmp_tags,
433 errors_are_identical);
435 case TYPE_ARRAY:
436 return t1->array_type()->is_identical(t2->array_type(), cmp_tags,
437 errors_are_identical);
439 case TYPE_MAP:
440 return t1->map_type()->is_identical(t2->map_type(), cmp_tags,
441 errors_are_identical);
443 case TYPE_CHANNEL:
444 return t1->channel_type()->is_identical(t2->channel_type(), cmp_tags,
445 errors_are_identical);
447 case TYPE_INTERFACE:
448 return t1->interface_type()->is_identical(t2->interface_type(), cmp_tags,
449 errors_are_identical);
451 case TYPE_CALL_MULTIPLE_RESULT:
452 if (reason != NULL)
453 *reason = "invalid use of multiple-value function call";
454 return false;
456 default:
457 go_unreachable();
461 // Return true if it's OK to have a binary operation with types LHS
462 // and RHS. This is not used for shifts or comparisons.
464 bool
465 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
467 if (Type::are_identical(lhs, rhs, true, NULL))
468 return true;
470 // A constant of abstract bool type may be mixed with any bool type.
471 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
472 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
473 return true;
475 // A constant of abstract string type may be mixed with any string
476 // type.
477 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
478 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
479 return true;
481 lhs = lhs->base();
482 rhs = rhs->base();
484 // A constant of abstract integer, float, or complex type may be
485 // mixed with an integer, float, or complex type.
486 if ((rhs->is_abstract()
487 && (rhs->integer_type() != NULL
488 || rhs->float_type() != NULL
489 || rhs->complex_type() != NULL)
490 && (lhs->integer_type() != NULL
491 || lhs->float_type() != NULL
492 || lhs->complex_type() != NULL))
493 || (lhs->is_abstract()
494 && (lhs->integer_type() != NULL
495 || lhs->float_type() != NULL
496 || lhs->complex_type() != NULL)
497 && (rhs->integer_type() != NULL
498 || rhs->float_type() != NULL
499 || rhs->complex_type() != NULL)))
500 return true;
502 // The nil type may be compared to a pointer, an interface type, a
503 // slice type, a channel type, a map type, or a function type.
504 if (lhs->is_nil_type()
505 && (rhs->points_to() != NULL
506 || rhs->interface_type() != NULL
507 || rhs->is_slice_type()
508 || rhs->map_type() != NULL
509 || rhs->channel_type() != NULL
510 || rhs->function_type() != NULL))
511 return true;
512 if (rhs->is_nil_type()
513 && (lhs->points_to() != NULL
514 || lhs->interface_type() != NULL
515 || lhs->is_slice_type()
516 || lhs->map_type() != NULL
517 || lhs->channel_type() != NULL
518 || lhs->function_type() != NULL))
519 return true;
521 return false;
524 // Return true if a value with type T1 may be compared with a value of
525 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
527 bool
528 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
529 const Type *t2, std::string *reason)
531 if (t1 != t2
532 && !Type::are_assignable(t1, t2, NULL)
533 && !Type::are_assignable(t2, t1, NULL))
535 if (reason != NULL)
536 *reason = "incompatible types in binary expression";
537 return false;
540 if (!is_equality_op)
542 if (t1->integer_type() == NULL
543 && t1->float_type() == NULL
544 && !t1->is_string_type())
546 if (reason != NULL)
547 *reason = _("invalid comparison of non-ordered type");
548 return false;
551 else if (t1->is_slice_type()
552 || t1->map_type() != NULL
553 || t1->function_type() != NULL
554 || t2->is_slice_type()
555 || t2->map_type() != NULL
556 || t2->function_type() != NULL)
558 if (!t1->is_nil_type() && !t2->is_nil_type())
560 if (reason != NULL)
562 if (t1->is_slice_type() || t2->is_slice_type())
563 *reason = _("slice can only be compared to nil");
564 else if (t1->map_type() != NULL || t2->map_type() != NULL)
565 *reason = _("map can only be compared to nil");
566 else
567 *reason = _("func can only be compared to nil");
569 // Match 6g error messages.
570 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
572 char buf[200];
573 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
574 reason->c_str());
575 *reason = buf;
578 return false;
581 else
583 if (!t1->is_boolean_type()
584 && t1->integer_type() == NULL
585 && t1->float_type() == NULL
586 && t1->complex_type() == NULL
587 && !t1->is_string_type()
588 && t1->points_to() == NULL
589 && t1->channel_type() == NULL
590 && t1->interface_type() == NULL
591 && t1->struct_type() == NULL
592 && t1->array_type() == NULL
593 && !t1->is_nil_type())
595 if (reason != NULL)
596 *reason = _("invalid comparison of non-comparable type");
597 return false;
600 if (t1->unalias()->named_type() != NULL)
601 return t1->unalias()->named_type()->named_type_is_comparable(reason);
602 else if (t2->unalias()->named_type() != NULL)
603 return t2->unalias()->named_type()->named_type_is_comparable(reason);
604 else if (t1->struct_type() != NULL)
606 if (t1->struct_type()->is_struct_incomparable())
608 if (reason != NULL)
609 *reason = _("invalid comparison of generated struct");
610 return false;
612 const Struct_field_list* fields = t1->struct_type()->fields();
613 for (Struct_field_list::const_iterator p = fields->begin();
614 p != fields->end();
615 ++p)
617 if (!p->type()->is_comparable())
619 if (reason != NULL)
620 *reason = _("invalid comparison of non-comparable struct");
621 return false;
625 else if (t1->array_type() != NULL)
627 if (t1->array_type()->is_array_incomparable())
629 if (reason != NULL)
630 *reason = _("invalid comparison of generated array");
631 return false;
633 if (t1->array_type()->length()->is_nil_expression()
634 || !t1->array_type()->element_type()->is_comparable())
636 if (reason != NULL)
637 *reason = _("invalid comparison of non-comparable array");
638 return false;
643 return true;
646 // Return true if a value with type RHS may be assigned to a variable
647 // with type LHS. If REASON is not NULL, set *REASON to the reason
648 // the types are not assignable.
650 bool
651 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
653 // Do some checks first. Make sure the types are defined.
654 if (rhs != NULL && !rhs->is_undefined())
656 if (rhs->is_void_type())
658 if (reason != NULL)
659 *reason = "non-value used as value";
660 return false;
662 if (rhs->is_call_multiple_result_type())
664 if (reason != NULL)
665 reason->assign(_("multiple-value function call in "
666 "single-value context"));
667 return false;
671 // Any value may be assigned to the blank identifier.
672 if (lhs != NULL
673 && !lhs->is_undefined()
674 && lhs->is_sink_type())
675 return true;
677 // Identical types are assignable.
678 if (Type::are_identical(lhs, rhs, true, reason))
679 return true;
681 // Ignore aliases, except for error messages.
682 const Type* lhs_orig = lhs;
683 const Type* rhs_orig = rhs;
684 lhs = lhs->unalias();
685 rhs = rhs->unalias();
687 // The types are assignable if they have identical underlying types
688 // and either LHS or RHS is not a named type.
689 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
690 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
691 && Type::are_identical(lhs->base(), rhs->base(), true, reason))
692 return true;
694 // The types are assignable if LHS is an interface type and RHS
695 // implements the required methods.
696 const Interface_type* lhs_interface_type = lhs->interface_type();
697 if (lhs_interface_type != NULL)
699 if (lhs_interface_type->implements_interface(rhs, reason))
700 return true;
701 const Interface_type* rhs_interface_type = rhs->interface_type();
702 if (rhs_interface_type != NULL
703 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
704 reason))
705 return true;
708 // The type are assignable if RHS is a bidirectional channel type,
709 // LHS is a channel type, they have identical element types, and
710 // either LHS or RHS is not a named type.
711 if (lhs->channel_type() != NULL
712 && rhs->channel_type() != NULL
713 && rhs->channel_type()->may_send()
714 && rhs->channel_type()->may_receive()
715 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
716 && Type::are_identical(lhs->channel_type()->element_type(),
717 rhs->channel_type()->element_type(),
718 true,
719 reason))
720 return true;
722 // The nil type may be assigned to a pointer, function, slice, map,
723 // channel, or interface type.
724 if (rhs->is_nil_type()
725 && (lhs->points_to() != NULL
726 || lhs->function_type() != NULL
727 || lhs->is_slice_type()
728 || lhs->map_type() != NULL
729 || lhs->channel_type() != NULL
730 || lhs->interface_type() != NULL))
731 return true;
733 // An untyped numeric constant may be assigned to a numeric type if
734 // it is representable in that type.
735 if ((rhs->is_abstract()
736 && (rhs->integer_type() != NULL
737 || rhs->float_type() != NULL
738 || rhs->complex_type() != NULL))
739 && (lhs->integer_type() != NULL
740 || lhs->float_type() != NULL
741 || lhs->complex_type() != NULL))
742 return true;
744 // Give some better error messages.
745 if (reason != NULL && reason->empty())
747 if (rhs->interface_type() != NULL)
748 reason->assign(_("need explicit conversion"));
749 else if (lhs_orig->named_type() != NULL
750 && rhs_orig->named_type() != NULL)
752 size_t len = (lhs_orig->named_type()->name().length()
753 + rhs_orig->named_type()->name().length()
754 + 100);
755 char* buf = new char[len];
756 snprintf(buf, len, _("cannot use type %s as type %s"),
757 rhs_orig->named_type()->message_name().c_str(),
758 lhs_orig->named_type()->message_name().c_str());
759 reason->assign(buf);
760 delete[] buf;
764 return false;
767 // Return true if a value with type RHS may be converted to type LHS.
768 // If REASON is not NULL, set *REASON to the reason the types are not
769 // convertible.
771 bool
772 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
774 // The types are convertible if they are assignable.
775 if (Type::are_assignable(lhs, rhs, reason))
776 return true;
778 // Ignore aliases.
779 lhs = lhs->unalias();
780 rhs = rhs->unalias();
782 // A pointer to a regular type may not be converted to a pointer to
783 // a type that may not live in the heap, except when converting from
784 // unsafe.Pointer.
785 if (lhs->points_to() != NULL
786 && rhs->points_to() != NULL
787 && !lhs->points_to()->in_heap()
788 && rhs->points_to()->in_heap()
789 && !rhs->is_unsafe_pointer_type())
791 if (reason != NULL)
792 reason->assign(_("conversion from normal type to notinheap type"));
793 return false;
796 // The types are convertible if they have identical underlying
797 // types, ignoring struct field tags.
798 if ((lhs->named_type() != NULL || rhs->named_type() != NULL)
799 && Type::are_identical_cmp_tags(lhs->base(), rhs->base(), IGNORE_TAGS,
800 true, reason))
801 return true;
803 // The types are convertible if they are both unnamed pointer types
804 // and their pointer base types have identical underlying types,
805 // ignoring struct field tags.
806 if (lhs->named_type() == NULL
807 && rhs->named_type() == NULL
808 && lhs->points_to() != NULL
809 && rhs->points_to() != NULL
810 && (lhs->points_to()->named_type() != NULL
811 || rhs->points_to()->named_type() != NULL)
812 && Type::are_identical_cmp_tags(lhs->points_to()->base(),
813 rhs->points_to()->base(),
814 IGNORE_TAGS,
815 true,
816 reason))
817 return true;
819 // Integer and floating point types are convertible to each other.
820 if ((lhs->integer_type() != NULL || lhs->float_type() != NULL)
821 && (rhs->integer_type() != NULL || rhs->float_type() != NULL))
822 return true;
824 // Complex types are convertible to each other.
825 if (lhs->complex_type() != NULL && rhs->complex_type() != NULL)
826 return true;
828 // An integer, or []byte, or []rune, may be converted to a string.
829 if (lhs->is_string_type())
831 if (rhs->integer_type() != NULL)
832 return true;
833 if (rhs->is_slice_type())
835 const Type* e = rhs->array_type()->element_type()->forwarded();
836 if (e->integer_type() != NULL
837 && (e->integer_type()->is_byte()
838 || e->integer_type()->is_rune()))
839 return true;
843 // A string may be converted to []byte or []rune.
844 if (rhs->is_string_type() && lhs->is_slice_type())
846 const Type* e = lhs->array_type()->element_type()->forwarded();
847 if (e->integer_type() != NULL
848 && (e->integer_type()->is_byte() || e->integer_type()->is_rune()))
849 return true;
852 // An unsafe.Pointer type may be converted to any pointer type or to
853 // a type whose underlying type is uintptr, and vice-versa.
854 if (lhs->is_unsafe_pointer_type()
855 && (rhs->points_to() != NULL
856 || (rhs->integer_type() != NULL
857 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
858 return true;
859 if (rhs->is_unsafe_pointer_type()
860 && (lhs->points_to() != NULL
861 || (lhs->integer_type() != NULL
862 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
863 return true;
865 // Give a better error message.
866 if (reason != NULL)
868 if (reason->empty())
869 *reason = "invalid type conversion";
870 else
872 std::string s = "invalid type conversion (";
873 s += *reason;
874 s += ')';
875 *reason = s;
879 return false;
882 // Copy expressions if it may change the size.
884 // The only type that has an expression is an array type. The only
885 // types whose size can be changed by the size of an array type are an
886 // array type itself, or a struct type with an array field.
887 Type*
888 Type::copy_expressions()
890 // This is run during parsing, so types may not be valid yet.
891 // We only have to worry about array type literals.
892 switch (this->classification_)
894 default:
895 return this;
897 case TYPE_ARRAY:
899 Array_type* at = this->array_type();
900 if (at->length() == NULL)
901 return this;
902 Expression* len = at->length()->copy();
903 if (at->length() == len)
904 return this;
905 return Type::make_array_type(at->element_type(), len);
908 case TYPE_STRUCT:
910 Struct_type* st = this->struct_type();
911 const Struct_field_list* sfl = st->fields();
912 if (sfl == NULL)
913 return this;
914 bool changed = false;
915 Struct_field_list *nsfl = new Struct_field_list();
916 for (Struct_field_list::const_iterator pf = sfl->begin();
917 pf != sfl->end();
918 ++pf)
920 Type* ft = pf->type()->copy_expressions();
921 Struct_field nf(Typed_identifier((pf->is_anonymous()
922 ? ""
923 : pf->field_name()),
925 pf->location()));
926 if (pf->has_tag())
927 nf.set_tag(pf->tag());
928 nsfl->push_back(nf);
929 if (ft != pf->type())
930 changed = true;
932 if (!changed)
934 delete(nsfl);
935 return this;
937 return Type::make_struct_type(nsfl, st->location());
941 go_unreachable();
944 // Return a hash code for the type to be used for method lookup.
946 unsigned int
947 Type::hash_for_method(Gogo* gogo) const
949 if (this->named_type() != NULL && this->named_type()->is_alias())
950 return this->named_type()->real_type()->hash_for_method(gogo);
951 unsigned int ret = 0;
952 if (this->classification_ != TYPE_FORWARD)
953 ret += this->classification_;
954 return ret + this->do_hash_for_method(gogo);
957 // Default implementation of do_hash_for_method. This is appropriate
958 // for types with no subfields.
960 unsigned int
961 Type::do_hash_for_method(Gogo*) const
963 return 0;
966 // Return a hash code for a string, given a starting hash.
968 unsigned int
969 Type::hash_string(const std::string& s, unsigned int h)
971 const char* p = s.data();
972 size_t len = s.length();
973 for (; len > 0; --len)
975 h ^= *p++;
976 h*= 16777619;
978 return h;
981 // A hash table mapping unnamed types to the backend representation of
982 // those types.
984 Type::Type_btypes Type::type_btypes;
986 // Return the backend representation for this type.
988 Btype*
989 Type::get_backend(Gogo* gogo)
991 if (this->btype_ != NULL)
992 return this->btype_;
994 if (this->named_type() != NULL && this->named_type()->is_alias()) {
995 Btype* bt = this->unalias()->get_backend(gogo);
996 if (gogo != NULL && gogo->named_types_are_converted())
997 this->btype_ = bt;
998 return bt;
1001 if (this->forward_declaration_type() != NULL
1002 || this->named_type() != NULL)
1003 return this->get_btype_without_hash(gogo);
1005 if (this->is_error_type())
1006 return gogo->backend()->error_type();
1008 // To avoid confusing the backend, translate all identical Go types
1009 // to the same backend representation. We use a hash table to do
1010 // that. There is no need to use the hash table for named types, as
1011 // named types are only identical to themselves.
1013 std::pair<Type*, Type_btype_entry> val;
1014 val.first = this;
1015 val.second.btype = NULL;
1016 val.second.is_placeholder = false;
1017 std::pair<Type_btypes::iterator, bool> ins =
1018 Type::type_btypes.insert(val);
1019 if (!ins.second && ins.first->second.btype != NULL)
1021 // Note that GOGO can be NULL here, but only when the GCC
1022 // middle-end is asking for a frontend type. That will only
1023 // happen for simple types, which should never require
1024 // placeholders.
1025 if (!ins.first->second.is_placeholder)
1026 this->btype_ = ins.first->second.btype;
1027 else if (gogo->named_types_are_converted())
1029 this->finish_backend(gogo, ins.first->second.btype);
1030 ins.first->second.is_placeholder = false;
1033 return ins.first->second.btype;
1036 Btype* bt = this->get_btype_without_hash(gogo);
1038 if (ins.first->second.btype == NULL)
1040 ins.first->second.btype = bt;
1041 ins.first->second.is_placeholder = false;
1043 else
1045 // We have already created a backend representation for this
1046 // type. This can happen when an unnamed type is defined using
1047 // a named type which in turns uses an identical unnamed type.
1048 // Use the representation we created earlier and ignore the one we just
1049 // built.
1050 if (this->btype_ == bt)
1051 this->btype_ = ins.first->second.btype;
1052 bt = ins.first->second.btype;
1055 return bt;
1058 // Return the backend representation for a type without looking in the
1059 // hash table for identical types. This is used for named types,
1060 // since a named type is never identical to any other type.
1062 Btype*
1063 Type::get_btype_without_hash(Gogo* gogo)
1065 if (this->btype_ == NULL)
1067 Btype* bt = this->do_get_backend(gogo);
1069 // For a recursive function or pointer type, we will temporarily
1070 // return a circular pointer type during the recursion. We
1071 // don't want to record that for a forwarding type, as it may
1072 // confuse us later.
1073 if (this->forward_declaration_type() != NULL
1074 && gogo->backend()->is_circular_pointer_type(bt))
1075 return bt;
1077 if (gogo == NULL || !gogo->named_types_are_converted())
1078 return bt;
1080 this->btype_ = bt;
1082 return this->btype_;
1085 // Get the backend representation of a type without forcing the
1086 // creation of the backend representation of all supporting types.
1087 // This will return a backend type that has the correct size but may
1088 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1089 // and will not contain the final representation of the type to which
1090 // it points. This is used while converting all named types to the
1091 // backend representation, to avoid problems with indirect references
1092 // to types which are not yet complete. When this is called, the
1093 // sizes of all direct references (e.g., a struct field) should be
1094 // known, but the sizes of indirect references (e.g., the type to
1095 // which a pointer points) may not.
1097 Btype*
1098 Type::get_backend_placeholder(Gogo* gogo)
1100 if (gogo->named_types_are_converted())
1101 return this->get_backend(gogo);
1102 if (this->btype_ != NULL)
1103 return this->btype_;
1105 Btype* bt;
1106 switch (this->classification_)
1108 case TYPE_ERROR:
1109 case TYPE_VOID:
1110 case TYPE_BOOLEAN:
1111 case TYPE_INTEGER:
1112 case TYPE_FLOAT:
1113 case TYPE_COMPLEX:
1114 case TYPE_STRING:
1115 case TYPE_NIL:
1116 // These are simple types that can just be created directly.
1117 return this->get_backend(gogo);
1119 case TYPE_MAP:
1120 case TYPE_CHANNEL:
1121 // All maps and channels have the same backend representation.
1122 return this->get_backend(gogo);
1124 case TYPE_NAMED:
1125 case TYPE_FORWARD:
1126 // Named types keep track of their own dependencies and manage
1127 // their own placeholders.
1128 return this->get_backend(gogo);
1130 case TYPE_INTERFACE:
1131 if (this->interface_type()->is_empty())
1132 return Interface_type::get_backend_empty_interface_type(gogo);
1133 break;
1135 default:
1136 break;
1139 std::pair<Type*, Type_btype_entry> val;
1140 val.first = this;
1141 val.second.btype = NULL;
1142 val.second.is_placeholder = false;
1143 std::pair<Type_btypes::iterator, bool> ins =
1144 Type::type_btypes.insert(val);
1145 if (!ins.second && ins.first->second.btype != NULL)
1146 return ins.first->second.btype;
1148 switch (this->classification_)
1150 case TYPE_FUNCTION:
1152 // A Go function type is a pointer to a struct type.
1153 Location loc = this->function_type()->location();
1154 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1156 break;
1158 case TYPE_POINTER:
1160 Location loc = Linemap::unknown_location();
1161 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1162 Pointer_type* pt = this->convert<Pointer_type, TYPE_POINTER>();
1163 Type::placeholder_pointers.push_back(pt);
1165 break;
1167 case TYPE_STRUCT:
1168 // We don't have to make the struct itself be a placeholder. We
1169 // are promised that we know the sizes of the struct fields.
1170 // But we may have to use a placeholder for any particular
1171 // struct field.
1173 std::vector<Backend::Btyped_identifier> bfields;
1174 get_backend_struct_fields(gogo, this->struct_type()->fields(),
1175 true, &bfields);
1176 bt = gogo->backend()->struct_type(bfields);
1178 break;
1180 case TYPE_ARRAY:
1181 if (this->is_slice_type())
1183 std::vector<Backend::Btyped_identifier> bfields;
1184 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1185 bt = gogo->backend()->struct_type(bfields);
1187 else
1189 Btype* element = this->array_type()->get_backend_element(gogo, true);
1190 Bexpression* len = this->array_type()->get_backend_length(gogo);
1191 bt = gogo->backend()->array_type(element, len);
1193 break;
1195 case TYPE_INTERFACE:
1197 go_assert(!this->interface_type()->is_empty());
1198 std::vector<Backend::Btyped_identifier> bfields;
1199 get_backend_interface_fields(gogo, this->interface_type(), true,
1200 &bfields);
1201 bt = gogo->backend()->struct_type(bfields);
1203 break;
1205 case TYPE_SINK:
1206 case TYPE_CALL_MULTIPLE_RESULT:
1207 /* Note that various classifications were handled in the earlier
1208 switch. */
1209 default:
1210 go_unreachable();
1213 if (ins.first->second.btype == NULL)
1215 ins.first->second.btype = bt;
1216 ins.first->second.is_placeholder = true;
1218 else
1220 // A placeholder for this type got created along the way. Use
1221 // that one and ignore the one we just built.
1222 bt = ins.first->second.btype;
1225 return bt;
1228 // Complete the backend representation. This is called for a type
1229 // using a placeholder type.
1231 void
1232 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1234 switch (this->classification_)
1236 case TYPE_ERROR:
1237 case TYPE_VOID:
1238 case TYPE_BOOLEAN:
1239 case TYPE_INTEGER:
1240 case TYPE_FLOAT:
1241 case TYPE_COMPLEX:
1242 case TYPE_STRING:
1243 case TYPE_NIL:
1244 go_unreachable();
1246 case TYPE_FUNCTION:
1248 Btype* bt = this->do_get_backend(gogo);
1249 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1250 go_assert(saw_errors());
1252 break;
1254 case TYPE_POINTER:
1256 Btype* bt = this->do_get_backend(gogo);
1257 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1258 go_assert(saw_errors());
1260 break;
1262 case TYPE_STRUCT:
1263 // The struct type itself is done, but we have to make sure that
1264 // all the field types are converted.
1265 this->struct_type()->finish_backend_fields(gogo);
1266 break;
1268 case TYPE_ARRAY:
1269 // The array type itself is done, but make sure the element type
1270 // is converted.
1271 this->array_type()->finish_backend_element(gogo);
1272 break;
1274 case TYPE_MAP:
1275 case TYPE_CHANNEL:
1276 go_unreachable();
1278 case TYPE_INTERFACE:
1279 // The interface type itself is done, but make sure the method
1280 // types are converted.
1281 this->interface_type()->finish_backend_methods(gogo);
1282 break;
1284 case TYPE_NAMED:
1285 case TYPE_FORWARD:
1286 go_unreachable();
1288 case TYPE_SINK:
1289 case TYPE_CALL_MULTIPLE_RESULT:
1290 default:
1291 go_unreachable();
1294 this->btype_ = placeholder;
1297 // Return a pointer to the type descriptor for this type.
1299 Bexpression*
1300 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1302 Type* t = this->unalias();
1303 if (t->type_descriptor_var_ == NULL)
1305 t->make_type_descriptor_var(gogo);
1306 go_assert(t->type_descriptor_var_ != NULL);
1308 Bexpression* var_expr =
1309 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1310 Bexpression* var_addr =
1311 gogo->backend()->address_expression(var_expr, location);
1312 Type* td_type = Type::make_type_descriptor_type();
1313 Btype* td_btype = td_type->get_backend(gogo);
1314 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1315 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1318 // A mapping from unnamed types to type descriptor variables.
1320 Type::Type_descriptor_vars Type::type_descriptor_vars;
1322 // Build the type descriptor for this type.
1324 void
1325 Type::make_type_descriptor_var(Gogo* gogo)
1327 go_assert(this->type_descriptor_var_ == NULL);
1329 Named_type* nt = this->named_type();
1331 // We can have multiple instances of unnamed types, but we only want
1332 // to emit the type descriptor once. We use a hash table. This is
1333 // not necessary for named types, as they are unique, and we store
1334 // the type descriptor in the type itself.
1335 Bvariable** phash = NULL;
1336 if (nt == NULL)
1338 Bvariable* bvnull = NULL;
1339 std::pair<Type_descriptor_vars::iterator, bool> ins =
1340 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1341 if (!ins.second)
1343 // We've already built a type descriptor for this type.
1344 this->type_descriptor_var_ = ins.first->second;
1345 return;
1347 phash = &ins.first->second;
1350 // The type descriptor symbol for the unsafe.Pointer type is defined in
1351 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1352 // symbol if necessary.
1353 if (this->is_unsafe_pointer_type())
1355 Location bloc = Linemap::predeclared_location();
1357 Type* td_type = Type::make_type_descriptor_type();
1358 Btype* td_btype = td_type->get_backend(gogo);
1359 std::string name = gogo->type_descriptor_name(this, nt);
1360 std::string asm_name(go_selectively_encode_id(name));
1361 this->type_descriptor_var_ =
1362 gogo->backend()->immutable_struct_reference(name, asm_name,
1363 td_btype,
1364 bloc);
1366 if (phash != NULL)
1367 *phash = this->type_descriptor_var_;
1368 return;
1371 std::string var_name = gogo->type_descriptor_name(this, nt);
1373 // Build the contents of the type descriptor.
1374 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1376 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1378 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1380 const Package* dummy;
1381 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1383 std::string asm_name(go_selectively_encode_id(var_name));
1384 this->type_descriptor_var_ =
1385 gogo->backend()->immutable_struct_reference(var_name, asm_name,
1386 initializer_btype,
1387 loc);
1388 if (phash != NULL)
1389 *phash = this->type_descriptor_var_;
1390 return;
1393 // See if this type descriptor can appear in multiple packages.
1394 bool is_common = false;
1395 if (nt != NULL)
1397 // We create the descriptor for a builtin type whenever we need
1398 // it.
1399 is_common = nt->is_builtin();
1401 else
1403 // This is an unnamed type. The descriptor could be defined in
1404 // any package where it is needed, and the linker will pick one
1405 // descriptor to keep.
1406 is_common = true;
1409 // We are going to build the type descriptor in this package. We
1410 // must create the variable before we convert the initializer to the
1411 // backend representation, because the initializer may refer to the
1412 // type descriptor of this type. By setting type_descriptor_var_ we
1413 // ensure that type_descriptor_pointer will work if called while
1414 // converting INITIALIZER.
1416 std::string asm_name(go_selectively_encode_id(var_name));
1417 this->type_descriptor_var_ =
1418 gogo->backend()->immutable_struct(var_name, asm_name, false, is_common,
1419 initializer_btype, loc);
1420 if (phash != NULL)
1421 *phash = this->type_descriptor_var_;
1423 Translate_context context(gogo, NULL, NULL, NULL);
1424 context.set_is_const();
1425 Bexpression* binitializer = initializer->get_backend(&context);
1427 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1428 var_name, false, is_common,
1429 initializer_btype, loc,
1430 binitializer);
1433 // Return true if this type descriptor is defined in a different
1434 // package. If this returns true it sets *PACKAGE to the package.
1436 bool
1437 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1438 const Package** package)
1440 if (nt != NULL)
1442 if (nt->named_object()->package() != NULL)
1444 // This is a named type defined in a different package. The
1445 // type descriptor should be defined in that package.
1446 *package = nt->named_object()->package();
1447 return true;
1450 else
1452 if (this->points_to() != NULL
1453 && this->points_to()->named_type() != NULL
1454 && this->points_to()->named_type()->named_object()->package() != NULL)
1456 // This is an unnamed pointer to a named type defined in a
1457 // different package. The descriptor should be defined in
1458 // that package.
1459 *package = this->points_to()->named_type()->named_object()->package();
1460 return true;
1463 return false;
1466 // Return a composite literal for a type descriptor.
1468 Expression*
1469 Type::type_descriptor(Gogo* gogo, Type* type)
1471 return type->do_type_descriptor(gogo, NULL);
1474 // Return a composite literal for a type descriptor with a name.
1476 Expression*
1477 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1479 go_assert(name != NULL && type->named_type() != name);
1480 return type->do_type_descriptor(gogo, name);
1483 // Make a builtin struct type from a list of fields. The fields are
1484 // pairs of a name and a type.
1486 Struct_type*
1487 Type::make_builtin_struct_type(int nfields, ...)
1489 va_list ap;
1490 va_start(ap, nfields);
1492 Location bloc = Linemap::predeclared_location();
1493 Struct_field_list* sfl = new Struct_field_list();
1494 for (int i = 0; i < nfields; i++)
1496 const char* field_name = va_arg(ap, const char *);
1497 Type* type = va_arg(ap, Type*);
1498 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1501 va_end(ap);
1503 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1504 ret->set_is_struct_incomparable();
1505 return ret;
1508 // A list of builtin named types.
1510 std::vector<Named_type*> Type::named_builtin_types;
1512 // Make a builtin named type.
1514 Named_type*
1515 Type::make_builtin_named_type(const char* name, Type* type)
1517 Location bloc = Linemap::predeclared_location();
1518 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1519 Named_type* ret = no->type_value();
1520 Type::named_builtin_types.push_back(ret);
1521 return ret;
1524 // Convert the named builtin types.
1526 void
1527 Type::convert_builtin_named_types(Gogo* gogo)
1529 for (std::vector<Named_type*>::const_iterator p =
1530 Type::named_builtin_types.begin();
1531 p != Type::named_builtin_types.end();
1532 ++p)
1534 bool r = (*p)->verify();
1535 go_assert(r);
1536 (*p)->convert(gogo);
1540 // Return the type of a type descriptor. We should really tie this to
1541 // runtime.Type rather than copying it. This must match the struct "_type"
1542 // declared in libgo/go/runtime/type.go.
1544 Type*
1545 Type::make_type_descriptor_type()
1547 static Type* ret;
1548 if (ret == NULL)
1550 Location bloc = Linemap::predeclared_location();
1552 Type* uint8_type = Type::lookup_integer_type("uint8");
1553 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1554 Type* uint32_type = Type::lookup_integer_type("uint32");
1555 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1556 Type* string_type = Type::lookup_string_type();
1557 Type* pointer_string_type = Type::make_pointer_type(string_type);
1559 // This is an unnamed version of unsafe.Pointer. Perhaps we
1560 // should use the named version instead, although that would
1561 // require us to create the unsafe package if it has not been
1562 // imported. It probably doesn't matter.
1563 Type* void_type = Type::make_void_type();
1564 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1566 Typed_identifier_list *params = new Typed_identifier_list();
1567 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1568 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1570 Typed_identifier_list* results = new Typed_identifier_list();
1571 results->push_back(Typed_identifier("", uintptr_type, bloc));
1573 Type* hash_fntype = Type::make_function_type(NULL, params, results,
1574 bloc);
1576 params = new Typed_identifier_list();
1577 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1578 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1580 results = new Typed_identifier_list();
1581 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1583 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1584 bloc);
1586 // Forward declaration for the type descriptor type.
1587 Named_object* named_type_descriptor_type =
1588 Named_object::make_type_declaration("_type", NULL, bloc);
1589 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1590 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1592 // The type of a method on a concrete type.
1593 Struct_type* method_type =
1594 Type::make_builtin_struct_type(5,
1595 "name", pointer_string_type,
1596 "pkgPath", pointer_string_type,
1597 "mtyp", pointer_type_descriptor_type,
1598 "typ", pointer_type_descriptor_type,
1599 "tfn", unsafe_pointer_type);
1600 Named_type* named_method_type =
1601 Type::make_builtin_named_type("method", method_type);
1603 // Information for types with a name or methods.
1604 Type* slice_named_method_type =
1605 Type::make_array_type(named_method_type, NULL);
1606 Struct_type* uncommon_type =
1607 Type::make_builtin_struct_type(3,
1608 "name", pointer_string_type,
1609 "pkgPath", pointer_string_type,
1610 "methods", slice_named_method_type);
1611 Named_type* named_uncommon_type =
1612 Type::make_builtin_named_type("uncommonType", uncommon_type);
1614 Type* pointer_uncommon_type =
1615 Type::make_pointer_type(named_uncommon_type);
1617 // The type descriptor type.
1619 Struct_type* type_descriptor_type =
1620 Type::make_builtin_struct_type(12,
1621 "size", uintptr_type,
1622 "ptrdata", uintptr_type,
1623 "hash", uint32_type,
1624 "kind", uint8_type,
1625 "align", uint8_type,
1626 "fieldAlign", uint8_type,
1627 "hashfn", hash_fntype,
1628 "equalfn", equal_fntype,
1629 "gcdata", pointer_uint8_type,
1630 "string", pointer_string_type,
1631 "", pointer_uncommon_type,
1632 "ptrToThis",
1633 pointer_type_descriptor_type);
1635 Named_type* named = Type::make_builtin_named_type("_type",
1636 type_descriptor_type);
1638 named_type_descriptor_type->set_type_value(named);
1640 ret = named;
1643 return ret;
1646 // Make the type of a pointer to a type descriptor as represented in
1647 // Go.
1649 Type*
1650 Type::make_type_descriptor_ptr_type()
1652 static Type* ret;
1653 if (ret == NULL)
1654 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1655 return ret;
1658 // Return the alignment required by the memequalN function. N is a
1659 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1660 // in libgo/go/runtime/alg.go.
1662 int64_t
1663 Type::memequal_align(Gogo* gogo, int size)
1665 const char* tn;
1666 switch (size)
1668 case 16:
1669 tn = "int16";
1670 break;
1671 case 32:
1672 tn = "int32";
1673 break;
1674 case 64:
1675 tn = "int64";
1676 break;
1677 case 128:
1678 // The code uses [2]int64, which must have the same alignment as
1679 // int64.
1680 tn = "int64";
1681 break;
1682 default:
1683 go_unreachable();
1686 Type* t = Type::lookup_integer_type(tn);
1688 int64_t ret;
1689 if (!t->backend_type_align(gogo, &ret))
1690 go_unreachable();
1691 return ret;
1694 // Return whether this type needs specially built type functions.
1695 // This returns true for types that are comparable and either can not
1696 // use an identity comparison, or are a non-standard size.
1698 bool
1699 Type::needs_specific_type_functions(Gogo* gogo)
1701 Named_type* nt = this->named_type();
1702 if (nt != NULL && nt->is_alias())
1703 return false;
1704 if (!this->is_comparable())
1705 return false;
1706 if (!this->compare_is_identity(gogo))
1707 return true;
1709 // We create a few predeclared types for type descriptors; they are
1710 // really just for the backend and don't need hash or equality
1711 // functions.
1712 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1713 return false;
1715 int64_t size, align;
1716 if (!this->backend_type_size(gogo, &size)
1717 || !this->backend_type_align(gogo, &align))
1719 go_assert(saw_errors());
1720 return false;
1722 // This switch matches the one in Type::type_functions.
1723 switch (size)
1725 case 0:
1726 case 1:
1727 case 2:
1728 return align < Type::memequal_align(gogo, 16);
1729 case 4:
1730 return align < Type::memequal_align(gogo, 32);
1731 case 8:
1732 return align < Type::memequal_align(gogo, 64);
1733 case 16:
1734 return align < Type::memequal_align(gogo, 128);
1735 default:
1736 return true;
1740 // Set *HASH_FN and *EQUAL_FN to the runtime functions which compute a
1741 // hash code for this type and which compare whether two values of
1742 // this type are equal. If NAME is not NULL it is the name of this
1743 // type. HASH_FNTYPE and EQUAL_FNTYPE are the types of these
1744 // functions, for convenience; they may be NULL.
1746 void
1747 Type::type_functions(Gogo* gogo, Named_type* name, Function_type* hash_fntype,
1748 Function_type* equal_fntype, Named_object** hash_fn,
1749 Named_object** equal_fn)
1751 // If the unaliased type is not a named type, then the type does not
1752 // have a name after all.
1753 if (name != NULL)
1754 name = name->unalias()->named_type();
1756 if (!this->is_comparable())
1758 *hash_fn = NULL;
1759 *equal_fn = NULL;
1760 return;
1763 if (hash_fntype == NULL || equal_fntype == NULL)
1765 Location bloc = Linemap::predeclared_location();
1767 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1768 Type* void_type = Type::make_void_type();
1769 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1771 if (hash_fntype == NULL)
1773 Typed_identifier_list* params = new Typed_identifier_list();
1774 params->push_back(Typed_identifier("key", unsafe_pointer_type,
1775 bloc));
1776 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1778 Typed_identifier_list* results = new Typed_identifier_list();
1779 results->push_back(Typed_identifier("", uintptr_type, bloc));
1781 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1783 if (equal_fntype == NULL)
1785 Typed_identifier_list* params = new Typed_identifier_list();
1786 params->push_back(Typed_identifier("key1", unsafe_pointer_type,
1787 bloc));
1788 params->push_back(Typed_identifier("key2", unsafe_pointer_type,
1789 bloc));
1791 Typed_identifier_list* results = new Typed_identifier_list();
1792 results->push_back(Typed_identifier("", Type::lookup_bool_type(),
1793 bloc));
1795 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
1799 const char* hash_fnname;
1800 const char* equal_fnname;
1801 if (this->compare_is_identity(gogo))
1803 int64_t size, align;
1804 if (!this->backend_type_size(gogo, &size)
1805 || !this->backend_type_align(gogo, &align))
1807 go_assert(saw_errors());
1808 return;
1810 bool build_functions = false;
1811 // This switch matches the one in Type::needs_specific_type_functions.
1812 // The alignment tests are because of the memequal functions,
1813 // which assume that the values are aligned as required for an
1814 // integer of that size.
1815 switch (size)
1817 case 0:
1818 hash_fnname = "runtime.memhash0";
1819 equal_fnname = "runtime.memequal0";
1820 break;
1821 case 1:
1822 hash_fnname = "runtime.memhash8";
1823 equal_fnname = "runtime.memequal8";
1824 break;
1825 case 2:
1826 if (align < Type::memequal_align(gogo, 16))
1827 build_functions = true;
1828 else
1830 hash_fnname = "runtime.memhash16";
1831 equal_fnname = "runtime.memequal16";
1833 break;
1834 case 4:
1835 if (align < Type::memequal_align(gogo, 32))
1836 build_functions = true;
1837 else
1839 hash_fnname = "runtime.memhash32";
1840 equal_fnname = "runtime.memequal32";
1842 break;
1843 case 8:
1844 if (align < Type::memequal_align(gogo, 64))
1845 build_functions = true;
1846 else
1848 hash_fnname = "runtime.memhash64";
1849 equal_fnname = "runtime.memequal64";
1851 break;
1852 case 16:
1853 if (align < Type::memequal_align(gogo, 128))
1854 build_functions = true;
1855 else
1857 hash_fnname = "runtime.memhash128";
1858 equal_fnname = "runtime.memequal128";
1860 break;
1861 default:
1862 build_functions = true;
1863 break;
1865 if (build_functions)
1867 // We don't have a built-in function for a type of this size
1868 // and alignment. Build a function to use that calls the
1869 // generic hash/equality functions for identity, passing the size.
1870 this->specific_type_functions(gogo, name, size, hash_fntype,
1871 equal_fntype, hash_fn, equal_fn);
1872 return;
1875 else
1877 switch (this->base()->classification())
1879 case Type::TYPE_ERROR:
1880 case Type::TYPE_VOID:
1881 case Type::TYPE_NIL:
1882 case Type::TYPE_FUNCTION:
1883 case Type::TYPE_MAP:
1884 // For these types is_comparable should have returned false.
1885 go_unreachable();
1887 case Type::TYPE_BOOLEAN:
1888 case Type::TYPE_INTEGER:
1889 case Type::TYPE_POINTER:
1890 case Type::TYPE_CHANNEL:
1891 // For these types compare_is_identity should have returned true.
1892 go_unreachable();
1894 case Type::TYPE_FLOAT:
1895 switch (this->float_type()->bits())
1897 case 32:
1898 hash_fnname = "runtime.f32hash";
1899 equal_fnname = "runtime.f32equal";
1900 break;
1901 case 64:
1902 hash_fnname = "runtime.f64hash";
1903 equal_fnname = "runtime.f64equal";
1904 break;
1905 default:
1906 go_unreachable();
1908 break;
1910 case Type::TYPE_COMPLEX:
1911 switch (this->complex_type()->bits())
1913 case 64:
1914 hash_fnname = "runtime.c64hash";
1915 equal_fnname = "runtime.c64equal";
1916 break;
1917 case 128:
1918 hash_fnname = "runtime.c128hash";
1919 equal_fnname = "runtime.c128equal";
1920 break;
1921 default:
1922 go_unreachable();
1924 break;
1926 case Type::TYPE_STRING:
1927 hash_fnname = "runtime.strhash";
1928 equal_fnname = "runtime.strequal";
1929 break;
1931 case Type::TYPE_STRUCT:
1933 // This is a struct which can not be compared using a
1934 // simple identity function. We need to build a function
1935 // for comparison.
1936 this->specific_type_functions(gogo, name, -1, hash_fntype,
1937 equal_fntype, hash_fn, equal_fn);
1938 return;
1941 case Type::TYPE_ARRAY:
1942 if (this->is_slice_type())
1944 // Type::is_compatible_for_comparison should have
1945 // returned false.
1946 go_unreachable();
1948 else
1950 // This is an array which can not be compared using a
1951 // simple identity function. We need to build a
1952 // function for comparison.
1953 this->specific_type_functions(gogo, name, -1, hash_fntype,
1954 equal_fntype, hash_fn, equal_fn);
1955 return;
1957 break;
1959 case Type::TYPE_INTERFACE:
1960 if (this->interface_type()->is_empty())
1962 hash_fnname = "runtime.nilinterhash";
1963 equal_fnname = "runtime.nilinterequal";
1965 else
1967 hash_fnname = "runtime.interhash";
1968 equal_fnname = "runtime.interequal";
1970 break;
1972 case Type::TYPE_NAMED:
1973 case Type::TYPE_FORWARD:
1974 go_unreachable();
1976 default:
1977 go_unreachable();
1982 Location bloc = Linemap::predeclared_location();
1983 *hash_fn = Named_object::make_function_declaration(hash_fnname, NULL,
1984 hash_fntype, bloc);
1985 (*hash_fn)->func_declaration_value()->set_asm_name(hash_fnname);
1986 *equal_fn = Named_object::make_function_declaration(equal_fnname, NULL,
1987 equal_fntype, bloc);
1988 (*equal_fn)->func_declaration_value()->set_asm_name(equal_fnname);
1991 // A hash table mapping types to the specific hash functions.
1993 Type::Type_functions Type::type_functions_table;
1995 // Handle a type function which is specific to a type: if SIZE == -1,
1996 // this is a struct or array that can not use an identity comparison.
1997 // Otherwise, it is a type that uses an identity comparison but is not
1998 // one of the standard supported sizes.
2000 void
2001 Type::specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2002 Function_type* hash_fntype,
2003 Function_type* equal_fntype,
2004 Named_object** hash_fn,
2005 Named_object** equal_fn)
2007 Hash_equal_fn fnull(NULL, NULL);
2008 std::pair<Type*, Hash_equal_fn> val(name != NULL ? name : this, fnull);
2009 std::pair<Type_functions::iterator, bool> ins =
2010 Type::type_functions_table.insert(val);
2011 if (!ins.second)
2013 // We already have functions for this type
2014 *hash_fn = ins.first->second.first;
2015 *equal_fn = ins.first->second.second;
2016 return;
2019 std::string hash_name;
2020 std::string equal_name;
2021 gogo->specific_type_function_names(this, name, &hash_name, &equal_name);
2023 Location bloc = Linemap::predeclared_location();
2025 const Package* package = NULL;
2026 bool is_defined_elsewhere =
2027 this->type_descriptor_defined_elsewhere(name, &package);
2028 if (is_defined_elsewhere)
2030 *hash_fn = Named_object::make_function_declaration(hash_name, package,
2031 hash_fntype, bloc);
2032 *equal_fn = Named_object::make_function_declaration(equal_name, package,
2033 equal_fntype, bloc);
2035 else
2037 *hash_fn = gogo->declare_package_function(hash_name, hash_fntype, bloc);
2038 *equal_fn = gogo->declare_package_function(equal_name, equal_fntype,
2039 bloc);
2042 ins.first->second.first = *hash_fn;
2043 ins.first->second.second = *equal_fn;
2045 if (!is_defined_elsewhere)
2047 if (gogo->in_global_scope())
2048 this->write_specific_type_functions(gogo, name, size, hash_name,
2049 hash_fntype, equal_name,
2050 equal_fntype);
2051 else
2052 gogo->queue_specific_type_function(this, name, size, hash_name,
2053 hash_fntype, equal_name,
2054 equal_fntype);
2058 // Write the hash and equality functions for a type which needs to be
2059 // written specially.
2061 void
2062 Type::write_specific_type_functions(Gogo* gogo, Named_type* name, int64_t size,
2063 const std::string& hash_name,
2064 Function_type* hash_fntype,
2065 const std::string& equal_name,
2066 Function_type* equal_fntype)
2068 Location bloc = Linemap::predeclared_location();
2070 if (gogo->specific_type_functions_are_written())
2072 go_assert(saw_errors());
2073 return;
2076 go_assert(this->is_comparable());
2078 Named_object* hash_fn = gogo->start_function(hash_name, hash_fntype, false,
2079 bloc);
2080 hash_fn->func_value()->set_is_type_specific_function();
2081 gogo->start_block(bloc);
2083 if (size != -1)
2084 this->write_identity_hash(gogo, size);
2085 else if (name != NULL && name->real_type()->named_type() != NULL)
2086 this->write_named_hash(gogo, name, hash_fntype, equal_fntype);
2087 else if (this->struct_type() != NULL)
2088 this->struct_type()->write_hash_function(gogo, name, hash_fntype,
2089 equal_fntype);
2090 else if (this->array_type() != NULL)
2091 this->array_type()->write_hash_function(gogo, name, hash_fntype,
2092 equal_fntype);
2093 else
2094 go_unreachable();
2096 Block* b = gogo->finish_block(bloc);
2097 gogo->add_block(b, bloc);
2098 gogo->lower_block(hash_fn, b);
2099 gogo->finish_function(bloc);
2101 Named_object *equal_fn = gogo->start_function(equal_name, equal_fntype,
2102 false, bloc);
2103 equal_fn->func_value()->set_is_type_specific_function();
2104 gogo->start_block(bloc);
2106 if (size != -1)
2107 this->write_identity_equal(gogo, size);
2108 else if (name != NULL && name->real_type()->named_type() != NULL)
2109 this->write_named_equal(gogo, name);
2110 else if (this->struct_type() != NULL)
2111 this->struct_type()->write_equal_function(gogo, name);
2112 else if (this->array_type() != NULL)
2113 this->array_type()->write_equal_function(gogo, name);
2114 else
2115 go_unreachable();
2117 b = gogo->finish_block(bloc);
2118 gogo->add_block(b, bloc);
2119 gogo->lower_block(equal_fn, b);
2120 gogo->finish_function(bloc);
2122 // Build the function descriptors for the type descriptor to refer to.
2123 hash_fn->func_value()->descriptor(gogo, hash_fn);
2124 equal_fn->func_value()->descriptor(gogo, equal_fn);
2127 // Write a hash function for a type that can use an identity hash but
2128 // is not one of the standard supported sizes. For example, this
2129 // would be used for the type [3]byte. This builds a return statement
2130 // that returns a call to the memhash function, passing the key and
2131 // seed from the function arguments (already constructed before this
2132 // is called), and the constant size.
2134 void
2135 Type::write_identity_hash(Gogo* gogo, int64_t size)
2137 Location bloc = Linemap::predeclared_location();
2139 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2140 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2142 Typed_identifier_list* params = new Typed_identifier_list();
2143 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2144 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2145 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2147 Typed_identifier_list* results = new Typed_identifier_list();
2148 results->push_back(Typed_identifier("", uintptr_type, bloc));
2150 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2151 results, bloc);
2153 Named_object* memhash =
2154 Named_object::make_function_declaration("runtime.memhash", NULL,
2155 memhash_fntype, bloc);
2156 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2158 Named_object* key_arg = gogo->lookup("key", NULL);
2159 go_assert(key_arg != NULL);
2160 Named_object* seed_arg = gogo->lookup("seed", NULL);
2161 go_assert(seed_arg != NULL);
2163 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2164 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2165 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2166 bloc);
2167 Expression_list* args = new Expression_list();
2168 args->push_back(key_ref);
2169 args->push_back(seed_ref);
2170 args->push_back(size_arg);
2171 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2172 Expression* call = Expression::make_call(func, args, false, bloc);
2174 Expression_list* vals = new Expression_list();
2175 vals->push_back(call);
2176 Statement* s = Statement::make_return_statement(vals, bloc);
2177 gogo->add_statement(s);
2180 // Write an equality function for a type that can use an identity
2181 // equality comparison but is not one of the standard supported sizes.
2182 // For example, this would be used for the type [3]byte. This builds
2183 // a return statement that returns a call to the memequal function,
2184 // passing the two keys from the function arguments (already
2185 // constructed before this is called), and the constant size.
2187 void
2188 Type::write_identity_equal(Gogo* gogo, int64_t size)
2190 Location bloc = Linemap::predeclared_location();
2192 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2193 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2195 Typed_identifier_list* params = new Typed_identifier_list();
2196 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2197 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2198 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2200 Typed_identifier_list* results = new Typed_identifier_list();
2201 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2203 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2204 results, bloc);
2206 Named_object* memequal =
2207 Named_object::make_function_declaration("runtime.memequal", NULL,
2208 memequal_fntype, bloc);
2209 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2211 Named_object* key1_arg = gogo->lookup("key1", NULL);
2212 go_assert(key1_arg != NULL);
2213 Named_object* key2_arg = gogo->lookup("key2", NULL);
2214 go_assert(key2_arg != NULL);
2216 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2217 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2218 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2219 bloc);
2220 Expression_list* args = new Expression_list();
2221 args->push_back(key1_ref);
2222 args->push_back(key2_ref);
2223 args->push_back(size_arg);
2224 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2225 Expression* call = Expression::make_call(func, args, false, bloc);
2227 Expression_list* vals = new Expression_list();
2228 vals->push_back(call);
2229 Statement* s = Statement::make_return_statement(vals, bloc);
2230 gogo->add_statement(s);
2233 // Write a hash function that simply calls the hash function for a
2234 // named type. This is used when one named type is defined as
2235 // another. This ensures that this case works when the other named
2236 // type is defined in another package and relies on calling hash
2237 // functions defined only in that package.
2239 void
2240 Type::write_named_hash(Gogo* gogo, Named_type* name,
2241 Function_type* hash_fntype, Function_type* equal_fntype)
2243 Location bloc = Linemap::predeclared_location();
2245 Named_type* base_type = name->real_type()->named_type();
2246 while (base_type->is_alias())
2248 base_type = base_type->real_type()->named_type();
2249 go_assert(base_type != NULL);
2251 go_assert(base_type != NULL);
2253 // The pointer to the type we are going to hash. This is an
2254 // unsafe.Pointer.
2255 Named_object* key_arg = gogo->lookup("key", NULL);
2256 go_assert(key_arg != NULL);
2258 // The seed argument to the hash function.
2259 Named_object* seed_arg = gogo->lookup("seed", NULL);
2260 go_assert(seed_arg != NULL);
2262 Named_object* hash_fn;
2263 Named_object* equal_fn;
2264 name->real_type()->type_functions(gogo, base_type, hash_fntype, equal_fntype,
2265 &hash_fn, &equal_fn);
2267 // Call the hash function for the base type.
2268 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2269 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2270 Expression_list* args = new Expression_list();
2271 args->push_back(key_ref);
2272 args->push_back(seed_ref);
2273 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
2274 Expression* call = Expression::make_call(func, args, false, bloc);
2276 // Return the hash of the base type.
2277 Expression_list* vals = new Expression_list();
2278 vals->push_back(call);
2279 Statement* s = Statement::make_return_statement(vals, bloc);
2280 gogo->add_statement(s);
2283 // Write an equality function that simply calls the equality function
2284 // for a named type. This is used when one named type is defined as
2285 // another. This ensures that this case works when the other named
2286 // type is defined in another package and relies on calling equality
2287 // functions defined only in that package.
2289 void
2290 Type::write_named_equal(Gogo* gogo, Named_type* name)
2292 Location bloc = Linemap::predeclared_location();
2294 // The pointers to the types we are going to compare. These have
2295 // type unsafe.Pointer.
2296 Named_object* key1_arg = gogo->lookup("key1", NULL);
2297 Named_object* key2_arg = gogo->lookup("key2", NULL);
2298 go_assert(key1_arg != NULL && key2_arg != NULL);
2300 Named_type* base_type = name->real_type()->named_type();
2301 go_assert(base_type != NULL);
2303 // Build temporaries with the base type.
2304 Type* pt = Type::make_pointer_type(base_type);
2306 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2307 ref = Expression::make_cast(pt, ref, bloc);
2308 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2309 gogo->add_statement(p1);
2311 ref = Expression::make_var_reference(key2_arg, bloc);
2312 ref = Expression::make_cast(pt, ref, bloc);
2313 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2314 gogo->add_statement(p2);
2316 // Compare the values for equality.
2317 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2318 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2320 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2321 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2323 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2325 // Return the equality comparison.
2326 Expression_list* vals = new Expression_list();
2327 vals->push_back(cond);
2328 Statement* s = Statement::make_return_statement(vals, bloc);
2329 gogo->add_statement(s);
2332 // Return a composite literal for the type descriptor for a plain type
2333 // of kind RUNTIME_TYPE_KIND named NAME.
2335 Expression*
2336 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2337 Named_type* name, const Methods* methods,
2338 bool only_value_methods)
2340 Location bloc = Linemap::predeclared_location();
2342 Type* td_type = Type::make_type_descriptor_type();
2343 const Struct_field_list* fields = td_type->struct_type()->fields();
2345 Expression_list* vals = new Expression_list();
2346 vals->reserve(12);
2348 if (!this->has_pointer())
2349 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2350 if (this->points_to() != NULL)
2351 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2352 int64_t ptrsize;
2353 int64_t ptrdata;
2354 if (this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2355 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2357 Struct_field_list::const_iterator p = fields->begin();
2358 go_assert(p->is_field_name("size"));
2359 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2360 vals->push_back(Expression::make_type_info(this, type_info));
2362 ++p;
2363 go_assert(p->is_field_name("ptrdata"));
2364 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2365 vals->push_back(Expression::make_type_info(this, type_info));
2367 ++p;
2368 go_assert(p->is_field_name("hash"));
2369 unsigned int h;
2370 if (name != NULL)
2371 h = name->hash_for_method(gogo);
2372 else
2373 h = this->hash_for_method(gogo);
2374 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2376 ++p;
2377 go_assert(p->is_field_name("kind"));
2378 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2379 bloc));
2381 ++p;
2382 go_assert(p->is_field_name("align"));
2383 type_info = Expression::TYPE_INFO_ALIGNMENT;
2384 vals->push_back(Expression::make_type_info(this, type_info));
2386 ++p;
2387 go_assert(p->is_field_name("fieldAlign"));
2388 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2389 vals->push_back(Expression::make_type_info(this, type_info));
2391 ++p;
2392 go_assert(p->is_field_name("hashfn"));
2393 Function_type* hash_fntype = p->type()->function_type();
2395 ++p;
2396 go_assert(p->is_field_name("equalfn"));
2397 Function_type* equal_fntype = p->type()->function_type();
2399 Named_object* hash_fn;
2400 Named_object* equal_fn;
2401 this->type_functions(gogo, name, hash_fntype, equal_fntype, &hash_fn,
2402 &equal_fn);
2403 if (hash_fn == NULL)
2404 vals->push_back(Expression::make_cast(hash_fntype,
2405 Expression::make_nil(bloc),
2406 bloc));
2407 else
2408 vals->push_back(Expression::make_func_reference(hash_fn, NULL, bloc));
2409 if (equal_fn == NULL)
2410 vals->push_back(Expression::make_cast(equal_fntype,
2411 Expression::make_nil(bloc),
2412 bloc));
2413 else
2414 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2416 ++p;
2417 go_assert(p->is_field_name("gcdata"));
2418 vals->push_back(Expression::make_gc_symbol(this));
2420 ++p;
2421 go_assert(p->is_field_name("string"));
2422 Expression* s = Expression::make_string((name != NULL
2423 ? name->reflection(gogo)
2424 : this->reflection(gogo)),
2425 bloc);
2426 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2428 ++p;
2429 go_assert(p->is_field_name("uncommonType"));
2430 if (name == NULL && methods == NULL)
2431 vals->push_back(Expression::make_nil(bloc));
2432 else
2434 if (methods == NULL)
2435 methods = name->methods();
2436 vals->push_back(this->uncommon_type_constructor(gogo,
2437 p->type()->deref(),
2438 name, methods,
2439 only_value_methods));
2442 ++p;
2443 go_assert(p->is_field_name("ptrToThis"));
2444 if (name == NULL && methods == NULL)
2445 vals->push_back(Expression::make_nil(bloc));
2446 else
2448 Type* pt;
2449 if (name != NULL)
2450 pt = Type::make_pointer_type(name);
2451 else
2452 pt = Type::make_pointer_type(this);
2453 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2456 ++p;
2457 go_assert(p == fields->end());
2459 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2462 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2463 // length used by the gc toolchain, and also appears in
2464 // libgo/go/reflect/type.go.
2466 static const int64_t max_ptrmask_bytes = 2048;
2468 // Return a pointer to the Garbage Collection information for this type.
2470 Bexpression*
2471 Type::gc_symbol_pointer(Gogo* gogo)
2473 Type* t = this->unalias();
2475 if (!t->has_pointer())
2476 return gogo->backend()->nil_pointer_expression();
2478 if (t->gc_symbol_var_ == NULL)
2480 t->make_gc_symbol_var(gogo);
2481 go_assert(t->gc_symbol_var_ != NULL);
2483 Location bloc = Linemap::predeclared_location();
2484 Bexpression* var_expr =
2485 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2486 Bexpression* addr_expr =
2487 gogo->backend()->address_expression(var_expr, bloc);
2489 Type* uint8_type = Type::lookup_integer_type("uint8");
2490 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2491 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2492 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2495 // A mapping from unnamed types to GC symbol variables.
2497 Type::GC_symbol_vars Type::gc_symbol_vars;
2499 // Build the GC symbol for this type.
2501 void
2502 Type::make_gc_symbol_var(Gogo* gogo)
2504 go_assert(this->gc_symbol_var_ == NULL);
2506 Named_type* nt = this->named_type();
2508 // We can have multiple instances of unnamed types and similar to type
2509 // descriptors, we only want to the emit the GC data once, so we use a
2510 // hash table.
2511 Bvariable** phash = NULL;
2512 if (nt == NULL)
2514 Bvariable* bvnull = NULL;
2515 std::pair<GC_symbol_vars::iterator, bool> ins =
2516 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2517 if (!ins.second)
2519 // We've already built a gc symbol for this type.
2520 this->gc_symbol_var_ = ins.first->second;
2521 return;
2523 phash = &ins.first->second;
2526 int64_t ptrsize;
2527 int64_t ptrdata;
2528 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2530 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2531 if (phash != NULL)
2532 *phash = this->gc_symbol_var_;
2533 return;
2536 std::string sym_name = gogo->gc_symbol_name(this);
2538 // Build the contents of the gc symbol.
2539 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2540 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2542 // If the type descriptor for this type is defined somewhere else, so is the
2543 // GC symbol.
2544 const Package* dummy;
2545 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2547 std::string asm_name(go_selectively_encode_id(sym_name));
2548 this->gc_symbol_var_ =
2549 gogo->backend()->implicit_variable_reference(sym_name, asm_name,
2550 sym_btype);
2551 if (phash != NULL)
2552 *phash = this->gc_symbol_var_;
2553 return;
2556 // See if this gc symbol can appear in multiple packages.
2557 bool is_common = false;
2558 if (nt != NULL)
2560 // We create the symbol for a builtin type whenever we need
2561 // it.
2562 is_common = nt->is_builtin();
2564 else
2566 // This is an unnamed type. The descriptor could be defined in
2567 // any package where it is needed, and the linker will pick one
2568 // descriptor to keep.
2569 is_common = true;
2572 // Since we are building the GC symbol in this package, we must create the
2573 // variable before converting the initializer to its backend representation
2574 // because the initializer may refer to the GC symbol for this type.
2575 std::string asm_name(go_selectively_encode_id(sym_name));
2576 this->gc_symbol_var_ =
2577 gogo->backend()->implicit_variable(sym_name, asm_name,
2578 sym_btype, false, true, is_common, 0);
2579 if (phash != NULL)
2580 *phash = this->gc_symbol_var_;
2582 Translate_context context(gogo, NULL, NULL, NULL);
2583 context.set_is_const();
2584 Bexpression* sym_binit = sym_init->get_backend(&context);
2585 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2586 sym_btype, false, true, is_common,
2587 sym_binit);
2590 // Return whether this type needs a GC program, and set *PTRDATA to
2591 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2592 // pointer.
2594 bool
2595 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2597 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2598 if (!voidptr->backend_type_size(gogo, ptrsize))
2599 go_unreachable();
2601 if (!this->backend_type_ptrdata(gogo, ptrdata))
2603 go_assert(saw_errors());
2604 return false;
2607 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2610 // A simple class used to build a GC ptrmask for a type.
2612 class Ptrmask
2614 public:
2615 Ptrmask(size_t count)
2616 : bits_((count + 7) / 8, 0)
2619 void
2620 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2622 std::string
2623 symname() const;
2625 Expression*
2626 constructor(Gogo* gogo) const;
2628 private:
2629 void
2630 set(size_t index)
2631 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2633 // The actual bits.
2634 std::vector<unsigned char> bits_;
2637 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2638 // counts in bytes. PTRSIZE is the size of a pointer on the target
2639 // system.
2641 void
2642 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2644 switch (type->base()->classification())
2646 default:
2647 case Type::TYPE_NIL:
2648 case Type::TYPE_CALL_MULTIPLE_RESULT:
2649 case Type::TYPE_NAMED:
2650 case Type::TYPE_FORWARD:
2651 go_unreachable();
2653 case Type::TYPE_ERROR:
2654 case Type::TYPE_VOID:
2655 case Type::TYPE_BOOLEAN:
2656 case Type::TYPE_INTEGER:
2657 case Type::TYPE_FLOAT:
2658 case Type::TYPE_COMPLEX:
2659 case Type::TYPE_SINK:
2660 break;
2662 case Type::TYPE_FUNCTION:
2663 case Type::TYPE_POINTER:
2664 case Type::TYPE_MAP:
2665 case Type::TYPE_CHANNEL:
2666 // These types are all a single pointer.
2667 go_assert((offset % ptrsize) == 0);
2668 this->set(offset / ptrsize);
2669 break;
2671 case Type::TYPE_STRING:
2672 // A string starts with a single pointer.
2673 go_assert((offset % ptrsize) == 0);
2674 this->set(offset / ptrsize);
2675 break;
2677 case Type::TYPE_INTERFACE:
2678 // An interface is two pointers.
2679 go_assert((offset % ptrsize) == 0);
2680 this->set(offset / ptrsize);
2681 this->set((offset / ptrsize) + 1);
2682 break;
2684 case Type::TYPE_STRUCT:
2686 if (!type->has_pointer())
2687 return;
2689 const Struct_field_list* fields = type->struct_type()->fields();
2690 int64_t soffset = 0;
2691 for (Struct_field_list::const_iterator pf = fields->begin();
2692 pf != fields->end();
2693 ++pf)
2695 int64_t field_align;
2696 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2698 go_assert(saw_errors());
2699 return;
2701 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2703 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2705 int64_t field_size;
2706 if (!pf->type()->backend_type_size(gogo, &field_size))
2708 go_assert(saw_errors());
2709 return;
2711 soffset += field_size;
2714 break;
2716 case Type::TYPE_ARRAY:
2717 if (type->is_slice_type())
2719 // A slice starts with a single pointer.
2720 go_assert((offset % ptrsize) == 0);
2721 this->set(offset / ptrsize);
2722 break;
2724 else
2726 if (!type->has_pointer())
2727 return;
2729 int64_t len;
2730 if (!type->array_type()->int_length(&len))
2732 go_assert(saw_errors());
2733 return;
2736 Type* element_type = type->array_type()->element_type();
2737 int64_t ele_size;
2738 if (!element_type->backend_type_size(gogo, &ele_size))
2740 go_assert(saw_errors());
2741 return;
2744 int64_t eoffset = 0;
2745 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2746 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2747 break;
2752 // Return a symbol name for this ptrmask. This is used to coalesce
2753 // identical ptrmasks, which are common. The symbol name must use
2754 // only characters that are valid in symbols. It's nice if it's
2755 // short. We convert it to a string that uses only 32 characters,
2756 // avoiding digits and u and U.
2758 std::string
2759 Ptrmask::symname() const
2761 const char chars[33] = "abcdefghijklmnopqrstvwxyzABCDEFG";
2762 go_assert(chars[32] == '\0');
2763 std::string ret;
2764 unsigned int b = 0;
2765 int remaining = 0;
2766 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2767 p != this->bits_.end();
2768 ++p)
2770 b |= *p << remaining;
2771 remaining += 8;
2772 while (remaining >= 5)
2774 ret += chars[b & 0x1f];
2775 b >>= 5;
2776 remaining -= 5;
2779 while (remaining > 0)
2781 ret += chars[b & 0x1f];
2782 b >>= 5;
2783 remaining -= 5;
2785 return ret;
2788 // Return a constructor for this ptrmask. This will be used to
2789 // initialize the runtime ptrmask value.
2791 Expression*
2792 Ptrmask::constructor(Gogo* gogo) const
2794 Location bloc = Linemap::predeclared_location();
2795 Type* byte_type = gogo->lookup_global("byte")->type_value();
2796 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
2797 bloc);
2798 Array_type* at = Type::make_array_type(byte_type, len);
2799 Expression_list* vals = new Expression_list();
2800 vals->reserve(this->bits_.size());
2801 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
2802 p != this->bits_.end();
2803 ++p)
2804 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
2805 return Expression::make_array_composite_literal(at, vals, bloc);
2808 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
2809 Type::GC_gcbits_vars Type::gc_gcbits_vars;
2811 // Return a ptrmask variable for a type. For a type descriptor this
2812 // is only used for variables that are small enough to not need a
2813 // gcprog, but for a global variable this is used for a variable of
2814 // any size. PTRDATA is the number of bytes of the type that contain
2815 // pointer data. PTRSIZE is the size of a pointer on the target
2816 // system.
2818 Bvariable*
2819 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
2821 Ptrmask ptrmask(ptrdata / ptrsize);
2822 if (ptrdata >= ptrsize)
2823 ptrmask.set_from(gogo, this, ptrsize, 0);
2824 else
2826 // This can happen in error cases. Just build an empty gcbits.
2827 go_assert(saw_errors());
2830 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
2831 Bvariable* bvnull = NULL;
2832 std::pair<GC_gcbits_vars::iterator, bool> ins =
2833 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
2834 if (!ins.second)
2836 // We've already built a GC symbol for this set of gcbits.
2837 return ins.first->second;
2840 Expression* val = ptrmask.constructor(gogo);
2841 Translate_context context(gogo, NULL, NULL, NULL);
2842 context.set_is_const();
2843 Bexpression* bval = val->get_backend(&context);
2845 std::string asm_name(go_selectively_encode_id(sym_name));
2846 Btype *btype = val->type()->get_backend(gogo);
2847 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, asm_name,
2848 btype, false, true,
2849 true, 0);
2850 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, false,
2851 true, true, bval);
2852 ins.first->second = ret;
2853 return ret;
2856 // A GCProg is used to build a program for the garbage collector.
2857 // This is used for types with a lot of pointer data, to reduce the
2858 // size of the data in the compiled program. The program is expanded
2859 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
2861 class GCProg
2863 public:
2864 GCProg()
2865 : bytes_(), index_(0), nb_(0)
2868 // The number of bits described so far.
2869 int64_t
2870 bit_index() const
2871 { return this->index_; }
2873 void
2874 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2876 void
2877 end();
2879 Expression*
2880 constructor(Gogo* gogo) const;
2882 private:
2883 void
2884 ptr(int64_t);
2886 bool
2887 should_repeat(int64_t, int64_t);
2889 void
2890 repeat(int64_t, int64_t);
2892 void
2893 zero_until(int64_t);
2895 void
2896 lit(unsigned char);
2898 void
2899 varint(int64_t);
2901 void
2902 flushlit();
2904 // Add a byte to the program.
2905 void
2906 byte(unsigned char x)
2907 { this->bytes_.push_back(x); }
2909 // The maximum number of bytes of literal bits.
2910 static const int max_literal = 127;
2912 // The program.
2913 std::vector<unsigned char> bytes_;
2914 // The index of the last bit described.
2915 int64_t index_;
2916 // The current set of literal bits.
2917 unsigned char b_[max_literal];
2918 // The current number of literal bits.
2919 int nb_;
2922 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
2923 // counts in bytes. PTRSIZE is the size of a pointer on the target
2924 // system.
2926 void
2927 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2929 switch (type->base()->classification())
2931 default:
2932 case Type::TYPE_NIL:
2933 case Type::TYPE_CALL_MULTIPLE_RESULT:
2934 case Type::TYPE_NAMED:
2935 case Type::TYPE_FORWARD:
2936 go_unreachable();
2938 case Type::TYPE_ERROR:
2939 case Type::TYPE_VOID:
2940 case Type::TYPE_BOOLEAN:
2941 case Type::TYPE_INTEGER:
2942 case Type::TYPE_FLOAT:
2943 case Type::TYPE_COMPLEX:
2944 case Type::TYPE_SINK:
2945 break;
2947 case Type::TYPE_FUNCTION:
2948 case Type::TYPE_POINTER:
2949 case Type::TYPE_MAP:
2950 case Type::TYPE_CHANNEL:
2951 // These types are all a single pointer.
2952 go_assert((offset % ptrsize) == 0);
2953 this->ptr(offset / ptrsize);
2954 break;
2956 case Type::TYPE_STRING:
2957 // A string starts with a single pointer.
2958 go_assert((offset % ptrsize) == 0);
2959 this->ptr(offset / ptrsize);
2960 break;
2962 case Type::TYPE_INTERFACE:
2963 // An interface is two pointers.
2964 go_assert((offset % ptrsize) == 0);
2965 this->ptr(offset / ptrsize);
2966 this->ptr((offset / ptrsize) + 1);
2967 break;
2969 case Type::TYPE_STRUCT:
2971 if (!type->has_pointer())
2972 return;
2974 const Struct_field_list* fields = type->struct_type()->fields();
2975 int64_t soffset = 0;
2976 for (Struct_field_list::const_iterator pf = fields->begin();
2977 pf != fields->end();
2978 ++pf)
2980 int64_t field_align;
2981 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2983 go_assert(saw_errors());
2984 return;
2986 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2988 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2990 int64_t field_size;
2991 if (!pf->type()->backend_type_size(gogo, &field_size))
2993 go_assert(saw_errors());
2994 return;
2996 soffset += field_size;
2999 break;
3001 case Type::TYPE_ARRAY:
3002 if (type->is_slice_type())
3004 // A slice starts with a single pointer.
3005 go_assert((offset % ptrsize) == 0);
3006 this->ptr(offset / ptrsize);
3007 break;
3009 else
3011 if (!type->has_pointer())
3012 return;
3014 int64_t len;
3015 if (!type->array_type()->int_length(&len))
3017 go_assert(saw_errors());
3018 return;
3021 Type* element_type = type->array_type()->element_type();
3023 // Flatten array of array to a big array by multiplying counts.
3024 while (element_type->array_type() != NULL
3025 && !element_type->is_slice_type())
3027 int64_t ele_len;
3028 if (!element_type->array_type()->int_length(&ele_len))
3030 go_assert(saw_errors());
3031 return;
3034 len *= ele_len;
3035 element_type = element_type->array_type()->element_type();
3038 int64_t ele_size;
3039 if (!element_type->backend_type_size(gogo, &ele_size))
3041 go_assert(saw_errors());
3042 return;
3045 go_assert(len > 0 && ele_size > 0);
3047 if (!this->should_repeat(ele_size / ptrsize, len))
3049 // Cheaper to just emit the bits.
3050 int64_t eoffset = 0;
3051 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3052 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3054 else
3056 go_assert((offset % ptrsize) == 0);
3057 go_assert((ele_size % ptrsize) == 0);
3058 this->set_from(gogo, element_type, ptrsize, offset);
3059 this->zero_until((offset + ele_size) / ptrsize);
3060 this->repeat(ele_size / ptrsize, len - 1);
3063 break;
3068 // Emit a 1 into the bit stream of a GC program at the given bit index.
3070 void
3071 GCProg::ptr(int64_t index)
3073 go_assert(index >= this->index_);
3074 this->zero_until(index);
3075 this->lit(1);
3078 // Return whether it is worthwhile to use a repeat to describe c
3079 // elements of n bits each, compared to just emitting c copies of the
3080 // n-bit description.
3082 bool
3083 GCProg::should_repeat(int64_t n, int64_t c)
3085 // Repeat if there is more than 1 item and if the total data doesn't
3086 // fit into four bytes.
3087 return c > 1 && c * n > 4 * 8;
3090 // Emit an instruction to repeat the description of the last n words c
3091 // times (including the initial description, so c + 1 times in total).
3093 void
3094 GCProg::repeat(int64_t n, int64_t c)
3096 if (n == 0 || c == 0)
3097 return;
3098 this->flushlit();
3099 if (n < 128)
3100 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3101 else
3103 this->byte(0x80);
3104 this->varint(n);
3106 this->varint(c);
3107 this->index_ += n * c;
3110 // Add zeros to the bit stream up to the given index.
3112 void
3113 GCProg::zero_until(int64_t index)
3115 go_assert(index >= this->index_);
3116 int64_t skip = index - this->index_;
3117 if (skip == 0)
3118 return;
3119 if (skip < 4 * 8)
3121 for (int64_t i = 0; i < skip; ++i)
3122 this->lit(0);
3123 return;
3125 this->lit(0);
3126 this->flushlit();
3127 this->repeat(1, skip - 1);
3130 // Add a single literal bit to the program.
3132 void
3133 GCProg::lit(unsigned char x)
3135 if (this->nb_ == GCProg::max_literal)
3136 this->flushlit();
3137 this->b_[this->nb_] = x;
3138 ++this->nb_;
3139 ++this->index_;
3142 // Emit the varint encoding of x.
3144 void
3145 GCProg::varint(int64_t x)
3147 go_assert(x >= 0);
3148 while (x >= 0x80)
3150 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3151 x >>= 7;
3153 this->byte(static_cast<unsigned char>(x & 0x7f));
3156 // Flush any pending literal bits.
3158 void
3159 GCProg::flushlit()
3161 if (this->nb_ == 0)
3162 return;
3163 this->byte(static_cast<unsigned char>(this->nb_));
3164 unsigned char bits = 0;
3165 for (int i = 0; i < this->nb_; ++i)
3167 bits |= this->b_[i] << (i % 8);
3168 if ((i + 1) % 8 == 0)
3170 this->byte(bits);
3171 bits = 0;
3174 if (this->nb_ % 8 != 0)
3175 this->byte(bits);
3176 this->nb_ = 0;
3179 // Mark the end of a GC program.
3181 void
3182 GCProg::end()
3184 this->flushlit();
3185 this->byte(0);
3188 // Return an Expression for the bytes in a GC program.
3190 Expression*
3191 GCProg::constructor(Gogo* gogo) const
3193 Location bloc = Linemap::predeclared_location();
3195 // The first four bytes are the length of the program in target byte
3196 // order. Build a struct whose first type is uint32 to make this
3197 // work.
3199 Type* uint32_type = Type::lookup_integer_type("uint32");
3201 Type* byte_type = gogo->lookup_global("byte")->type_value();
3202 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3203 bloc);
3204 Array_type* at = Type::make_array_type(byte_type, len);
3206 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3207 "bytes", at);
3209 Expression_list* vals = new Expression_list();
3210 vals->reserve(this->bytes_.size());
3211 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3212 p != this->bytes_.end();
3213 ++p)
3214 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3215 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3217 vals = new Expression_list();
3218 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3219 bloc));
3220 vals->push_back(bytes);
3222 return Expression::make_struct_composite_literal(st, vals, bloc);
3225 // Return a composite literal for the garbage collection program for
3226 // this type. This is only used for types that are too large to use a
3227 // ptrmask.
3229 Expression*
3230 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3232 Location bloc = Linemap::predeclared_location();
3234 GCProg prog;
3235 prog.set_from(gogo, this, ptrsize, 0);
3236 int64_t offset = prog.bit_index() * ptrsize;
3237 prog.end();
3239 int64_t type_size;
3240 if (!this->backend_type_size(gogo, &type_size))
3242 go_assert(saw_errors());
3243 return Expression::make_error(bloc);
3246 go_assert(offset >= ptrdata && offset <= type_size);
3248 return prog.constructor(gogo);
3251 // Return a composite literal for the uncommon type information for
3252 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3253 // struct. If name is not NULL, it is the name of the type. If
3254 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3255 // is true if only value methods should be included. At least one of
3256 // NAME and METHODS must not be NULL.
3258 Expression*
3259 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3260 Named_type* name, const Methods* methods,
3261 bool only_value_methods) const
3263 Location bloc = Linemap::predeclared_location();
3265 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3267 Expression_list* vals = new Expression_list();
3268 vals->reserve(3);
3270 Struct_field_list::const_iterator p = fields->begin();
3271 go_assert(p->is_field_name("name"));
3273 ++p;
3274 go_assert(p->is_field_name("pkgPath"));
3276 if (name == NULL)
3278 vals->push_back(Expression::make_nil(bloc));
3279 vals->push_back(Expression::make_nil(bloc));
3281 else
3283 Named_object* no = name->named_object();
3284 std::string n = Gogo::unpack_hidden_name(no->name());
3285 Expression* s = Expression::make_string(n, bloc);
3286 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3288 if (name->is_builtin())
3289 vals->push_back(Expression::make_nil(bloc));
3290 else
3292 const Package* package = no->package();
3293 const std::string& pkgpath(package == NULL
3294 ? gogo->pkgpath()
3295 : package->pkgpath());
3296 s = Expression::make_string(pkgpath, bloc);
3297 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3301 ++p;
3302 go_assert(p->is_field_name("methods"));
3303 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3304 only_value_methods));
3306 ++p;
3307 go_assert(p == fields->end());
3309 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3310 vals, bloc);
3311 return Expression::make_unary(OPERATOR_AND, r, bloc);
3314 // Sort methods by name.
3316 class Sort_methods
3318 public:
3319 bool
3320 operator()(const std::pair<std::string, const Method*>& m1,
3321 const std::pair<std::string, const Method*>& m2) const
3323 return (Gogo::unpack_hidden_name(m1.first)
3324 < Gogo::unpack_hidden_name(m2.first));
3328 // Return a composite literal for the type method table for this type.
3329 // METHODS_TYPE is the type of the table, and is a slice type.
3330 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3331 // then only value methods are used.
3333 Expression*
3334 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3335 const Methods* methods,
3336 bool only_value_methods) const
3338 Location bloc = Linemap::predeclared_location();
3340 std::vector<std::pair<std::string, const Method*> > smethods;
3341 if (methods != NULL)
3343 smethods.reserve(methods->count());
3344 for (Methods::const_iterator p = methods->begin();
3345 p != methods->end();
3346 ++p)
3348 if (p->second->is_ambiguous())
3349 continue;
3350 if (only_value_methods && !p->second->is_value_method())
3351 continue;
3353 // This is where we implement the magic //go:nointerface
3354 // comment. If we saw that comment, we don't add this
3355 // method to the type descriptor.
3356 if (p->second->nointerface())
3357 continue;
3359 smethods.push_back(std::make_pair(p->first, p->second));
3363 if (smethods.empty())
3364 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3366 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3368 Type* method_type = methods_type->array_type()->element_type();
3370 Expression_list* vals = new Expression_list();
3371 vals->reserve(smethods.size());
3372 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3373 = smethods.begin();
3374 p != smethods.end();
3375 ++p)
3376 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3377 p->second, only_value_methods));
3379 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3382 // Return a composite literal for a single method. METHOD_TYPE is the
3383 // type of the entry. METHOD_NAME is the name of the method and M is
3384 // the method information.
3386 Expression*
3387 Type::method_constructor(Gogo*, Type* method_type,
3388 const std::string& method_name,
3389 const Method* m,
3390 bool only_value_methods) const
3392 Location bloc = Linemap::predeclared_location();
3394 const Struct_field_list* fields = method_type->struct_type()->fields();
3396 Expression_list* vals = new Expression_list();
3397 vals->reserve(5);
3399 Struct_field_list::const_iterator p = fields->begin();
3400 go_assert(p->is_field_name("name"));
3401 const std::string n = Gogo::unpack_hidden_name(method_name);
3402 Expression* s = Expression::make_string(n, bloc);
3403 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3405 ++p;
3406 go_assert(p->is_field_name("pkgPath"));
3407 if (!Gogo::is_hidden_name(method_name))
3408 vals->push_back(Expression::make_nil(bloc));
3409 else
3411 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3412 bloc);
3413 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3416 Named_object* no = (m->needs_stub_method()
3417 ? m->stub_object()
3418 : m->named_object());
3420 Function_type* mtype;
3421 if (no->is_function())
3422 mtype = no->func_value()->type();
3423 else
3424 mtype = no->func_declaration_value()->type();
3425 go_assert(mtype->is_method());
3426 Type* nonmethod_type = mtype->copy_without_receiver();
3428 ++p;
3429 go_assert(p->is_field_name("mtyp"));
3430 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3432 ++p;
3433 go_assert(p->is_field_name("typ"));
3434 bool want_pointer_receiver = !only_value_methods && m->is_value_method();
3435 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3436 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3438 ++p;
3439 go_assert(p->is_field_name("tfn"));
3440 vals->push_back(Expression::make_func_code_reference(no, bloc));
3442 ++p;
3443 go_assert(p == fields->end());
3445 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3448 // Return a composite literal for the type descriptor of a plain type.
3449 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3450 // NULL, it is the name to use as well as the list of methods.
3452 Expression*
3453 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3454 Named_type* name)
3456 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3457 name, NULL, true);
3460 // Return the type reflection string for this type.
3462 std::string
3463 Type::reflection(Gogo* gogo) const
3465 std::string ret;
3467 // The do_reflection virtual function should set RET to the
3468 // reflection string.
3469 this->do_reflection(gogo, &ret);
3471 return ret;
3474 // Return whether the backend size of the type is known.
3476 bool
3477 Type::is_backend_type_size_known(Gogo* gogo)
3479 switch (this->classification_)
3481 case TYPE_ERROR:
3482 case TYPE_VOID:
3483 case TYPE_BOOLEAN:
3484 case TYPE_INTEGER:
3485 case TYPE_FLOAT:
3486 case TYPE_COMPLEX:
3487 case TYPE_STRING:
3488 case TYPE_FUNCTION:
3489 case TYPE_POINTER:
3490 case TYPE_NIL:
3491 case TYPE_MAP:
3492 case TYPE_CHANNEL:
3493 case TYPE_INTERFACE:
3494 return true;
3496 case TYPE_STRUCT:
3498 const Struct_field_list* fields = this->struct_type()->fields();
3499 for (Struct_field_list::const_iterator pf = fields->begin();
3500 pf != fields->end();
3501 ++pf)
3502 if (!pf->type()->is_backend_type_size_known(gogo))
3503 return false;
3504 return true;
3507 case TYPE_ARRAY:
3509 const Array_type* at = this->array_type();
3510 if (at->length() == NULL)
3511 return true;
3512 else
3514 Numeric_constant nc;
3515 if (!at->length()->numeric_constant_value(&nc))
3516 return false;
3517 mpz_t ival;
3518 if (!nc.to_int(&ival))
3519 return false;
3520 mpz_clear(ival);
3521 return at->element_type()->is_backend_type_size_known(gogo);
3525 case TYPE_NAMED:
3526 this->named_type()->convert(gogo);
3527 return this->named_type()->is_named_backend_type_size_known();
3529 case TYPE_FORWARD:
3531 Forward_declaration_type* fdt = this->forward_declaration_type();
3532 return fdt->real_type()->is_backend_type_size_known(gogo);
3535 case TYPE_SINK:
3536 case TYPE_CALL_MULTIPLE_RESULT:
3537 go_unreachable();
3539 default:
3540 go_unreachable();
3544 // If the size of the type can be determined, set *PSIZE to the size
3545 // in bytes and return true. Otherwise, return false. This queries
3546 // the backend.
3548 bool
3549 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3551 if (!this->is_backend_type_size_known(gogo))
3552 return false;
3553 if (this->is_error_type())
3554 return false;
3555 Btype* bt = this->get_backend_placeholder(gogo);
3556 *psize = gogo->backend()->type_size(bt);
3557 if (*psize == -1)
3559 if (this->named_type() != NULL)
3560 go_error_at(this->named_type()->location(),
3561 "type %s larger than address space",
3562 Gogo::message_name(this->named_type()->name()).c_str());
3563 else
3564 go_error_at(Linemap::unknown_location(),
3565 "type %s larger than address space",
3566 this->reflection(gogo).c_str());
3568 // Make this an error type to avoid knock-on errors.
3569 this->classification_ = TYPE_ERROR;
3570 return false;
3572 return true;
3575 // If the alignment of the type can be determined, set *PALIGN to
3576 // the alignment in bytes and return true. Otherwise, return false.
3578 bool
3579 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3581 if (!this->is_backend_type_size_known(gogo))
3582 return false;
3583 Btype* bt = this->get_backend_placeholder(gogo);
3584 *palign = gogo->backend()->type_alignment(bt);
3585 return true;
3588 // Like backend_type_align, but return the alignment when used as a
3589 // field.
3591 bool
3592 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3594 if (!this->is_backend_type_size_known(gogo))
3595 return false;
3596 Btype* bt = this->get_backend_placeholder(gogo);
3597 *palign = gogo->backend()->type_field_alignment(bt);
3598 return true;
3601 // Get the ptrdata value for a type. This is the size of the prefix
3602 // of the type that contains all pointers. Store the ptrdata in
3603 // *PPTRDATA and return whether we found it.
3605 bool
3606 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3608 *pptrdata = 0;
3610 if (!this->has_pointer())
3611 return true;
3613 if (!this->is_backend_type_size_known(gogo))
3614 return false;
3616 switch (this->classification_)
3618 case TYPE_ERROR:
3619 return true;
3621 case TYPE_FUNCTION:
3622 case TYPE_POINTER:
3623 case TYPE_MAP:
3624 case TYPE_CHANNEL:
3625 // These types are nothing but a pointer.
3626 return this->backend_type_size(gogo, pptrdata);
3628 case TYPE_INTERFACE:
3629 // An interface is a struct of two pointers.
3630 return this->backend_type_size(gogo, pptrdata);
3632 case TYPE_STRING:
3634 // A string is a struct whose first field is a pointer, and
3635 // whose second field is not.
3636 Type* uint8_type = Type::lookup_integer_type("uint8");
3637 Type* ptr = Type::make_pointer_type(uint8_type);
3638 return ptr->backend_type_size(gogo, pptrdata);
3641 case TYPE_NAMED:
3642 case TYPE_FORWARD:
3643 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3645 case TYPE_STRUCT:
3647 const Struct_field_list* fields = this->struct_type()->fields();
3648 int64_t offset = 0;
3649 const Struct_field *ptr = NULL;
3650 int64_t ptr_offset = 0;
3651 for (Struct_field_list::const_iterator pf = fields->begin();
3652 pf != fields->end();
3653 ++pf)
3655 int64_t field_align;
3656 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3657 return false;
3658 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3660 if (pf->type()->has_pointer())
3662 ptr = &*pf;
3663 ptr_offset = offset;
3666 int64_t field_size;
3667 if (!pf->type()->backend_type_size(gogo, &field_size))
3668 return false;
3669 offset += field_size;
3672 if (ptr != NULL)
3674 int64_t ptr_ptrdata;
3675 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3676 return false;
3677 *pptrdata = ptr_offset + ptr_ptrdata;
3679 return true;
3682 case TYPE_ARRAY:
3683 if (this->is_slice_type())
3685 // A slice is a struct whose first field is a pointer, and
3686 // whose remaining fields are not.
3687 Type* element_type = this->array_type()->element_type();
3688 Type* ptr = Type::make_pointer_type(element_type);
3689 return ptr->backend_type_size(gogo, pptrdata);
3691 else
3693 Numeric_constant nc;
3694 if (!this->array_type()->length()->numeric_constant_value(&nc))
3695 return false;
3696 int64_t len;
3697 if (!nc.to_memory_size(&len))
3698 return false;
3700 Type* element_type = this->array_type()->element_type();
3701 int64_t ele_size;
3702 int64_t ele_ptrdata;
3703 if (!element_type->backend_type_size(gogo, &ele_size)
3704 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3705 return false;
3706 go_assert(ele_size > 0 && ele_ptrdata > 0);
3708 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3709 return true;
3712 default:
3713 case TYPE_VOID:
3714 case TYPE_BOOLEAN:
3715 case TYPE_INTEGER:
3716 case TYPE_FLOAT:
3717 case TYPE_COMPLEX:
3718 case TYPE_SINK:
3719 case TYPE_NIL:
3720 case TYPE_CALL_MULTIPLE_RESULT:
3721 go_unreachable();
3725 // Get the ptrdata value to store in a type descriptor. This is
3726 // normally the same as backend_type_ptrdata, but for a type that is
3727 // large enough to use a gcprog we may need to store a different value
3728 // if it ends with an array. If the gcprog uses a repeat descriptor
3729 // for the array, and if the array element ends with non-pointer data,
3730 // then the gcprog will produce a value that describes the complete
3731 // array where the backend ptrdata will omit the non-pointer elements
3732 // of the final array element. This is a subtle difference but the
3733 // run time code checks it to verify that it has expanded a gcprog as
3734 // expected.
3736 bool
3737 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3739 int64_t backend_ptrdata;
3740 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
3741 return false;
3743 int64_t ptrsize;
3744 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
3746 *pptrdata = backend_ptrdata;
3747 return true;
3750 GCProg prog;
3751 prog.set_from(gogo, this, ptrsize, 0);
3752 int64_t offset = prog.bit_index() * ptrsize;
3754 go_assert(offset >= backend_ptrdata);
3755 *pptrdata = offset;
3756 return true;
3759 // Default function to export a type.
3761 void
3762 Type::do_export(Export*) const
3764 go_unreachable();
3767 // Import a type.
3769 Type*
3770 Type::import_type(Import* imp)
3772 if (imp->match_c_string("("))
3773 return Function_type::do_import(imp);
3774 else if (imp->match_c_string("*"))
3775 return Pointer_type::do_import(imp);
3776 else if (imp->match_c_string("struct "))
3777 return Struct_type::do_import(imp);
3778 else if (imp->match_c_string("["))
3779 return Array_type::do_import(imp);
3780 else if (imp->match_c_string("map "))
3781 return Map_type::do_import(imp);
3782 else if (imp->match_c_string("chan "))
3783 return Channel_type::do_import(imp);
3784 else if (imp->match_c_string("interface"))
3785 return Interface_type::do_import(imp);
3786 else
3788 go_error_at(imp->location(), "import error: expected type");
3789 return Type::make_error_type();
3793 // Class Error_type.
3795 // Return the backend representation of an Error type.
3797 Btype*
3798 Error_type::do_get_backend(Gogo* gogo)
3800 return gogo->backend()->error_type();
3803 // Return an expression for the type descriptor for an error type.
3806 Expression*
3807 Error_type::do_type_descriptor(Gogo*, Named_type*)
3809 return Expression::make_error(Linemap::predeclared_location());
3812 // We should not be asked for the reflection string for an error type.
3814 void
3815 Error_type::do_reflection(Gogo*, std::string*) const
3817 go_assert(saw_errors());
3820 Type*
3821 Type::make_error_type()
3823 static Error_type singleton_error_type;
3824 return &singleton_error_type;
3827 // Class Void_type.
3829 // Get the backend representation of a void type.
3831 Btype*
3832 Void_type::do_get_backend(Gogo* gogo)
3834 return gogo->backend()->void_type();
3837 Type*
3838 Type::make_void_type()
3840 static Void_type singleton_void_type;
3841 return &singleton_void_type;
3844 // Class Boolean_type.
3846 // Return the backend representation of the boolean type.
3848 Btype*
3849 Boolean_type::do_get_backend(Gogo* gogo)
3851 return gogo->backend()->bool_type();
3854 // Make the type descriptor.
3856 Expression*
3857 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
3859 if (name != NULL)
3860 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
3861 else
3863 Named_object* no = gogo->lookup_global("bool");
3864 go_assert(no != NULL);
3865 return Type::type_descriptor(gogo, no->type_value());
3869 Type*
3870 Type::make_boolean_type()
3872 static Boolean_type boolean_type;
3873 return &boolean_type;
3876 // The named type "bool".
3878 static Named_type* named_bool_type;
3880 // Get the named type "bool".
3882 Named_type*
3883 Type::lookup_bool_type()
3885 return named_bool_type;
3888 // Make the named type "bool".
3890 Named_type*
3891 Type::make_named_bool_type()
3893 Type* bool_type = Type::make_boolean_type();
3894 Named_object* named_object =
3895 Named_object::make_type("bool", NULL, bool_type,
3896 Linemap::predeclared_location());
3897 Named_type* named_type = named_object->type_value();
3898 named_bool_type = named_type;
3899 return named_type;
3902 // Class Integer_type.
3904 Integer_type::Named_integer_types Integer_type::named_integer_types;
3906 // Create a new integer type. Non-abstract integer types always have
3907 // names.
3909 Named_type*
3910 Integer_type::create_integer_type(const char* name, bool is_unsigned,
3911 int bits, int runtime_type_kind)
3913 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
3914 runtime_type_kind);
3915 std::string sname(name);
3916 Named_object* named_object =
3917 Named_object::make_type(sname, NULL, integer_type,
3918 Linemap::predeclared_location());
3919 Named_type* named_type = named_object->type_value();
3920 std::pair<Named_integer_types::iterator, bool> ins =
3921 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
3922 go_assert(ins.second);
3923 return named_type;
3926 // Look up an existing integer type.
3928 Named_type*
3929 Integer_type::lookup_integer_type(const char* name)
3931 Named_integer_types::const_iterator p =
3932 Integer_type::named_integer_types.find(name);
3933 go_assert(p != Integer_type::named_integer_types.end());
3934 return p->second;
3937 // Create a new abstract integer type.
3939 Integer_type*
3940 Integer_type::create_abstract_integer_type()
3942 static Integer_type* abstract_type;
3943 if (abstract_type == NULL)
3945 Type* int_type = Type::lookup_integer_type("int");
3946 abstract_type = new Integer_type(true, false,
3947 int_type->integer_type()->bits(),
3948 RUNTIME_TYPE_KIND_INT);
3950 return abstract_type;
3953 // Create a new abstract character type.
3955 Integer_type*
3956 Integer_type::create_abstract_character_type()
3958 static Integer_type* abstract_type;
3959 if (abstract_type == NULL)
3961 abstract_type = new Integer_type(true, false, 32,
3962 RUNTIME_TYPE_KIND_INT32);
3963 abstract_type->set_is_rune();
3965 return abstract_type;
3968 // Integer type compatibility.
3970 bool
3971 Integer_type::is_identical(const Integer_type* t) const
3973 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
3974 return false;
3975 return this->is_abstract_ == t->is_abstract_;
3978 // Hash code.
3980 unsigned int
3981 Integer_type::do_hash_for_method(Gogo*) const
3983 return ((this->bits_ << 4)
3984 + ((this->is_unsigned_ ? 1 : 0) << 8)
3985 + ((this->is_abstract_ ? 1 : 0) << 9));
3988 // Convert an Integer_type to the backend representation.
3990 Btype*
3991 Integer_type::do_get_backend(Gogo* gogo)
3993 if (this->is_abstract_)
3995 go_assert(saw_errors());
3996 return gogo->backend()->error_type();
3998 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4001 // The type descriptor for an integer type. Integer types are always
4002 // named.
4004 Expression*
4005 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4007 go_assert(name != NULL || saw_errors());
4008 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4011 // We should not be asked for the reflection string of a basic type.
4013 void
4014 Integer_type::do_reflection(Gogo*, std::string*) const
4016 go_assert(saw_errors());
4019 // Make an integer type.
4021 Named_type*
4022 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4023 int runtime_type_kind)
4025 return Integer_type::create_integer_type(name, is_unsigned, bits,
4026 runtime_type_kind);
4029 // Make an abstract integer type.
4031 Integer_type*
4032 Type::make_abstract_integer_type()
4034 return Integer_type::create_abstract_integer_type();
4037 // Make an abstract character type.
4039 Integer_type*
4040 Type::make_abstract_character_type()
4042 return Integer_type::create_abstract_character_type();
4045 // Look up an integer type.
4047 Named_type*
4048 Type::lookup_integer_type(const char* name)
4050 return Integer_type::lookup_integer_type(name);
4053 // Class Float_type.
4055 Float_type::Named_float_types Float_type::named_float_types;
4057 // Create a new float type. Non-abstract float types always have
4058 // names.
4060 Named_type*
4061 Float_type::create_float_type(const char* name, int bits,
4062 int runtime_type_kind)
4064 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4065 std::string sname(name);
4066 Named_object* named_object =
4067 Named_object::make_type(sname, NULL, float_type,
4068 Linemap::predeclared_location());
4069 Named_type* named_type = named_object->type_value();
4070 std::pair<Named_float_types::iterator, bool> ins =
4071 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4072 go_assert(ins.second);
4073 return named_type;
4076 // Look up an existing float type.
4078 Named_type*
4079 Float_type::lookup_float_type(const char* name)
4081 Named_float_types::const_iterator p =
4082 Float_type::named_float_types.find(name);
4083 go_assert(p != Float_type::named_float_types.end());
4084 return p->second;
4087 // Create a new abstract float type.
4089 Float_type*
4090 Float_type::create_abstract_float_type()
4092 static Float_type* abstract_type;
4093 if (abstract_type == NULL)
4094 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4095 return abstract_type;
4098 // Whether this type is identical with T.
4100 bool
4101 Float_type::is_identical(const Float_type* t) const
4103 if (this->bits_ != t->bits_)
4104 return false;
4105 return this->is_abstract_ == t->is_abstract_;
4108 // Hash code.
4110 unsigned int
4111 Float_type::do_hash_for_method(Gogo*) const
4113 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4116 // Convert to the backend representation.
4118 Btype*
4119 Float_type::do_get_backend(Gogo* gogo)
4121 return gogo->backend()->float_type(this->bits_);
4124 // The type descriptor for a float type. Float types are always named.
4126 Expression*
4127 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4129 go_assert(name != NULL || saw_errors());
4130 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4133 // We should not be asked for the reflection string of a basic type.
4135 void
4136 Float_type::do_reflection(Gogo*, std::string*) const
4138 go_assert(saw_errors());
4141 // Make a floating point type.
4143 Named_type*
4144 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4146 return Float_type::create_float_type(name, bits, runtime_type_kind);
4149 // Make an abstract float type.
4151 Float_type*
4152 Type::make_abstract_float_type()
4154 return Float_type::create_abstract_float_type();
4157 // Look up a float type.
4159 Named_type*
4160 Type::lookup_float_type(const char* name)
4162 return Float_type::lookup_float_type(name);
4165 // Class Complex_type.
4167 Complex_type::Named_complex_types Complex_type::named_complex_types;
4169 // Create a new complex type. Non-abstract complex types always have
4170 // names.
4172 Named_type*
4173 Complex_type::create_complex_type(const char* name, int bits,
4174 int runtime_type_kind)
4176 Complex_type* complex_type = new Complex_type(false, bits,
4177 runtime_type_kind);
4178 std::string sname(name);
4179 Named_object* named_object =
4180 Named_object::make_type(sname, NULL, complex_type,
4181 Linemap::predeclared_location());
4182 Named_type* named_type = named_object->type_value();
4183 std::pair<Named_complex_types::iterator, bool> ins =
4184 Complex_type::named_complex_types.insert(std::make_pair(sname,
4185 named_type));
4186 go_assert(ins.second);
4187 return named_type;
4190 // Look up an existing complex type.
4192 Named_type*
4193 Complex_type::lookup_complex_type(const char* name)
4195 Named_complex_types::const_iterator p =
4196 Complex_type::named_complex_types.find(name);
4197 go_assert(p != Complex_type::named_complex_types.end());
4198 return p->second;
4201 // Create a new abstract complex type.
4203 Complex_type*
4204 Complex_type::create_abstract_complex_type()
4206 static Complex_type* abstract_type;
4207 if (abstract_type == NULL)
4208 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4209 return abstract_type;
4212 // Whether this type is identical with T.
4214 bool
4215 Complex_type::is_identical(const Complex_type *t) const
4217 if (this->bits_ != t->bits_)
4218 return false;
4219 return this->is_abstract_ == t->is_abstract_;
4222 // Hash code.
4224 unsigned int
4225 Complex_type::do_hash_for_method(Gogo*) const
4227 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4230 // Convert to the backend representation.
4232 Btype*
4233 Complex_type::do_get_backend(Gogo* gogo)
4235 return gogo->backend()->complex_type(this->bits_);
4238 // The type descriptor for a complex type. Complex types are always
4239 // named.
4241 Expression*
4242 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4244 go_assert(name != NULL || saw_errors());
4245 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4248 // We should not be asked for the reflection string of a basic type.
4250 void
4251 Complex_type::do_reflection(Gogo*, std::string*) const
4253 go_assert(saw_errors());
4256 // Make a complex type.
4258 Named_type*
4259 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4261 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4264 // Make an abstract complex type.
4266 Complex_type*
4267 Type::make_abstract_complex_type()
4269 return Complex_type::create_abstract_complex_type();
4272 // Look up a complex type.
4274 Named_type*
4275 Type::lookup_complex_type(const char* name)
4277 return Complex_type::lookup_complex_type(name);
4280 // Class String_type.
4282 // Convert String_type to the backend representation. A string is a
4283 // struct with two fields: a pointer to the characters and a length.
4285 Btype*
4286 String_type::do_get_backend(Gogo* gogo)
4288 static Btype* backend_string_type;
4289 if (backend_string_type == NULL)
4291 std::vector<Backend::Btyped_identifier> fields(2);
4293 Type* b = gogo->lookup_global("byte")->type_value();
4294 Type* pb = Type::make_pointer_type(b);
4296 // We aren't going to get back to this field to finish the
4297 // backend representation, so force it to be finished now.
4298 if (!gogo->named_types_are_converted())
4300 Btype* bt = pb->get_backend_placeholder(gogo);
4301 pb->finish_backend(gogo, bt);
4304 fields[0].name = "__data";
4305 fields[0].btype = pb->get_backend(gogo);
4306 fields[0].location = Linemap::predeclared_location();
4308 Type* int_type = Type::lookup_integer_type("int");
4309 fields[1].name = "__length";
4310 fields[1].btype = int_type->get_backend(gogo);
4311 fields[1].location = fields[0].location;
4313 backend_string_type = gogo->backend()->struct_type(fields);
4315 return backend_string_type;
4318 // The type descriptor for the string type.
4320 Expression*
4321 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4323 if (name != NULL)
4324 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4325 else
4327 Named_object* no = gogo->lookup_global("string");
4328 go_assert(no != NULL);
4329 return Type::type_descriptor(gogo, no->type_value());
4333 // We should not be asked for the reflection string of a basic type.
4335 void
4336 String_type::do_reflection(Gogo*, std::string* ret) const
4338 ret->append("string");
4341 // Make a string type.
4343 Type*
4344 Type::make_string_type()
4346 static String_type string_type;
4347 return &string_type;
4350 // The named type "string".
4352 static Named_type* named_string_type;
4354 // Get the named type "string".
4356 Named_type*
4357 Type::lookup_string_type()
4359 return named_string_type;
4362 // Make the named type string.
4364 Named_type*
4365 Type::make_named_string_type()
4367 Type* string_type = Type::make_string_type();
4368 Named_object* named_object =
4369 Named_object::make_type("string", NULL, string_type,
4370 Linemap::predeclared_location());
4371 Named_type* named_type = named_object->type_value();
4372 named_string_type = named_type;
4373 return named_type;
4376 // The sink type. This is the type of the blank identifier _. Any
4377 // type may be assigned to it.
4379 class Sink_type : public Type
4381 public:
4382 Sink_type()
4383 : Type(TYPE_SINK)
4386 protected:
4387 bool
4388 do_compare_is_identity(Gogo*)
4389 { return false; }
4391 Btype*
4392 do_get_backend(Gogo*)
4393 { go_unreachable(); }
4395 Expression*
4396 do_type_descriptor(Gogo*, Named_type*)
4397 { go_unreachable(); }
4399 void
4400 do_reflection(Gogo*, std::string*) const
4401 { go_unreachable(); }
4403 void
4404 do_mangled_name(Gogo*, std::string*) const
4405 { go_unreachable(); }
4408 // Make the sink type.
4410 Type*
4411 Type::make_sink_type()
4413 static Sink_type sink_type;
4414 return &sink_type;
4417 // Class Function_type.
4419 // Traversal.
4422 Function_type::do_traverse(Traverse* traverse)
4424 if (this->receiver_ != NULL
4425 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4426 return TRAVERSE_EXIT;
4427 if (this->parameters_ != NULL
4428 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4429 return TRAVERSE_EXIT;
4430 if (this->results_ != NULL
4431 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4432 return TRAVERSE_EXIT;
4433 return TRAVERSE_CONTINUE;
4436 // Returns whether T is a valid redeclaration of this type. If this
4437 // returns false, and REASON is not NULL, *REASON may be set to a
4438 // brief explanation of why it returned false.
4440 bool
4441 Function_type::is_valid_redeclaration(const Function_type* t,
4442 std::string* reason) const
4444 if (!this->is_identical(t, false, COMPARE_TAGS, true, reason))
4445 return false;
4447 // A redeclaration of a function is required to use the same names
4448 // for the receiver and parameters.
4449 if (this->receiver() != NULL
4450 && this->receiver()->name() != t->receiver()->name())
4452 if (reason != NULL)
4453 *reason = "receiver name changed";
4454 return false;
4457 const Typed_identifier_list* parms1 = this->parameters();
4458 const Typed_identifier_list* parms2 = t->parameters();
4459 if (parms1 != NULL)
4461 Typed_identifier_list::const_iterator p1 = parms1->begin();
4462 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4463 p2 != parms2->end();
4464 ++p2, ++p1)
4466 if (p1->name() != p2->name())
4468 if (reason != NULL)
4469 *reason = "parameter name changed";
4470 return false;
4473 // This is called at parse time, so we may have unknown
4474 // types.
4475 Type* t1 = p1->type()->forwarded();
4476 Type* t2 = p2->type()->forwarded();
4477 if (t1 != t2
4478 && t1->forward_declaration_type() != NULL
4479 && (t2->forward_declaration_type() == NULL
4480 || (t1->forward_declaration_type()->named_object()
4481 != t2->forward_declaration_type()->named_object())))
4482 return false;
4486 const Typed_identifier_list* results1 = this->results();
4487 const Typed_identifier_list* results2 = t->results();
4488 if (results1 != NULL)
4490 Typed_identifier_list::const_iterator res1 = results1->begin();
4491 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4492 res2 != results2->end();
4493 ++res2, ++res1)
4495 if (res1->name() != res2->name())
4497 if (reason != NULL)
4498 *reason = "result name changed";
4499 return false;
4502 // This is called at parse time, so we may have unknown
4503 // types.
4504 Type* t1 = res1->type()->forwarded();
4505 Type* t2 = res2->type()->forwarded();
4506 if (t1 != t2
4507 && t1->forward_declaration_type() != NULL
4508 && (t2->forward_declaration_type() == NULL
4509 || (t1->forward_declaration_type()->named_object()
4510 != t2->forward_declaration_type()->named_object())))
4511 return false;
4515 return true;
4518 // Check whether T is the same as this type.
4520 bool
4521 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4522 Cmp_tags cmp_tags, bool errors_are_identical,
4523 std::string* reason) const
4525 if (this->is_backend_function_type() != t->is_backend_function_type())
4526 return false;
4528 if (!ignore_receiver)
4530 const Typed_identifier* r1 = this->receiver();
4531 const Typed_identifier* r2 = t->receiver();
4532 if ((r1 != NULL) != (r2 != NULL))
4534 if (reason != NULL)
4535 *reason = _("different receiver types");
4536 return false;
4538 if (r1 != NULL)
4540 if (!Type::are_identical_cmp_tags(r1->type(), r2->type(), cmp_tags,
4541 errors_are_identical, reason))
4543 if (reason != NULL && !reason->empty())
4544 *reason = "receiver: " + *reason;
4545 return false;
4550 const Typed_identifier_list* parms1 = this->parameters();
4551 if (parms1 != NULL && parms1->empty())
4552 parms1 = NULL;
4553 const Typed_identifier_list* parms2 = t->parameters();
4554 if (parms2 != NULL && parms2->empty())
4555 parms2 = NULL;
4556 if ((parms1 != NULL) != (parms2 != NULL))
4558 if (reason != NULL)
4559 *reason = _("different number of parameters");
4560 return false;
4562 if (parms1 != NULL)
4564 Typed_identifier_list::const_iterator p1 = parms1->begin();
4565 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4566 p2 != parms2->end();
4567 ++p2, ++p1)
4569 if (p1 == parms1->end())
4571 if (reason != NULL)
4572 *reason = _("different number of parameters");
4573 return false;
4576 if (!Type::are_identical_cmp_tags(p1->type(), p2->type(), cmp_tags,
4577 errors_are_identical, NULL))
4579 if (reason != NULL)
4580 *reason = _("different parameter types");
4581 return false;
4584 if (p1 != parms1->end())
4586 if (reason != NULL)
4587 *reason = _("different number of parameters");
4588 return false;
4592 if (this->is_varargs() != t->is_varargs())
4594 if (reason != NULL)
4595 *reason = _("different varargs");
4596 return false;
4599 const Typed_identifier_list* results1 = this->results();
4600 if (results1 != NULL && results1->empty())
4601 results1 = NULL;
4602 const Typed_identifier_list* results2 = t->results();
4603 if (results2 != NULL && results2->empty())
4604 results2 = NULL;
4605 if ((results1 != NULL) != (results2 != NULL))
4607 if (reason != NULL)
4608 *reason = _("different number of results");
4609 return false;
4611 if (results1 != NULL)
4613 Typed_identifier_list::const_iterator res1 = results1->begin();
4614 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4615 res2 != results2->end();
4616 ++res2, ++res1)
4618 if (res1 == results1->end())
4620 if (reason != NULL)
4621 *reason = _("different number of results");
4622 return false;
4625 if (!Type::are_identical_cmp_tags(res1->type(), res2->type(),
4626 cmp_tags, errors_are_identical,
4627 NULL))
4629 if (reason != NULL)
4630 *reason = _("different result types");
4631 return false;
4634 if (res1 != results1->end())
4636 if (reason != NULL)
4637 *reason = _("different number of results");
4638 return false;
4642 return true;
4645 // Hash code.
4647 unsigned int
4648 Function_type::do_hash_for_method(Gogo* gogo) const
4650 unsigned int ret = 0;
4651 // We ignore the receiver type for hash codes, because we need to
4652 // get the same hash code for a method in an interface and a method
4653 // declared for a type. The former will not have a receiver.
4654 if (this->parameters_ != NULL)
4656 int shift = 1;
4657 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4658 p != this->parameters_->end();
4659 ++p, ++shift)
4660 ret += p->type()->hash_for_method(gogo) << shift;
4662 if (this->results_ != NULL)
4664 int shift = 2;
4665 for (Typed_identifier_list::const_iterator p = this->results_->begin();
4666 p != this->results_->end();
4667 ++p, ++shift)
4668 ret += p->type()->hash_for_method(gogo) << shift;
4670 if (this->is_varargs_)
4671 ret += 1;
4672 ret <<= 4;
4673 return ret;
4676 // Hash result parameters.
4678 unsigned int
4679 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
4681 unsigned int hash = 0;
4682 for (Typed_identifier_list::const_iterator p = t->begin();
4683 p != t->end();
4684 ++p)
4686 hash <<= 2;
4687 hash = Type::hash_string(p->name(), hash);
4688 hash += p->type()->hash_for_method(NULL);
4690 return hash;
4693 // Compare result parameters so that can map identical result
4694 // parameters to a single struct type.
4696 bool
4697 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
4698 const Typed_identifier_list* b) const
4700 if (a->size() != b->size())
4701 return false;
4702 Typed_identifier_list::const_iterator pa = a->begin();
4703 for (Typed_identifier_list::const_iterator pb = b->begin();
4704 pb != b->end();
4705 ++pa, ++pb)
4707 if (pa->name() != pb->name()
4708 || !Type::are_identical(pa->type(), pb->type(), true, NULL))
4709 return false;
4711 return true;
4714 // Hash from results to a backend struct type.
4716 Function_type::Results_structs Function_type::results_structs;
4718 // Get the backend representation for a function type.
4720 Btype*
4721 Function_type::get_backend_fntype(Gogo* gogo)
4723 if (this->fnbtype_ == NULL)
4725 Backend::Btyped_identifier breceiver;
4726 if (this->receiver_ != NULL)
4728 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
4730 // We always pass the address of the receiver parameter, in
4731 // order to make interface calls work with unknown types.
4732 Type* rtype = this->receiver_->type();
4733 if (rtype->points_to() == NULL)
4734 rtype = Type::make_pointer_type(rtype);
4735 breceiver.btype = rtype->get_backend(gogo);
4736 breceiver.location = this->receiver_->location();
4739 std::vector<Backend::Btyped_identifier> bparameters;
4740 if (this->parameters_ != NULL)
4742 bparameters.resize(this->parameters_->size());
4743 size_t i = 0;
4744 for (Typed_identifier_list::const_iterator p =
4745 this->parameters_->begin(); p != this->parameters_->end();
4746 ++p, ++i)
4748 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
4749 bparameters[i].btype = p->type()->get_backend(gogo);
4750 bparameters[i].location = p->location();
4752 go_assert(i == bparameters.size());
4755 std::vector<Backend::Btyped_identifier> bresults;
4756 Btype* bresult_struct = NULL;
4757 if (this->results_ != NULL)
4759 bresults.resize(this->results_->size());
4760 size_t i = 0;
4761 for (Typed_identifier_list::const_iterator p =
4762 this->results_->begin();
4763 p != this->results_->end();
4764 ++p, ++i)
4766 bresults[i].name = Gogo::unpack_hidden_name(p->name());
4767 bresults[i].btype = p->type()->get_backend(gogo);
4768 bresults[i].location = p->location();
4770 go_assert(i == bresults.size());
4772 if (this->results_->size() > 1)
4774 // Use the same results struct for all functions that
4775 // return the same set of results. This is useful to
4776 // unify calls to interface methods with other calls.
4777 std::pair<Typed_identifier_list*, Btype*> val;
4778 val.first = this->results_;
4779 val.second = NULL;
4780 std::pair<Results_structs::iterator, bool> ins =
4781 Function_type::results_structs.insert(val);
4782 if (ins.second)
4784 // Build a new struct type.
4785 Struct_field_list* sfl = new Struct_field_list;
4786 for (Typed_identifier_list::const_iterator p =
4787 this->results_->begin();
4788 p != this->results_->end();
4789 ++p)
4791 Typed_identifier tid = *p;
4792 if (tid.name().empty())
4793 tid = Typed_identifier("UNNAMED", tid.type(),
4794 tid.location());
4795 sfl->push_back(Struct_field(tid));
4797 Struct_type* st = Type::make_struct_type(sfl,
4798 this->location());
4799 st->set_is_struct_incomparable();
4800 ins.first->second = st->get_backend(gogo);
4802 bresult_struct = ins.first->second;
4806 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
4807 bresults, bresult_struct,
4808 this->location());
4812 return this->fnbtype_;
4815 // Get the backend representation for a Go function type.
4817 Btype*
4818 Function_type::do_get_backend(Gogo* gogo)
4820 // When we do anything with a function value other than call it, it
4821 // is represented as a pointer to a struct whose first field is the
4822 // actual function. So that is what we return as the type of a Go
4823 // function.
4825 Location loc = this->location();
4826 Btype* struct_type =
4827 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
4828 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
4830 std::vector<Backend::Btyped_identifier> fields(1);
4831 fields[0].name = "code";
4832 fields[0].btype = this->get_backend_fntype(gogo);
4833 fields[0].location = loc;
4834 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
4835 return gogo->backend()->error_type();
4836 return ptr_struct_type;
4839 // The type of a function type descriptor.
4841 Type*
4842 Function_type::make_function_type_descriptor_type()
4844 static Type* ret;
4845 if (ret == NULL)
4847 Type* tdt = Type::make_type_descriptor_type();
4848 Type* ptdt = Type::make_type_descriptor_ptr_type();
4850 Type* bool_type = Type::lookup_bool_type();
4852 Type* slice_type = Type::make_array_type(ptdt, NULL);
4854 Struct_type* s = Type::make_builtin_struct_type(4,
4855 "", tdt,
4856 "dotdotdot", bool_type,
4857 "in", slice_type,
4858 "out", slice_type);
4860 ret = Type::make_builtin_named_type("FuncType", s);
4863 return ret;
4866 // The type descriptor for a function type.
4868 Expression*
4869 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4871 Location bloc = Linemap::predeclared_location();
4873 Type* ftdt = Function_type::make_function_type_descriptor_type();
4875 const Struct_field_list* fields = ftdt->struct_type()->fields();
4877 Expression_list* vals = new Expression_list();
4878 vals->reserve(4);
4880 Struct_field_list::const_iterator p = fields->begin();
4881 go_assert(p->is_field_name("_type"));
4882 vals->push_back(this->type_descriptor_constructor(gogo,
4883 RUNTIME_TYPE_KIND_FUNC,
4884 name, NULL, true));
4886 ++p;
4887 go_assert(p->is_field_name("dotdotdot"));
4888 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
4890 ++p;
4891 go_assert(p->is_field_name("in"));
4892 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
4893 this->parameters()));
4895 ++p;
4896 go_assert(p->is_field_name("out"));
4897 vals->push_back(this->type_descriptor_params(p->type(), NULL,
4898 this->results()));
4900 ++p;
4901 go_assert(p == fields->end());
4903 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
4906 // Return a composite literal for the parameters or results of a type
4907 // descriptor.
4909 Expression*
4910 Function_type::type_descriptor_params(Type* params_type,
4911 const Typed_identifier* receiver,
4912 const Typed_identifier_list* params)
4914 Location bloc = Linemap::predeclared_location();
4916 if (receiver == NULL && params == NULL)
4917 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
4919 Expression_list* vals = new Expression_list();
4920 vals->reserve((params == NULL ? 0 : params->size())
4921 + (receiver != NULL ? 1 : 0));
4923 if (receiver != NULL)
4924 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
4926 if (params != NULL)
4928 for (Typed_identifier_list::const_iterator p = params->begin();
4929 p != params->end();
4930 ++p)
4931 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
4934 return Expression::make_slice_composite_literal(params_type, vals, bloc);
4937 // The reflection string.
4939 void
4940 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
4942 // FIXME: Turn this off until we straighten out the type of the
4943 // struct field used in a go statement which calls a method.
4944 // go_assert(this->receiver_ == NULL);
4946 ret->append("func");
4948 if (this->receiver_ != NULL)
4950 ret->push_back('(');
4951 this->append_reflection(this->receiver_->type(), gogo, ret);
4952 ret->push_back(')');
4955 ret->push_back('(');
4956 const Typed_identifier_list* params = this->parameters();
4957 if (params != NULL)
4959 bool is_varargs = this->is_varargs_;
4960 for (Typed_identifier_list::const_iterator p = params->begin();
4961 p != params->end();
4962 ++p)
4964 if (p != params->begin())
4965 ret->append(", ");
4966 if (!is_varargs || p + 1 != params->end())
4967 this->append_reflection(p->type(), gogo, ret);
4968 else
4970 ret->append("...");
4971 this->append_reflection(p->type()->array_type()->element_type(),
4972 gogo, ret);
4976 ret->push_back(')');
4978 const Typed_identifier_list* results = this->results();
4979 if (results != NULL && !results->empty())
4981 if (results->size() == 1)
4982 ret->push_back(' ');
4983 else
4984 ret->append(" (");
4985 for (Typed_identifier_list::const_iterator p = results->begin();
4986 p != results->end();
4987 ++p)
4989 if (p != results->begin())
4990 ret->append(", ");
4991 this->append_reflection(p->type(), gogo, ret);
4993 if (results->size() > 1)
4994 ret->push_back(')');
4998 // Export a function type.
5000 void
5001 Function_type::do_export(Export* exp) const
5003 // We don't write out the receiver. The only function types which
5004 // should have a receiver are the ones associated with explicitly
5005 // defined methods. For those the receiver type is written out by
5006 // Function::export_func.
5008 exp->write_c_string("(");
5009 bool first = true;
5010 if (this->parameters_ != NULL)
5012 bool is_varargs = this->is_varargs_;
5013 for (Typed_identifier_list::const_iterator p =
5014 this->parameters_->begin();
5015 p != this->parameters_->end();
5016 ++p)
5018 if (first)
5019 first = false;
5020 else
5021 exp->write_c_string(", ");
5022 exp->write_name(p->name());
5023 exp->write_c_string(" ");
5024 if (!is_varargs || p + 1 != this->parameters_->end())
5025 exp->write_type(p->type());
5026 else
5028 exp->write_c_string("...");
5029 exp->write_type(p->type()->array_type()->element_type());
5033 exp->write_c_string(")");
5035 const Typed_identifier_list* results = this->results_;
5036 if (results != NULL)
5038 exp->write_c_string(" ");
5039 if (results->size() == 1 && results->begin()->name().empty())
5040 exp->write_type(results->begin()->type());
5041 else
5043 first = true;
5044 exp->write_c_string("(");
5045 for (Typed_identifier_list::const_iterator p = results->begin();
5046 p != results->end();
5047 ++p)
5049 if (first)
5050 first = false;
5051 else
5052 exp->write_c_string(", ");
5053 exp->write_name(p->name());
5054 exp->write_c_string(" ");
5055 exp->write_type(p->type());
5057 exp->write_c_string(")");
5062 // Import a function type.
5064 Function_type*
5065 Function_type::do_import(Import* imp)
5067 imp->require_c_string("(");
5068 Typed_identifier_list* parameters;
5069 bool is_varargs = false;
5070 if (imp->peek_char() == ')')
5071 parameters = NULL;
5072 else
5074 parameters = new Typed_identifier_list();
5075 while (true)
5077 std::string name = imp->read_name();
5078 imp->require_c_string(" ");
5080 if (imp->match_c_string("..."))
5082 imp->advance(3);
5083 is_varargs = true;
5086 Type* ptype = imp->read_type();
5087 if (is_varargs)
5088 ptype = Type::make_array_type(ptype, NULL);
5089 parameters->push_back(Typed_identifier(name, ptype,
5090 imp->location()));
5091 if (imp->peek_char() != ',')
5092 break;
5093 go_assert(!is_varargs);
5094 imp->require_c_string(", ");
5097 imp->require_c_string(")");
5099 Typed_identifier_list* results;
5100 if (imp->peek_char() != ' ')
5101 results = NULL;
5102 else
5104 imp->advance(1);
5105 results = new Typed_identifier_list;
5106 if (imp->peek_char() != '(')
5108 Type* rtype = imp->read_type();
5109 results->push_back(Typed_identifier("", rtype, imp->location()));
5111 else
5113 imp->advance(1);
5114 while (true)
5116 std::string name = imp->read_name();
5117 imp->require_c_string(" ");
5118 Type* rtype = imp->read_type();
5119 results->push_back(Typed_identifier(name, rtype,
5120 imp->location()));
5121 if (imp->peek_char() != ',')
5122 break;
5123 imp->require_c_string(", ");
5125 imp->require_c_string(")");
5129 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5130 imp->location());
5131 if (is_varargs)
5132 ret->set_is_varargs();
5133 return ret;
5136 // Make a copy of a function type without a receiver.
5138 Function_type*
5139 Function_type::copy_without_receiver() const
5141 go_assert(this->is_method());
5142 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5143 this->results_,
5144 this->location_);
5145 if (this->is_varargs())
5146 ret->set_is_varargs();
5147 if (this->is_builtin())
5148 ret->set_is_builtin();
5149 return ret;
5152 // Make a copy of a function type with a receiver.
5154 Function_type*
5155 Function_type::copy_with_receiver(Type* receiver_type) const
5157 go_assert(!this->is_method());
5158 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5159 this->location_);
5160 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5161 this->results_,
5162 this->location_);
5163 if (this->is_varargs_)
5164 ret->set_is_varargs();
5165 return ret;
5168 // Make a copy of a function type with the receiver as the first
5169 // parameter.
5171 Function_type*
5172 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5174 go_assert(this->is_method());
5175 Typed_identifier_list* new_params = new Typed_identifier_list();
5176 Type* rtype = this->receiver_->type();
5177 if (want_pointer_receiver)
5178 rtype = Type::make_pointer_type(rtype);
5179 Typed_identifier receiver(this->receiver_->name(), rtype,
5180 this->receiver_->location());
5181 new_params->push_back(receiver);
5182 const Typed_identifier_list* orig_params = this->parameters_;
5183 if (orig_params != NULL && !orig_params->empty())
5185 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5186 p != orig_params->end();
5187 ++p)
5188 new_params->push_back(*p);
5190 return Type::make_function_type(NULL, new_params, this->results_,
5191 this->location_);
5194 // Make a copy of a function type ignoring any receiver and adding a
5195 // closure parameter.
5197 Function_type*
5198 Function_type::copy_with_names() const
5200 Typed_identifier_list* new_params = new Typed_identifier_list();
5201 const Typed_identifier_list* orig_params = this->parameters_;
5202 if (orig_params != NULL && !orig_params->empty())
5204 static int count;
5205 char buf[50];
5206 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5207 p != orig_params->end();
5208 ++p)
5210 snprintf(buf, sizeof buf, "pt.%u", count);
5211 ++count;
5212 new_params->push_back(Typed_identifier(buf, p->type(),
5213 p->location()));
5217 const Typed_identifier_list* orig_results = this->results_;
5218 Typed_identifier_list* new_results;
5219 if (orig_results == NULL || orig_results->empty())
5220 new_results = NULL;
5221 else
5223 new_results = new Typed_identifier_list();
5224 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5225 p != orig_results->end();
5226 ++p)
5227 new_results->push_back(Typed_identifier("", p->type(),
5228 p->location()));
5231 return Type::make_function_type(NULL, new_params, new_results,
5232 this->location());
5235 // Make a function type.
5237 Function_type*
5238 Type::make_function_type(Typed_identifier* receiver,
5239 Typed_identifier_list* parameters,
5240 Typed_identifier_list* results,
5241 Location location)
5243 return new Function_type(receiver, parameters, results, location);
5246 // Make a backend function type.
5248 Backend_function_type*
5249 Type::make_backend_function_type(Typed_identifier* receiver,
5250 Typed_identifier_list* parameters,
5251 Typed_identifier_list* results,
5252 Location location)
5254 return new Backend_function_type(receiver, parameters, results, location);
5257 // Class Pointer_type.
5259 // Traversal.
5262 Pointer_type::do_traverse(Traverse* traverse)
5264 return Type::traverse(this->to_type_, traverse);
5267 // Hash code.
5269 unsigned int
5270 Pointer_type::do_hash_for_method(Gogo* gogo) const
5272 return this->to_type_->hash_for_method(gogo) << 4;
5275 // Get the backend representation for a pointer type.
5277 Btype*
5278 Pointer_type::do_get_backend(Gogo* gogo)
5280 Btype* to_btype = this->to_type_->get_backend(gogo);
5281 return gogo->backend()->pointer_type(to_btype);
5284 // The type of a pointer type descriptor.
5286 Type*
5287 Pointer_type::make_pointer_type_descriptor_type()
5289 static Type* ret;
5290 if (ret == NULL)
5292 Type* tdt = Type::make_type_descriptor_type();
5293 Type* ptdt = Type::make_type_descriptor_ptr_type();
5295 Struct_type* s = Type::make_builtin_struct_type(2,
5296 "", tdt,
5297 "elem", ptdt);
5299 ret = Type::make_builtin_named_type("PtrType", s);
5302 return ret;
5305 // The type descriptor for a pointer type.
5307 Expression*
5308 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5310 if (this->is_unsafe_pointer_type())
5312 go_assert(name != NULL);
5313 return this->plain_type_descriptor(gogo,
5314 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5315 name);
5317 else
5319 Location bloc = Linemap::predeclared_location();
5321 const Methods* methods;
5322 Type* deref = this->points_to();
5323 if (deref->named_type() != NULL)
5324 methods = deref->named_type()->methods();
5325 else if (deref->struct_type() != NULL)
5326 methods = deref->struct_type()->methods();
5327 else
5328 methods = NULL;
5330 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5332 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5334 Expression_list* vals = new Expression_list();
5335 vals->reserve(2);
5337 Struct_field_list::const_iterator p = fields->begin();
5338 go_assert(p->is_field_name("_type"));
5339 vals->push_back(this->type_descriptor_constructor(gogo,
5340 RUNTIME_TYPE_KIND_PTR,
5341 name, methods, false));
5343 ++p;
5344 go_assert(p->is_field_name("elem"));
5345 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5347 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5351 // Reflection string.
5353 void
5354 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5356 ret->push_back('*');
5357 this->append_reflection(this->to_type_, gogo, ret);
5360 // Export.
5362 void
5363 Pointer_type::do_export(Export* exp) const
5365 exp->write_c_string("*");
5366 if (this->is_unsafe_pointer_type())
5367 exp->write_c_string("any");
5368 else
5369 exp->write_type(this->to_type_);
5372 // Import.
5374 Pointer_type*
5375 Pointer_type::do_import(Import* imp)
5377 imp->require_c_string("*");
5378 if (imp->match_c_string("any"))
5380 imp->advance(3);
5381 return Type::make_pointer_type(Type::make_void_type());
5383 Type* to = imp->read_type();
5384 return Type::make_pointer_type(to);
5387 // Cache of pointer types. Key is "to" type, value is pointer type
5388 // that points to key.
5390 Type::Pointer_type_table Type::pointer_types;
5392 // A list of placeholder pointer types. We keep this so we can ensure
5393 // they are finalized.
5395 std::vector<Pointer_type*> Type::placeholder_pointers;
5397 // Make a pointer type.
5399 Pointer_type*
5400 Type::make_pointer_type(Type* to_type)
5402 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5403 if (p != pointer_types.end())
5404 return p->second;
5405 Pointer_type* ret = new Pointer_type(to_type);
5406 pointer_types[to_type] = ret;
5407 return ret;
5410 // This helper is invoked immediately after named types have been
5411 // converted, to clean up any unresolved pointer types remaining in
5412 // the pointer type cache.
5414 // The motivation for this routine: occasionally the compiler creates
5415 // some specific pointer type as part of a lowering operation (ex:
5416 // pointer-to-void), then Type::backend_type_size() is invoked on the
5417 // type (which creates a Btype placeholder for it), that placeholder
5418 // passed somewhere along the line to the back end, but since there is
5419 // no reference to the type in user code, there is never a call to
5420 // Type::finish_backend for the type (hence the Btype remains as an
5421 // unresolved placeholder). Calling this routine will clean up such
5422 // instances.
5424 void
5425 Type::finish_pointer_types(Gogo* gogo)
5427 // We don't use begin() and end() because it is possible to add new
5428 // placeholder pointer types as we finalized existing ones.
5429 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5431 Pointer_type* pt = Type::placeholder_pointers[i];
5432 Type_btypes::iterator tbti = Type::type_btypes.find(pt);
5433 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5435 pt->finish_backend(gogo, tbti->second.btype);
5436 tbti->second.is_placeholder = false;
5441 // Class Nil_type.
5443 // Get the backend representation of a nil type. FIXME: Is this ever
5444 // actually called?
5446 Btype*
5447 Nil_type::do_get_backend(Gogo* gogo)
5449 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5452 // Make the nil type.
5454 Type*
5455 Type::make_nil_type()
5457 static Nil_type singleton_nil_type;
5458 return &singleton_nil_type;
5461 // The type of a function call which returns multiple values. This is
5462 // really a struct, but we don't want to confuse a function call which
5463 // returns a struct with a function call which returns multiple
5464 // values.
5466 class Call_multiple_result_type : public Type
5468 public:
5469 Call_multiple_result_type(Call_expression* call)
5470 : Type(TYPE_CALL_MULTIPLE_RESULT),
5471 call_(call)
5474 protected:
5475 bool
5476 do_has_pointer() const
5477 { return false; }
5479 bool
5480 do_compare_is_identity(Gogo*)
5481 { return false; }
5483 Btype*
5484 do_get_backend(Gogo* gogo)
5486 go_assert(saw_errors());
5487 return gogo->backend()->error_type();
5490 Expression*
5491 do_type_descriptor(Gogo*, Named_type*)
5493 go_assert(saw_errors());
5494 return Expression::make_error(Linemap::unknown_location());
5497 void
5498 do_reflection(Gogo*, std::string*) const
5499 { go_assert(saw_errors()); }
5501 void
5502 do_mangled_name(Gogo*, std::string*) const
5503 { go_assert(saw_errors()); }
5505 private:
5506 // The expression being called.
5507 Call_expression* call_;
5510 // Make a call result type.
5512 Type*
5513 Type::make_call_multiple_result_type(Call_expression* call)
5515 return new Call_multiple_result_type(call);
5518 // Class Struct_field.
5520 // Get the name of a field.
5522 const std::string&
5523 Struct_field::field_name() const
5525 const std::string& name(this->typed_identifier_.name());
5526 if (!name.empty())
5527 return name;
5528 else
5530 // This is called during parsing, before anything is lowered, so
5531 // we have to be pretty careful to avoid dereferencing an
5532 // unknown type name.
5533 Type* t = this->typed_identifier_.type();
5534 Type* dt = t;
5535 if (t->classification() == Type::TYPE_POINTER)
5537 // Very ugly.
5538 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5539 dt = ptype->points_to();
5541 if (dt->forward_declaration_type() != NULL)
5542 return dt->forward_declaration_type()->name();
5543 else if (dt->named_type() != NULL)
5545 // Note that this can be an alias name.
5546 return dt->named_type()->name();
5548 else if (t->is_error_type() || dt->is_error_type())
5550 static const std::string error_string = "*error*";
5551 return error_string;
5553 else
5555 // Avoid crashing in the erroneous case where T is named but
5556 // DT is not.
5557 go_assert(t != dt);
5558 if (t->forward_declaration_type() != NULL)
5559 return t->forward_declaration_type()->name();
5560 else if (t->named_type() != NULL)
5561 return t->named_type()->name();
5562 else
5563 go_unreachable();
5568 // Return whether this field is named NAME.
5570 bool
5571 Struct_field::is_field_name(const std::string& name) const
5573 const std::string& me(this->typed_identifier_.name());
5574 if (!me.empty())
5575 return me == name;
5576 else
5578 Type* t = this->typed_identifier_.type();
5579 if (t->points_to() != NULL)
5580 t = t->points_to();
5581 Named_type* nt = t->named_type();
5582 if (nt != NULL && nt->name() == name)
5583 return true;
5585 // This is a horrible hack caused by the fact that we don't pack
5586 // the names of builtin types. FIXME.
5587 if (!this->is_imported_
5588 && nt != NULL
5589 && nt->is_builtin()
5590 && nt->name() == Gogo::unpack_hidden_name(name))
5591 return true;
5593 return false;
5597 // Return whether this field is an unexported field named NAME.
5599 bool
5600 Struct_field::is_unexported_field_name(Gogo* gogo,
5601 const std::string& name) const
5603 const std::string& field_name(this->field_name());
5604 if (Gogo::is_hidden_name(field_name)
5605 && name == Gogo::unpack_hidden_name(field_name)
5606 && gogo->pack_hidden_name(name, false) != field_name)
5607 return true;
5609 // Check for the name of a builtin type. This is like the test in
5610 // is_field_name, only there we return false if this->is_imported_,
5611 // and here we return true.
5612 if (this->is_imported_ && this->is_anonymous())
5614 Type* t = this->typed_identifier_.type();
5615 if (t->points_to() != NULL)
5616 t = t->points_to();
5617 Named_type* nt = t->named_type();
5618 if (nt != NULL
5619 && nt->is_builtin()
5620 && nt->name() == Gogo::unpack_hidden_name(name))
5621 return true;
5624 return false;
5627 // Return whether this field is an embedded built-in type.
5629 bool
5630 Struct_field::is_embedded_builtin(Gogo* gogo) const
5632 const std::string& name(this->field_name());
5633 // We know that a field is an embedded type if it is anonymous.
5634 // We can decide if it is a built-in type by checking to see if it is
5635 // registered globally under the field's name.
5636 // This allows us to distinguish between embedded built-in types and
5637 // embedded types that are aliases to built-in types.
5638 return (this->is_anonymous()
5639 && !Gogo::is_hidden_name(name)
5640 && gogo->lookup_global(name.c_str()) != NULL);
5643 // Class Struct_type.
5645 // A hash table used to find identical unnamed structs so that they
5646 // share method tables.
5648 Struct_type::Identical_structs Struct_type::identical_structs;
5650 // A hash table used to merge method sets for identical unnamed
5651 // structs.
5653 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
5655 // Traversal.
5658 Struct_type::do_traverse(Traverse* traverse)
5660 Struct_field_list* fields = this->fields_;
5661 if (fields != NULL)
5663 for (Struct_field_list::iterator p = fields->begin();
5664 p != fields->end();
5665 ++p)
5667 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
5668 return TRAVERSE_EXIT;
5671 return TRAVERSE_CONTINUE;
5674 // Verify that the struct type is complete and valid.
5676 bool
5677 Struct_type::do_verify()
5679 Struct_field_list* fields = this->fields_;
5680 if (fields == NULL)
5681 return true;
5682 for (Struct_field_list::iterator p = fields->begin();
5683 p != fields->end();
5684 ++p)
5686 Type* t = p->type();
5687 if (p->is_anonymous())
5689 if ((t->named_type() != NULL && t->points_to() != NULL)
5690 || (t->named_type() == NULL && t->points_to() != NULL
5691 && t->points_to()->points_to() != NULL))
5693 go_error_at(p->location(), "embedded type may not be a pointer");
5694 p->set_type(Type::make_error_type());
5696 else if (t->points_to() != NULL
5697 && t->points_to()->interface_type() != NULL)
5699 go_error_at(p->location(),
5700 "embedded type may not be pointer to interface");
5701 p->set_type(Type::make_error_type());
5705 return true;
5708 // Whether this contains a pointer.
5710 bool
5711 Struct_type::do_has_pointer() const
5713 const Struct_field_list* fields = this->fields();
5714 if (fields == NULL)
5715 return false;
5716 for (Struct_field_list::const_iterator p = fields->begin();
5717 p != fields->end();
5718 ++p)
5720 if (p->type()->has_pointer())
5721 return true;
5723 return false;
5726 // Whether this type is identical to T.
5728 bool
5729 Struct_type::is_identical(const Struct_type* t, Cmp_tags cmp_tags,
5730 bool errors_are_identical) const
5732 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
5733 return false;
5734 const Struct_field_list* fields1 = this->fields();
5735 const Struct_field_list* fields2 = t->fields();
5736 if (fields1 == NULL || fields2 == NULL)
5737 return fields1 == fields2;
5738 Struct_field_list::const_iterator pf2 = fields2->begin();
5739 for (Struct_field_list::const_iterator pf1 = fields1->begin();
5740 pf1 != fields1->end();
5741 ++pf1, ++pf2)
5743 if (pf2 == fields2->end())
5744 return false;
5745 if (pf1->field_name() != pf2->field_name())
5746 return false;
5747 if (pf1->is_anonymous() != pf2->is_anonymous()
5748 || !Type::are_identical_cmp_tags(pf1->type(), pf2->type(), cmp_tags,
5749 errors_are_identical, NULL))
5750 return false;
5751 if (cmp_tags == COMPARE_TAGS)
5753 if (!pf1->has_tag())
5755 if (pf2->has_tag())
5756 return false;
5758 else
5760 if (!pf2->has_tag())
5761 return false;
5762 if (pf1->tag() != pf2->tag())
5763 return false;
5767 if (pf2 != fields2->end())
5768 return false;
5769 return true;
5772 // Whether comparisons of this struct type are simple identity
5773 // comparisons.
5775 bool
5776 Struct_type::do_compare_is_identity(Gogo* gogo)
5778 const Struct_field_list* fields = this->fields_;
5779 if (fields == NULL)
5780 return true;
5781 int64_t offset = 0;
5782 for (Struct_field_list::const_iterator pf = fields->begin();
5783 pf != fields->end();
5784 ++pf)
5786 if (Gogo::is_sink_name(pf->field_name()))
5787 return false;
5789 if (!pf->type()->compare_is_identity(gogo))
5790 return false;
5792 int64_t field_align;
5793 if (!pf->type()->backend_type_align(gogo, &field_align))
5794 return false;
5795 if ((offset & (field_align - 1)) != 0)
5797 // This struct has padding. We don't guarantee that that
5798 // padding is zero-initialized for a stack variable, so we
5799 // can't use memcmp to compare struct values.
5800 return false;
5803 int64_t field_size;
5804 if (!pf->type()->backend_type_size(gogo, &field_size))
5805 return false;
5806 offset += field_size;
5809 int64_t struct_size;
5810 if (!this->backend_type_size(gogo, &struct_size))
5811 return false;
5812 if (offset != struct_size)
5814 // Trailing padding may not be zero when on the stack.
5815 return false;
5818 return true;
5821 // Return whether this struct type is reflexive--whether a value of
5822 // this type is always equal to itself.
5824 bool
5825 Struct_type::do_is_reflexive()
5827 const Struct_field_list* fields = this->fields_;
5828 if (fields == NULL)
5829 return true;
5830 for (Struct_field_list::const_iterator pf = fields->begin();
5831 pf != fields->end();
5832 ++pf)
5834 if (!pf->type()->is_reflexive())
5835 return false;
5837 return true;
5840 // Return whether this struct type needs a key update when used as a
5841 // map key.
5843 bool
5844 Struct_type::do_needs_key_update()
5846 const Struct_field_list* fields = this->fields_;
5847 if (fields == NULL)
5848 return false;
5849 for (Struct_field_list::const_iterator pf = fields->begin();
5850 pf != fields->end();
5851 ++pf)
5853 if (pf->type()->needs_key_update())
5854 return true;
5856 return false;
5859 // Return whether this struct type is permitted to be in the heap.
5861 bool
5862 Struct_type::do_in_heap()
5864 const Struct_field_list* fields = this->fields_;
5865 if (fields == NULL)
5866 return true;
5867 for (Struct_field_list::const_iterator pf = fields->begin();
5868 pf != fields->end();
5869 ++pf)
5871 if (!pf->type()->in_heap())
5872 return false;
5874 return true;
5877 // Build identity and hash functions for this struct.
5879 // Hash code.
5881 unsigned int
5882 Struct_type::do_hash_for_method(Gogo* gogo) const
5884 unsigned int ret = 0;
5885 if (this->fields() != NULL)
5887 for (Struct_field_list::const_iterator pf = this->fields()->begin();
5888 pf != this->fields()->end();
5889 ++pf)
5890 ret = (ret << 1) + pf->type()->hash_for_method(gogo);
5892 ret <<= 2;
5893 if (this->is_struct_incomparable_)
5894 ret <<= 1;
5895 return ret;
5898 // Find the local field NAME.
5900 const Struct_field*
5901 Struct_type::find_local_field(const std::string& name,
5902 unsigned int *pindex) const
5904 const Struct_field_list* fields = this->fields_;
5905 if (fields == NULL)
5906 return NULL;
5907 unsigned int i = 0;
5908 for (Struct_field_list::const_iterator pf = fields->begin();
5909 pf != fields->end();
5910 ++pf, ++i)
5912 if (pf->is_field_name(name))
5914 if (pindex != NULL)
5915 *pindex = i;
5916 return &*pf;
5919 return NULL;
5922 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
5924 Field_reference_expression*
5925 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
5926 Location location) const
5928 unsigned int depth;
5929 return this->field_reference_depth(struct_expr, name, location, NULL,
5930 &depth);
5933 // Return an expression for a field, along with the depth at which it
5934 // was found.
5936 Field_reference_expression*
5937 Struct_type::field_reference_depth(Expression* struct_expr,
5938 const std::string& name,
5939 Location location,
5940 Saw_named_type* saw,
5941 unsigned int* depth) const
5943 const Struct_field_list* fields = this->fields_;
5944 if (fields == NULL)
5945 return NULL;
5947 // Look for a field with this name.
5948 unsigned int i = 0;
5949 for (Struct_field_list::const_iterator pf = fields->begin();
5950 pf != fields->end();
5951 ++pf, ++i)
5953 if (pf->is_field_name(name))
5955 *depth = 0;
5956 return Expression::make_field_reference(struct_expr, i, location);
5960 // Look for an anonymous field which contains a field with this
5961 // name.
5962 unsigned int found_depth = 0;
5963 Field_reference_expression* ret = NULL;
5964 i = 0;
5965 for (Struct_field_list::const_iterator pf = fields->begin();
5966 pf != fields->end();
5967 ++pf, ++i)
5969 if (!pf->is_anonymous())
5970 continue;
5972 Struct_type* st = pf->type()->deref()->struct_type();
5973 if (st == NULL)
5974 continue;
5976 Saw_named_type* hold_saw = saw;
5977 Saw_named_type saw_here;
5978 Named_type* nt = pf->type()->named_type();
5979 if (nt == NULL)
5980 nt = pf->type()->deref()->named_type();
5981 if (nt != NULL)
5983 Saw_named_type* q;
5984 for (q = saw; q != NULL; q = q->next)
5986 if (q->nt == nt)
5988 // If this is an error, it will be reported
5989 // elsewhere.
5990 break;
5993 if (q != NULL)
5994 continue;
5995 saw_here.next = saw;
5996 saw_here.nt = nt;
5997 saw = &saw_here;
6000 // Look for a reference using a NULL struct expression. If we
6001 // find one, fill in the struct expression with a reference to
6002 // this field.
6003 unsigned int subdepth;
6004 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6005 location,
6006 saw,
6007 &subdepth);
6009 saw = hold_saw;
6011 if (sub == NULL)
6012 continue;
6014 if (ret == NULL || subdepth < found_depth)
6016 if (ret != NULL)
6017 delete ret;
6018 ret = sub;
6019 found_depth = subdepth;
6020 Expression* here = Expression::make_field_reference(struct_expr, i,
6021 location);
6022 if (pf->type()->points_to() != NULL)
6023 here = Expression::make_dereference(here,
6024 Expression::NIL_CHECK_DEFAULT,
6025 location);
6026 while (sub->expr() != NULL)
6028 sub = sub->expr()->deref()->field_reference_expression();
6029 go_assert(sub != NULL);
6031 sub->set_struct_expression(here);
6032 sub->set_implicit(true);
6034 else if (subdepth > found_depth)
6035 delete sub;
6036 else
6038 // We do not handle ambiguity here--it should be handled by
6039 // Type::bind_field_or_method.
6040 delete sub;
6041 found_depth = 0;
6042 ret = NULL;
6046 if (ret != NULL)
6047 *depth = found_depth + 1;
6049 return ret;
6052 // Return the total number of fields, including embedded fields.
6054 unsigned int
6055 Struct_type::total_field_count() const
6057 if (this->fields_ == NULL)
6058 return 0;
6059 unsigned int ret = 0;
6060 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6061 pf != this->fields_->end();
6062 ++pf)
6064 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6065 ++ret;
6066 else
6067 ret += pf->type()->struct_type()->total_field_count();
6069 return ret;
6072 // Return whether NAME is an unexported field, for better error reporting.
6074 bool
6075 Struct_type::is_unexported_local_field(Gogo* gogo,
6076 const std::string& name) const
6078 const Struct_field_list* fields = this->fields_;
6079 if (fields != NULL)
6081 for (Struct_field_list::const_iterator pf = fields->begin();
6082 pf != fields->end();
6083 ++pf)
6084 if (pf->is_unexported_field_name(gogo, name))
6085 return true;
6087 return false;
6090 // Finalize the methods of an unnamed struct.
6092 void
6093 Struct_type::finalize_methods(Gogo* gogo)
6095 if (this->all_methods_ != NULL)
6096 return;
6098 // It is possible to have multiple identical structs that have
6099 // methods. We want them to share method tables. Otherwise we will
6100 // emit identical methods more than once, which is bad since they
6101 // will even have the same names.
6102 std::pair<Identical_structs::iterator, bool> ins =
6103 Struct_type::identical_structs.insert(std::make_pair(this, this));
6104 if (!ins.second)
6106 // An identical struct was already entered into the hash table.
6107 // Note that finalize_methods is, fortunately, not recursive.
6108 this->all_methods_ = ins.first->second->all_methods_;
6109 return;
6112 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6115 // Return the method NAME, or NULL if there isn't one or if it is
6116 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6117 // ambiguous.
6119 Method*
6120 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6122 return Type::method_function(this->all_methods_, name, is_ambiguous);
6125 // Return a pointer to the interface method table for this type for
6126 // the interface INTERFACE. IS_POINTER is true if this is for a
6127 // pointer to THIS.
6129 Expression*
6130 Struct_type::interface_method_table(Interface_type* interface,
6131 bool is_pointer)
6133 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6134 val(this, NULL);
6135 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6136 Struct_type::struct_method_tables.insert(val);
6138 Struct_method_table_pair* smtp;
6139 if (!ins.second)
6140 smtp = ins.first->second;
6141 else
6143 smtp = new Struct_method_table_pair();
6144 smtp->first = NULL;
6145 smtp->second = NULL;
6146 ins.first->second = smtp;
6149 return Type::interface_method_table(this, interface, is_pointer,
6150 &smtp->first, &smtp->second);
6153 // Convert struct fields to the backend representation. This is not
6154 // declared in types.h so that types.h doesn't have to #include
6155 // backend.h.
6157 static void
6158 get_backend_struct_fields(Gogo* gogo, const Struct_field_list* fields,
6159 bool use_placeholder,
6160 std::vector<Backend::Btyped_identifier>* bfields)
6162 bfields->resize(fields->size());
6163 size_t i = 0;
6164 for (Struct_field_list::const_iterator p = fields->begin();
6165 p != fields->end();
6166 ++p, ++i)
6168 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6169 (*bfields)[i].btype = (use_placeholder
6170 ? p->type()->get_backend_placeholder(gogo)
6171 : p->type()->get_backend(gogo));
6172 (*bfields)[i].location = p->location();
6174 go_assert(i == fields->size());
6177 // Get the backend representation for a struct type.
6179 Btype*
6180 Struct_type::do_get_backend(Gogo* gogo)
6182 std::vector<Backend::Btyped_identifier> bfields;
6183 get_backend_struct_fields(gogo, this->fields_, false, &bfields);
6184 return gogo->backend()->struct_type(bfields);
6187 // Finish the backend representation of the fields of a struct.
6189 void
6190 Struct_type::finish_backend_fields(Gogo* gogo)
6192 const Struct_field_list* fields = this->fields_;
6193 if (fields != NULL)
6195 for (Struct_field_list::const_iterator p = fields->begin();
6196 p != fields->end();
6197 ++p)
6198 p->type()->get_backend(gogo);
6202 // The type of a struct type descriptor.
6204 Type*
6205 Struct_type::make_struct_type_descriptor_type()
6207 static Type* ret;
6208 if (ret == NULL)
6210 Type* tdt = Type::make_type_descriptor_type();
6211 Type* ptdt = Type::make_type_descriptor_ptr_type();
6213 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6214 Type* string_type = Type::lookup_string_type();
6215 Type* pointer_string_type = Type::make_pointer_type(string_type);
6217 Struct_type* sf =
6218 Type::make_builtin_struct_type(5,
6219 "name", pointer_string_type,
6220 "pkgPath", pointer_string_type,
6221 "typ", ptdt,
6222 "tag", pointer_string_type,
6223 "offsetAnon", uintptr_type);
6224 Type* nsf = Type::make_builtin_named_type("structField", sf);
6226 Type* slice_type = Type::make_array_type(nsf, NULL);
6228 Struct_type* s = Type::make_builtin_struct_type(2,
6229 "", tdt,
6230 "fields", slice_type);
6232 ret = Type::make_builtin_named_type("StructType", s);
6235 return ret;
6238 // Build a type descriptor for a struct type.
6240 Expression*
6241 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6243 Location bloc = Linemap::predeclared_location();
6245 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6247 const Struct_field_list* fields = stdt->struct_type()->fields();
6249 Expression_list* vals = new Expression_list();
6250 vals->reserve(2);
6252 const Methods* methods = this->methods();
6253 // A named struct should not have methods--the methods should attach
6254 // to the named type.
6255 go_assert(methods == NULL || name == NULL);
6257 Struct_field_list::const_iterator ps = fields->begin();
6258 go_assert(ps->is_field_name("_type"));
6259 vals->push_back(this->type_descriptor_constructor(gogo,
6260 RUNTIME_TYPE_KIND_STRUCT,
6261 name, methods, true));
6263 ++ps;
6264 go_assert(ps->is_field_name("fields"));
6266 Expression_list* elements = new Expression_list();
6267 elements->reserve(this->fields_->size());
6268 Type* element_type = ps->type()->array_type()->element_type();
6269 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6270 pf != this->fields_->end();
6271 ++pf)
6273 const Struct_field_list* f = element_type->struct_type()->fields();
6275 Expression_list* fvals = new Expression_list();
6276 fvals->reserve(5);
6278 Struct_field_list::const_iterator q = f->begin();
6279 go_assert(q->is_field_name("name"));
6280 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6281 Expression* s = Expression::make_string(n, bloc);
6282 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6284 ++q;
6285 go_assert(q->is_field_name("pkgPath"));
6286 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6287 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6288 fvals->push_back(Expression::make_nil(bloc));
6289 else
6291 std::string n;
6292 if (is_embedded_builtin)
6293 n = gogo->package_name();
6294 else
6295 n = Gogo::hidden_name_pkgpath(pf->field_name());
6296 Expression* s = Expression::make_string(n, bloc);
6297 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6300 ++q;
6301 go_assert(q->is_field_name("typ"));
6302 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6304 ++q;
6305 go_assert(q->is_field_name("tag"));
6306 if (!pf->has_tag())
6307 fvals->push_back(Expression::make_nil(bloc));
6308 else
6310 Expression* s = Expression::make_string(pf->tag(), bloc);
6311 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6314 ++q;
6315 go_assert(q->is_field_name("offsetAnon"));
6316 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6317 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6318 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6319 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6320 int av = pf->is_anonymous() ? 1 : 0;
6321 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6322 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6323 fvals->push_back(o);
6325 Expression* v = Expression::make_struct_composite_literal(element_type,
6326 fvals, bloc);
6327 elements->push_back(v);
6330 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6331 elements, bloc));
6333 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6336 // Write the hash function for a struct which can not use the identity
6337 // function.
6339 void
6340 Struct_type::write_hash_function(Gogo* gogo, Named_type*,
6341 Function_type* hash_fntype,
6342 Function_type* equal_fntype)
6344 Location bloc = Linemap::predeclared_location();
6346 // The pointer to the struct that we are going to hash. This is an
6347 // argument to the hash function we are implementing here.
6348 Named_object* key_arg = gogo->lookup("key", NULL);
6349 go_assert(key_arg != NULL);
6350 Type* key_arg_type = key_arg->var_value()->type();
6352 // The seed argument to the hash function.
6353 Named_object* seed_arg = gogo->lookup("seed", NULL);
6354 go_assert(seed_arg != NULL);
6356 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6358 // Make a temporary to hold the return value, initialized to the seed.
6359 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6360 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6361 bloc);
6362 gogo->add_statement(retval);
6364 // Make a temporary to hold the key as a uintptr.
6365 ref = Expression::make_var_reference(key_arg, bloc);
6366 ref = Expression::make_cast(uintptr_type, ref, bloc);
6367 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6368 bloc);
6369 gogo->add_statement(key);
6371 // Loop over the struct fields.
6372 const Struct_field_list* fields = this->fields_;
6373 for (Struct_field_list::const_iterator pf = fields->begin();
6374 pf != fields->end();
6375 ++pf)
6377 if (Gogo::is_sink_name(pf->field_name()))
6378 continue;
6380 // Get a pointer to the value of this field.
6381 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6382 ref = Expression::make_temporary_reference(key, bloc);
6383 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6384 bloc);
6385 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6387 // Get the hash function to use for the type of this field.
6388 Named_object* hash_fn;
6389 Named_object* equal_fn;
6390 pf->type()->type_functions(gogo, pf->type()->named_type(), hash_fntype,
6391 equal_fntype, &hash_fn, &equal_fn);
6393 // Call the hash function for the field, passing retval as the seed.
6394 ref = Expression::make_temporary_reference(retval, bloc);
6395 Expression_list* args = new Expression_list();
6396 args->push_back(subkey);
6397 args->push_back(ref);
6398 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6399 Expression* call = Expression::make_call(func, args, false, bloc);
6401 // Set retval to the result.
6402 Temporary_reference_expression* tref =
6403 Expression::make_temporary_reference(retval, bloc);
6404 tref->set_is_lvalue();
6405 Statement* s = Statement::make_assignment(tref, call, bloc);
6406 gogo->add_statement(s);
6409 // Return retval to the caller of the hash function.
6410 Expression_list* vals = new Expression_list();
6411 ref = Expression::make_temporary_reference(retval, bloc);
6412 vals->push_back(ref);
6413 Statement* s = Statement::make_return_statement(vals, bloc);
6414 gogo->add_statement(s);
6417 // Write the equality function for a struct which can not use the
6418 // identity function.
6420 void
6421 Struct_type::write_equal_function(Gogo* gogo, Named_type* name)
6423 Location bloc = Linemap::predeclared_location();
6425 // The pointers to the structs we are going to compare.
6426 Named_object* key1_arg = gogo->lookup("key1", NULL);
6427 Named_object* key2_arg = gogo->lookup("key2", NULL);
6428 go_assert(key1_arg != NULL && key2_arg != NULL);
6430 // Build temporaries with the right types.
6431 Type* pt = Type::make_pointer_type(name != NULL
6432 ? static_cast<Type*>(name)
6433 : static_cast<Type*>(this));
6435 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6436 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6437 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6438 gogo->add_statement(p1);
6440 ref = Expression::make_var_reference(key2_arg, bloc);
6441 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6442 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6443 gogo->add_statement(p2);
6445 const Struct_field_list* fields = this->fields_;
6446 unsigned int field_index = 0;
6447 for (Struct_field_list::const_iterator pf = fields->begin();
6448 pf != fields->end();
6449 ++pf, ++field_index)
6451 if (Gogo::is_sink_name(pf->field_name()))
6452 continue;
6454 // Compare one field in both P1 and P2.
6455 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6456 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6457 bloc);
6458 f1 = Expression::make_field_reference(f1, field_index, bloc);
6460 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6461 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6462 bloc);
6463 f2 = Expression::make_field_reference(f2, field_index, bloc);
6465 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6467 // If the values are not equal, return false.
6468 gogo->start_block(bloc);
6469 Expression_list* vals = new Expression_list();
6470 vals->push_back(Expression::make_boolean(false, bloc));
6471 Statement* s = Statement::make_return_statement(vals, bloc);
6472 gogo->add_statement(s);
6473 Block* then_block = gogo->finish_block(bloc);
6475 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
6476 gogo->add_statement(s);
6479 // All the fields are equal, so return true.
6480 Expression_list* vals = new Expression_list();
6481 vals->push_back(Expression::make_boolean(true, bloc));
6482 Statement* s = Statement::make_return_statement(vals, bloc);
6483 gogo->add_statement(s);
6486 // Reflection string.
6488 void
6489 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
6491 ret->append("struct {");
6493 for (Struct_field_list::const_iterator p = this->fields_->begin();
6494 p != this->fields_->end();
6495 ++p)
6497 if (p != this->fields_->begin())
6498 ret->push_back(';');
6499 ret->push_back(' ');
6500 if (!p->is_anonymous())
6502 ret->append(Gogo::unpack_hidden_name(p->field_name()));
6503 ret->push_back(' ');
6505 if (p->is_anonymous()
6506 && p->type()->named_type() != NULL
6507 && p->type()->named_type()->is_alias())
6508 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
6509 else
6510 this->append_reflection(p->type(), gogo, ret);
6512 if (p->has_tag())
6514 const std::string& tag(p->tag());
6515 ret->append(" \"");
6516 for (std::string::const_iterator p = tag.begin();
6517 p != tag.end();
6518 ++p)
6520 if (*p == '\0')
6521 ret->append("\\x00");
6522 else if (*p == '\n')
6523 ret->append("\\n");
6524 else if (*p == '\t')
6525 ret->append("\\t");
6526 else if (*p == '"')
6527 ret->append("\\\"");
6528 else if (*p == '\\')
6529 ret->append("\\\\");
6530 else
6531 ret->push_back(*p);
6533 ret->push_back('"');
6537 if (!this->fields_->empty())
6538 ret->push_back(' ');
6540 ret->push_back('}');
6543 // If the offset of field INDEX in the backend implementation can be
6544 // determined, set *POFFSET to the offset in bytes and return true.
6545 // Otherwise, return false.
6547 bool
6548 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
6549 int64_t* poffset)
6551 if (!this->is_backend_type_size_known(gogo))
6552 return false;
6553 Btype* bt = this->get_backend_placeholder(gogo);
6554 *poffset = gogo->backend()->type_field_offset(bt, index);
6555 return true;
6558 // Export.
6560 void
6561 Struct_type::do_export(Export* exp) const
6563 exp->write_c_string("struct { ");
6564 const Struct_field_list* fields = this->fields_;
6565 go_assert(fields != NULL);
6566 for (Struct_field_list::const_iterator p = fields->begin();
6567 p != fields->end();
6568 ++p)
6570 if (p->is_anonymous())
6571 exp->write_string("? ");
6572 else
6574 exp->write_string(p->field_name());
6575 exp->write_c_string(" ");
6577 exp->write_type(p->type());
6579 if (p->has_tag())
6581 exp->write_c_string(" ");
6582 Expression* expr =
6583 Expression::make_string(p->tag(), Linemap::predeclared_location());
6584 expr->export_expression(exp);
6585 delete expr;
6588 exp->write_c_string("; ");
6590 exp->write_c_string("}");
6593 // Import.
6595 Struct_type*
6596 Struct_type::do_import(Import* imp)
6598 imp->require_c_string("struct { ");
6599 Struct_field_list* fields = new Struct_field_list;
6600 if (imp->peek_char() != '}')
6602 while (true)
6604 std::string name;
6605 if (imp->match_c_string("? "))
6606 imp->advance(2);
6607 else
6609 name = imp->read_identifier();
6610 imp->require_c_string(" ");
6612 Type* ftype = imp->read_type();
6614 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
6615 sf.set_is_imported();
6617 if (imp->peek_char() == ' ')
6619 imp->advance(1);
6620 Expression* expr = Expression::import_expression(imp);
6621 String_expression* sexpr = expr->string_expression();
6622 go_assert(sexpr != NULL);
6623 sf.set_tag(sexpr->val());
6624 delete sexpr;
6627 imp->require_c_string("; ");
6628 fields->push_back(sf);
6629 if (imp->peek_char() == '}')
6630 break;
6633 imp->require_c_string("}");
6635 return Type::make_struct_type(fields, imp->location());
6638 // Whether we can write this struct type to a C header file.
6639 // We can't if any of the fields are structs defined in a different package.
6641 bool
6642 Struct_type::can_write_to_c_header(
6643 std::vector<const Named_object*>* requires,
6644 std::vector<const Named_object*>* declare) const
6646 const Struct_field_list* fields = this->fields_;
6647 if (fields == NULL || fields->empty())
6648 return false;
6649 int sinks = 0;
6650 for (Struct_field_list::const_iterator p = fields->begin();
6651 p != fields->end();
6652 ++p)
6654 if (p->is_anonymous())
6655 return false;
6656 if (!this->can_write_type_to_c_header(p->type(), requires, declare))
6657 return false;
6658 if (Gogo::message_name(p->field_name()) == "_")
6659 sinks++;
6661 if (sinks > 1)
6662 return false;
6663 return true;
6666 // Whether we can write the type T to a C header file.
6668 bool
6669 Struct_type::can_write_type_to_c_header(
6670 const Type* t,
6671 std::vector<const Named_object*>* requires,
6672 std::vector<const Named_object*>* declare) const
6674 t = t->forwarded();
6675 switch (t->classification())
6677 case TYPE_ERROR:
6678 case TYPE_FORWARD:
6679 return false;
6681 case TYPE_VOID:
6682 case TYPE_BOOLEAN:
6683 case TYPE_INTEGER:
6684 case TYPE_FLOAT:
6685 case TYPE_COMPLEX:
6686 case TYPE_STRING:
6687 case TYPE_FUNCTION:
6688 case TYPE_MAP:
6689 case TYPE_CHANNEL:
6690 case TYPE_INTERFACE:
6691 return true;
6693 case TYPE_POINTER:
6694 // Don't try to handle a pointer to an array.
6695 if (t->points_to()->array_type() != NULL
6696 && !t->points_to()->is_slice_type())
6697 return false;
6699 if (t->points_to()->named_type() != NULL
6700 && t->points_to()->struct_type() != NULL)
6701 declare->push_back(t->points_to()->named_type()->named_object());
6702 return true;
6704 case TYPE_STRUCT:
6705 return t->struct_type()->can_write_to_c_header(requires, declare);
6707 case TYPE_ARRAY:
6708 if (t->is_slice_type())
6709 return true;
6710 return this->can_write_type_to_c_header(t->array_type()->element_type(),
6711 requires, declare);
6713 case TYPE_NAMED:
6715 const Named_object* no = t->named_type()->named_object();
6716 if (no->package() != NULL)
6718 if (t->is_unsafe_pointer_type())
6719 return true;
6720 return false;
6722 if (t->struct_type() != NULL)
6724 requires->push_back(no);
6725 return t->struct_type()->can_write_to_c_header(requires, declare);
6727 return this->can_write_type_to_c_header(t->base(), requires, declare);
6730 case TYPE_CALL_MULTIPLE_RESULT:
6731 case TYPE_NIL:
6732 case TYPE_SINK:
6733 default:
6734 go_unreachable();
6738 // Write this struct to a C header file.
6740 void
6741 Struct_type::write_to_c_header(std::ostream& os) const
6743 const Struct_field_list* fields = this->fields_;
6744 for (Struct_field_list::const_iterator p = fields->begin();
6745 p != fields->end();
6746 ++p)
6748 os << '\t';
6749 this->write_field_to_c_header(os, p->field_name(), p->type());
6750 os << ';' << std::endl;
6754 // Write the type of a struct field to a C header file.
6756 void
6757 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
6758 const Type *t) const
6760 bool print_name = true;
6761 t = t->forwarded();
6762 switch (t->classification())
6764 case TYPE_VOID:
6765 os << "void";
6766 break;
6768 case TYPE_BOOLEAN:
6769 os << "_Bool";
6770 break;
6772 case TYPE_INTEGER:
6774 const Integer_type* it = t->integer_type();
6775 if (it->is_unsigned())
6776 os << 'u';
6777 os << "int" << it->bits() << "_t";
6779 break;
6781 case TYPE_FLOAT:
6782 switch (t->float_type()->bits())
6784 case 32:
6785 os << "float";
6786 break;
6787 case 64:
6788 os << "double";
6789 break;
6790 default:
6791 go_unreachable();
6793 break;
6795 case TYPE_COMPLEX:
6796 switch (t->complex_type()->bits())
6798 case 64:
6799 os << "float _Complex";
6800 break;
6801 case 128:
6802 os << "double _Complex";
6803 break;
6804 default:
6805 go_unreachable();
6807 break;
6809 case TYPE_STRING:
6810 os << "String";
6811 break;
6813 case TYPE_FUNCTION:
6814 os << "FuncVal*";
6815 break;
6817 case TYPE_POINTER:
6819 std::vector<const Named_object*> requires;
6820 std::vector<const Named_object*> declare;
6821 if (!this->can_write_type_to_c_header(t->points_to(), &requires,
6822 &declare))
6823 os << "void*";
6824 else
6826 this->write_field_to_c_header(os, "", t->points_to());
6827 os << '*';
6830 break;
6832 case TYPE_MAP:
6833 os << "Map*";
6834 break;
6836 case TYPE_CHANNEL:
6837 os << "Chan*";
6838 break;
6840 case TYPE_INTERFACE:
6841 if (t->interface_type()->is_empty())
6842 os << "Eface";
6843 else
6844 os << "Iface";
6845 break;
6847 case TYPE_STRUCT:
6848 os << "struct {" << std::endl;
6849 t->struct_type()->write_to_c_header(os);
6850 os << "\t}";
6851 break;
6853 case TYPE_ARRAY:
6854 if (t->is_slice_type())
6855 os << "Slice";
6856 else
6858 const Type *ele = t;
6859 std::vector<const Type*> array_types;
6860 while (ele->array_type() != NULL && !ele->is_slice_type())
6862 array_types.push_back(ele);
6863 ele = ele->array_type()->element_type();
6865 this->write_field_to_c_header(os, "", ele);
6866 os << ' ' << Gogo::message_name(name);
6867 print_name = false;
6868 while (!array_types.empty())
6870 ele = array_types.back();
6871 array_types.pop_back();
6872 os << '[';
6873 Numeric_constant nc;
6874 if (!ele->array_type()->length()->numeric_constant_value(&nc))
6875 go_unreachable();
6876 mpz_t val;
6877 if (!nc.to_int(&val))
6878 go_unreachable();
6879 char* s = mpz_get_str(NULL, 10, val);
6880 os << s;
6881 free(s);
6882 mpz_clear(val);
6883 os << ']';
6886 break;
6888 case TYPE_NAMED:
6890 const Named_object* no = t->named_type()->named_object();
6891 if (t->struct_type() != NULL)
6892 os << "struct " << no->message_name();
6893 else if (t->is_unsafe_pointer_type())
6894 os << "void*";
6895 else if (t == Type::lookup_integer_type("uintptr"))
6896 os << "uintptr_t";
6897 else
6899 this->write_field_to_c_header(os, name, t->base());
6900 print_name = false;
6903 break;
6905 case TYPE_ERROR:
6906 case TYPE_FORWARD:
6907 case TYPE_CALL_MULTIPLE_RESULT:
6908 case TYPE_NIL:
6909 case TYPE_SINK:
6910 default:
6911 go_unreachable();
6914 if (print_name && !name.empty())
6915 os << ' ' << Gogo::message_name(name);
6918 // Make a struct type.
6920 Struct_type*
6921 Type::make_struct_type(Struct_field_list* fields,
6922 Location location)
6924 return new Struct_type(fields, location);
6927 // Class Array_type.
6929 // Store the length of an array as an int64_t into *PLEN. Return
6930 // false if the length can not be determined. This will assert if
6931 // called for a slice.
6933 bool
6934 Array_type::int_length(int64_t* plen)
6936 go_assert(this->length_ != NULL);
6937 Numeric_constant nc;
6938 if (!this->length_->numeric_constant_value(&nc))
6939 return false;
6940 return nc.to_memory_size(plen);
6943 // Whether two array types are identical.
6945 bool
6946 Array_type::is_identical(const Array_type* t, Cmp_tags cmp_tags,
6947 bool errors_are_identical) const
6949 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
6950 cmp_tags, errors_are_identical, NULL))
6951 return false;
6953 if (this->is_array_incomparable_ != t->is_array_incomparable_)
6954 return false;
6956 Expression* l1 = this->length();
6957 Expression* l2 = t->length();
6959 // Slices of the same element type are identical.
6960 if (l1 == NULL && l2 == NULL)
6961 return true;
6963 // Arrays of the same element type are identical if they have the
6964 // same length.
6965 if (l1 != NULL && l2 != NULL)
6967 if (l1 == l2)
6968 return true;
6970 // Try to determine the lengths. If we can't, assume the arrays
6971 // are not identical.
6972 bool ret = false;
6973 Numeric_constant nc1, nc2;
6974 if (l1->numeric_constant_value(&nc1)
6975 && l2->numeric_constant_value(&nc2))
6977 mpz_t v1;
6978 if (nc1.to_int(&v1))
6980 mpz_t v2;
6981 if (nc2.to_int(&v2))
6983 ret = mpz_cmp(v1, v2) == 0;
6984 mpz_clear(v2);
6986 mpz_clear(v1);
6989 return ret;
6992 // Otherwise the arrays are not identical.
6993 return false;
6996 // Traversal.
6999 Array_type::do_traverse(Traverse* traverse)
7001 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7002 return TRAVERSE_EXIT;
7003 if (this->length_ != NULL
7004 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7005 return TRAVERSE_EXIT;
7006 return TRAVERSE_CONTINUE;
7009 // Check that the length is valid.
7011 bool
7012 Array_type::verify_length()
7014 if (this->length_ == NULL)
7015 return true;
7017 Type_context context(Type::lookup_integer_type("int"), false);
7018 this->length_->determine_type(&context);
7020 if (!this->length_->is_constant())
7022 go_error_at(this->length_->location(), "array bound is not constant");
7023 return false;
7026 // For array types, the length expression can be an untyped constant
7027 // representable as an int, but we don't allow explicitly non-integer
7028 // values such as "float64(10)". See issues #13485 and #13486.
7029 if (this->length_->type()->integer_type() == NULL
7030 && !this->length_->type()->is_error_type())
7032 go_error_at(this->length_->location(), "invalid array bound");
7033 return false;
7036 Numeric_constant nc;
7037 if (!this->length_->numeric_constant_value(&nc))
7039 if (this->length_->type()->integer_type() != NULL
7040 || this->length_->type()->float_type() != NULL)
7041 go_error_at(this->length_->location(), "array bound is not constant");
7042 else
7043 go_error_at(this->length_->location(), "array bound is not numeric");
7044 return false;
7047 Type* int_type = Type::lookup_integer_type("int");
7048 unsigned int tbits = int_type->integer_type()->bits();
7049 unsigned long val;
7050 switch (nc.to_unsigned_long(&val))
7052 case Numeric_constant::NC_UL_VALID:
7053 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7055 go_error_at(this->length_->location(), "array bound overflows");
7056 return false;
7058 break;
7059 case Numeric_constant::NC_UL_NOTINT:
7060 go_error_at(this->length_->location(), "array bound truncated to integer");
7061 return false;
7062 case Numeric_constant::NC_UL_NEGATIVE:
7063 go_error_at(this->length_->location(), "negative array bound");
7064 return false;
7065 case Numeric_constant::NC_UL_BIG:
7067 mpz_t val;
7068 if (!nc.to_int(&val))
7069 go_unreachable();
7070 unsigned int bits = mpz_sizeinbase(val, 2);
7071 mpz_clear(val);
7072 if (bits >= tbits)
7074 go_error_at(this->length_->location(), "array bound overflows");
7075 return false;
7078 break;
7079 default:
7080 go_unreachable();
7083 return true;
7086 // Verify the type.
7088 bool
7089 Array_type::do_verify()
7091 if (this->element_type()->is_error_type())
7092 return false;
7093 if (!this->verify_length())
7094 this->length_ = Expression::make_error(this->length_->location());
7095 return true;
7098 // Whether the type contains pointers. This is always true for a
7099 // slice. For an array it is true if the element type has pointers
7100 // and the length is greater than zero.
7102 bool
7103 Array_type::do_has_pointer() const
7105 if (this->length_ == NULL)
7106 return true;
7107 if (!this->element_type_->has_pointer())
7108 return false;
7110 Numeric_constant nc;
7111 if (!this->length_->numeric_constant_value(&nc))
7113 // Error reported elsewhere.
7114 return false;
7117 unsigned long val;
7118 switch (nc.to_unsigned_long(&val))
7120 case Numeric_constant::NC_UL_VALID:
7121 return val > 0;
7122 case Numeric_constant::NC_UL_BIG:
7123 return true;
7124 default:
7125 // Error reported elsewhere.
7126 return false;
7130 // Whether we can use memcmp to compare this array.
7132 bool
7133 Array_type::do_compare_is_identity(Gogo* gogo)
7135 if (this->length_ == NULL)
7136 return false;
7138 // Check for [...], which indicates that this is not a real type.
7139 if (this->length_->is_nil_expression())
7140 return false;
7142 if (!this->element_type_->compare_is_identity(gogo))
7143 return false;
7145 // If there is any padding, then we can't use memcmp.
7146 int64_t size;
7147 int64_t align;
7148 if (!this->element_type_->backend_type_size(gogo, &size)
7149 || !this->element_type_->backend_type_align(gogo, &align))
7150 return false;
7151 if ((size & (align - 1)) != 0)
7152 return false;
7154 return true;
7157 // Array type hash code.
7159 unsigned int
7160 Array_type::do_hash_for_method(Gogo* gogo) const
7162 unsigned int ret;
7164 // There is no very convenient way to get a hash code for the
7165 // length.
7166 ret = this->element_type_->hash_for_method(gogo) + 1;
7167 if (this->is_array_incomparable_)
7168 ret <<= 1;
7169 return ret;
7172 // Write the hash function for an array which can not use the identify
7173 // function.
7175 void
7176 Array_type::write_hash_function(Gogo* gogo, Named_type* name,
7177 Function_type* hash_fntype,
7178 Function_type* equal_fntype)
7180 Location bloc = Linemap::predeclared_location();
7182 // The pointer to the array that we are going to hash. This is an
7183 // argument to the hash function we are implementing here.
7184 Named_object* key_arg = gogo->lookup("key", NULL);
7185 go_assert(key_arg != NULL);
7186 Type* key_arg_type = key_arg->var_value()->type();
7188 // The seed argument to the hash function.
7189 Named_object* seed_arg = gogo->lookup("seed", NULL);
7190 go_assert(seed_arg != NULL);
7192 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7194 // Make a temporary to hold the return value, initialized to the seed.
7195 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7196 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7197 bloc);
7198 gogo->add_statement(retval);
7200 // Make a temporary to hold the key as a uintptr.
7201 ref = Expression::make_var_reference(key_arg, bloc);
7202 ref = Expression::make_cast(uintptr_type, ref, bloc);
7203 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7204 bloc);
7205 gogo->add_statement(key);
7207 // Loop over the array elements.
7208 // for i = range a
7209 Type* int_type = Type::lookup_integer_type("int");
7210 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7211 gogo->add_statement(index);
7213 Expression* iref = Expression::make_temporary_reference(index, bloc);
7214 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7215 Type* pt = Type::make_pointer_type(name != NULL
7216 ? static_cast<Type*>(name)
7217 : static_cast<Type*>(this));
7218 aref = Expression::make_cast(pt, aref, bloc);
7219 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7220 NULL,
7221 aref,
7222 bloc);
7224 gogo->start_block(bloc);
7226 // Get the hash function for the element type.
7227 Named_object* hash_fn;
7228 Named_object* equal_fn;
7229 this->element_type_->type_functions(gogo, this->element_type_->named_type(),
7230 hash_fntype, equal_fntype, &hash_fn,
7231 &equal_fn);
7233 // Get a pointer to this element in the loop.
7234 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7235 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7237 // Get the size of each element.
7238 Expression* ele_size = Expression::make_type_info(this->element_type_,
7239 Expression::TYPE_INFO_SIZE);
7241 // Get the hash of this element, passing retval as the seed.
7242 ref = Expression::make_temporary_reference(retval, bloc);
7243 Expression_list* args = new Expression_list();
7244 args->push_back(subkey);
7245 args->push_back(ref);
7246 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7247 Expression* call = Expression::make_call(func, args, false, bloc);
7249 // Set retval to the result.
7250 Temporary_reference_expression* tref =
7251 Expression::make_temporary_reference(retval, bloc);
7252 tref->set_is_lvalue();
7253 Statement* s = Statement::make_assignment(tref, call, bloc);
7254 gogo->add_statement(s);
7256 // Increase the element pointer.
7257 tref = Expression::make_temporary_reference(key, bloc);
7258 tref->set_is_lvalue();
7259 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7260 bloc);
7261 Block* statements = gogo->finish_block(bloc);
7263 for_range->add_statements(statements);
7264 gogo->add_statement(for_range);
7266 // Return retval to the caller of the hash function.
7267 Expression_list* vals = new Expression_list();
7268 ref = Expression::make_temporary_reference(retval, bloc);
7269 vals->push_back(ref);
7270 s = Statement::make_return_statement(vals, bloc);
7271 gogo->add_statement(s);
7274 // Write the equality function for an array which can not use the
7275 // identity function.
7277 void
7278 Array_type::write_equal_function(Gogo* gogo, Named_type* name)
7280 Location bloc = Linemap::predeclared_location();
7282 // The pointers to the arrays we are going to compare.
7283 Named_object* key1_arg = gogo->lookup("key1", NULL);
7284 Named_object* key2_arg = gogo->lookup("key2", NULL);
7285 go_assert(key1_arg != NULL && key2_arg != NULL);
7287 // Build temporaries for the keys with the right types.
7288 Type* pt = Type::make_pointer_type(name != NULL
7289 ? static_cast<Type*>(name)
7290 : static_cast<Type*>(this));
7292 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7293 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7294 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7295 gogo->add_statement(p1);
7297 ref = Expression::make_var_reference(key2_arg, bloc);
7298 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7299 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7300 gogo->add_statement(p2);
7302 // Loop over the array elements.
7303 // for i = range a
7304 Type* int_type = Type::lookup_integer_type("int");
7305 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7306 gogo->add_statement(index);
7308 Expression* iref = Expression::make_temporary_reference(index, bloc);
7309 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7310 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7311 NULL,
7312 aref,
7313 bloc);
7315 gogo->start_block(bloc);
7317 // Compare element in P1 and P2.
7318 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7319 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7320 ref = Expression::make_temporary_reference(index, bloc);
7321 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7323 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7324 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7325 ref = Expression::make_temporary_reference(index, bloc);
7326 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7328 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7330 // If the elements are not equal, return false.
7331 gogo->start_block(bloc);
7332 Expression_list* vals = new Expression_list();
7333 vals->push_back(Expression::make_boolean(false, bloc));
7334 Statement* s = Statement::make_return_statement(vals, bloc);
7335 gogo->add_statement(s);
7336 Block* then_block = gogo->finish_block(bloc);
7338 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7339 gogo->add_statement(s);
7341 Block* statements = gogo->finish_block(bloc);
7343 for_range->add_statements(statements);
7344 gogo->add_statement(for_range);
7346 // All the elements are equal, so return true.
7347 vals = new Expression_list();
7348 vals->push_back(Expression::make_boolean(true, bloc));
7349 s = Statement::make_return_statement(vals, bloc);
7350 gogo->add_statement(s);
7353 // Get the backend representation of the fields of a slice. This is
7354 // not declared in types.h so that types.h doesn't have to #include
7355 // backend.h.
7357 // We use int for the count and capacity fields. This matches 6g.
7358 // The language more or less assumes that we can't allocate space of a
7359 // size which does not fit in int.
7361 static void
7362 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7363 std::vector<Backend::Btyped_identifier>* bfields)
7365 bfields->resize(3);
7367 Type* pet = Type::make_pointer_type(type->element_type());
7368 Btype* pbet = (use_placeholder
7369 ? pet->get_backend_placeholder(gogo)
7370 : pet->get_backend(gogo));
7371 Location ploc = Linemap::predeclared_location();
7373 Backend::Btyped_identifier* p = &(*bfields)[0];
7374 p->name = "__values";
7375 p->btype = pbet;
7376 p->location = ploc;
7378 Type* int_type = Type::lookup_integer_type("int");
7380 p = &(*bfields)[1];
7381 p->name = "__count";
7382 p->btype = int_type->get_backend(gogo);
7383 p->location = ploc;
7385 p = &(*bfields)[2];
7386 p->name = "__capacity";
7387 p->btype = int_type->get_backend(gogo);
7388 p->location = ploc;
7391 // Get the backend representation for the type of this array. A fixed array is
7392 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7393 // just like an array in C. An open array is a struct with three
7394 // fields: a data pointer, the length, and the capacity.
7396 Btype*
7397 Array_type::do_get_backend(Gogo* gogo)
7399 if (this->length_ == NULL)
7401 std::vector<Backend::Btyped_identifier> bfields;
7402 get_backend_slice_fields(gogo, this, false, &bfields);
7403 return gogo->backend()->struct_type(bfields);
7405 else
7407 Btype* element = this->get_backend_element(gogo, false);
7408 Bexpression* len = this->get_backend_length(gogo);
7409 return gogo->backend()->array_type(element, len);
7413 // Return the backend representation of the element type.
7415 Btype*
7416 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
7418 if (use_placeholder)
7419 return this->element_type_->get_backend_placeholder(gogo);
7420 else
7421 return this->element_type_->get_backend(gogo);
7424 // Return the backend representation of the length. The length may be
7425 // computed using a function call, so we must only evaluate it once.
7427 Bexpression*
7428 Array_type::get_backend_length(Gogo* gogo)
7430 go_assert(this->length_ != NULL);
7431 if (this->blength_ == NULL)
7433 if (this->length_->is_error_expression())
7435 this->blength_ = gogo->backend()->error_expression();
7436 return this->blength_;
7438 Numeric_constant nc;
7439 mpz_t val;
7440 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
7442 if (mpz_sgn(val) < 0)
7444 this->blength_ = gogo->backend()->error_expression();
7445 return this->blength_;
7447 Type* t = nc.type();
7448 if (t == NULL)
7449 t = Type::lookup_integer_type("int");
7450 else if (t->is_abstract())
7451 t = t->make_non_abstract_type();
7452 Btype* btype = t->get_backend(gogo);
7453 this->blength_ =
7454 gogo->backend()->integer_constant_expression(btype, val);
7455 mpz_clear(val);
7457 else
7459 // Make up a translation context for the array length
7460 // expression. FIXME: This won't work in general.
7461 Translate_context context(gogo, NULL, NULL, NULL);
7462 this->blength_ = this->length_->get_backend(&context);
7464 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
7465 this->blength_ =
7466 gogo->backend()->convert_expression(ibtype, this->blength_,
7467 this->length_->location());
7470 return this->blength_;
7473 // Finish backend representation of the array.
7475 void
7476 Array_type::finish_backend_element(Gogo* gogo)
7478 Type* et = this->array_type()->element_type();
7479 et->get_backend(gogo);
7480 if (this->is_slice_type())
7482 // This relies on the fact that we always use the same
7483 // structure for a pointer to any given type.
7484 Type* pet = Type::make_pointer_type(et);
7485 pet->get_backend(gogo);
7489 // Return an expression for a pointer to the values in ARRAY.
7491 Expression*
7492 Array_type::get_value_pointer(Gogo*, Expression* array, bool is_lvalue) const
7494 if (this->length() != NULL)
7496 // Fixed array.
7497 go_assert(array->type()->array_type() != NULL);
7498 Type* etype = array->type()->array_type()->element_type();
7499 array = Expression::make_unary(OPERATOR_AND, array, array->location());
7500 return Expression::make_cast(Type::make_pointer_type(etype), array,
7501 array->location());
7504 // Slice.
7506 if (is_lvalue)
7508 Temporary_reference_expression* tref =
7509 array->temporary_reference_expression();
7510 Var_expression* ve = array->var_expression();
7511 if (tref != NULL)
7513 tref = tref->copy()->temporary_reference_expression();
7514 tref->set_is_lvalue();
7515 array = tref;
7517 else if (ve != NULL)
7519 ve = new Var_expression(ve->named_object(), ve->location());
7520 array = ve;
7524 return Expression::make_slice_info(array,
7525 Expression::SLICE_INFO_VALUE_POINTER,
7526 array->location());
7529 // Return an expression for the length of the array ARRAY which has this
7530 // type.
7532 Expression*
7533 Array_type::get_length(Gogo*, Expression* array) const
7535 if (this->length_ != NULL)
7536 return this->length_;
7538 // This is a slice. We need to read the length field.
7539 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
7540 array->location());
7543 // Return an expression for the capacity of the array ARRAY which has this
7544 // type.
7546 Expression*
7547 Array_type::get_capacity(Gogo*, Expression* array) const
7549 if (this->length_ != NULL)
7550 return this->length_;
7552 // This is a slice. We need to read the capacity field.
7553 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
7554 array->location());
7557 // Export.
7559 void
7560 Array_type::do_export(Export* exp) const
7562 exp->write_c_string("[");
7563 if (this->length_ != NULL)
7564 this->length_->export_expression(exp);
7565 exp->write_c_string("] ");
7566 exp->write_type(this->element_type_);
7569 // Import.
7571 Array_type*
7572 Array_type::do_import(Import* imp)
7574 imp->require_c_string("[");
7575 Expression* length;
7576 if (imp->peek_char() == ']')
7577 length = NULL;
7578 else
7579 length = Expression::import_expression(imp);
7580 imp->require_c_string("] ");
7581 Type* element_type = imp->read_type();
7582 return Type::make_array_type(element_type, length);
7585 // The type of an array type descriptor.
7587 Type*
7588 Array_type::make_array_type_descriptor_type()
7590 static Type* ret;
7591 if (ret == NULL)
7593 Type* tdt = Type::make_type_descriptor_type();
7594 Type* ptdt = Type::make_type_descriptor_ptr_type();
7596 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7598 Struct_type* sf =
7599 Type::make_builtin_struct_type(4,
7600 "", tdt,
7601 "elem", ptdt,
7602 "slice", ptdt,
7603 "len", uintptr_type);
7605 ret = Type::make_builtin_named_type("ArrayType", sf);
7608 return ret;
7611 // The type of an slice type descriptor.
7613 Type*
7614 Array_type::make_slice_type_descriptor_type()
7616 static Type* ret;
7617 if (ret == NULL)
7619 Type* tdt = Type::make_type_descriptor_type();
7620 Type* ptdt = Type::make_type_descriptor_ptr_type();
7622 Struct_type* sf =
7623 Type::make_builtin_struct_type(2,
7624 "", tdt,
7625 "elem", ptdt);
7627 ret = Type::make_builtin_named_type("SliceType", sf);
7630 return ret;
7633 // Build a type descriptor for an array/slice type.
7635 Expression*
7636 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
7638 if (this->length_ != NULL)
7639 return this->array_type_descriptor(gogo, name);
7640 else
7641 return this->slice_type_descriptor(gogo, name);
7644 // Build a type descriptor for an array type.
7646 Expression*
7647 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
7649 Location bloc = Linemap::predeclared_location();
7651 Type* atdt = Array_type::make_array_type_descriptor_type();
7653 const Struct_field_list* fields = atdt->struct_type()->fields();
7655 Expression_list* vals = new Expression_list();
7656 vals->reserve(3);
7658 Struct_field_list::const_iterator p = fields->begin();
7659 go_assert(p->is_field_name("_type"));
7660 vals->push_back(this->type_descriptor_constructor(gogo,
7661 RUNTIME_TYPE_KIND_ARRAY,
7662 name, NULL, true));
7664 ++p;
7665 go_assert(p->is_field_name("elem"));
7666 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7668 ++p;
7669 go_assert(p->is_field_name("slice"));
7670 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
7671 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
7673 ++p;
7674 go_assert(p->is_field_name("len"));
7675 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
7677 ++p;
7678 go_assert(p == fields->end());
7680 return Expression::make_struct_composite_literal(atdt, vals, bloc);
7683 // Build a type descriptor for a slice type.
7685 Expression*
7686 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
7688 Location bloc = Linemap::predeclared_location();
7690 Type* stdt = Array_type::make_slice_type_descriptor_type();
7692 const Struct_field_list* fields = stdt->struct_type()->fields();
7694 Expression_list* vals = new Expression_list();
7695 vals->reserve(2);
7697 Struct_field_list::const_iterator p = fields->begin();
7698 go_assert(p->is_field_name("_type"));
7699 vals->push_back(this->type_descriptor_constructor(gogo,
7700 RUNTIME_TYPE_KIND_SLICE,
7701 name, NULL, true));
7703 ++p;
7704 go_assert(p->is_field_name("elem"));
7705 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
7707 ++p;
7708 go_assert(p == fields->end());
7710 return Expression::make_struct_composite_literal(stdt, vals, bloc);
7713 // Reflection string.
7715 void
7716 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
7718 ret->push_back('[');
7719 if (this->length_ != NULL)
7721 Numeric_constant nc;
7722 if (!this->length_->numeric_constant_value(&nc))
7724 go_assert(saw_errors());
7725 return;
7727 mpz_t val;
7728 if (!nc.to_int(&val))
7730 go_assert(saw_errors());
7731 return;
7733 char* s = mpz_get_str(NULL, 10, val);
7734 ret->append(s);
7735 free(s);
7736 mpz_clear(val);
7738 ret->push_back(']');
7740 this->append_reflection(this->element_type_, gogo, ret);
7743 // Make an array type.
7745 Array_type*
7746 Type::make_array_type(Type* element_type, Expression* length)
7748 return new Array_type(element_type, length);
7751 // Class Map_type.
7753 Named_object* Map_type::zero_value;
7754 int64_t Map_type::zero_value_size;
7755 int64_t Map_type::zero_value_align;
7757 // If this map requires the "fat" functions, return the pointer to
7758 // pass as the zero value to those functions. Otherwise, in the
7759 // normal case, return NULL. The map requires the "fat" functions if
7760 // the value size is larger than max_zero_size bytes. max_zero_size
7761 // must match maxZero in libgo/go/runtime/hashmap.go.
7763 Expression*
7764 Map_type::fat_zero_value(Gogo* gogo)
7766 int64_t valsize;
7767 if (!this->val_type_->backend_type_size(gogo, &valsize))
7769 go_assert(saw_errors());
7770 return NULL;
7772 if (valsize <= Map_type::max_zero_size)
7773 return NULL;
7775 if (Map_type::zero_value_size < valsize)
7776 Map_type::zero_value_size = valsize;
7778 int64_t valalign;
7779 if (!this->val_type_->backend_type_align(gogo, &valalign))
7781 go_assert(saw_errors());
7782 return NULL;
7785 if (Map_type::zero_value_align < valalign)
7786 Map_type::zero_value_align = valalign;
7788 Location bloc = Linemap::predeclared_location();
7790 if (Map_type::zero_value == NULL)
7792 // The final type will be set in backend_zero_value.
7793 Type* uint8_type = Type::lookup_integer_type("uint8");
7794 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
7795 Array_type* array_type = Type::make_array_type(uint8_type, size);
7796 array_type->set_is_array_incomparable();
7797 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
7798 std::string name = gogo->map_zero_value_name();
7799 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
7802 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
7803 z = Expression::make_unary(OPERATOR_AND, z, bloc);
7804 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
7805 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
7806 return z;
7809 // Return whether VAR is the map zero value.
7811 bool
7812 Map_type::is_zero_value(Variable* var)
7814 return (Map_type::zero_value != NULL
7815 && Map_type::zero_value->var_value() == var);
7818 // Return the backend representation for the zero value.
7820 Bvariable*
7821 Map_type::backend_zero_value(Gogo* gogo)
7823 Location bloc = Linemap::predeclared_location();
7825 go_assert(Map_type::zero_value != NULL);
7827 Type* uint8_type = Type::lookup_integer_type("uint8");
7828 Btype* buint8_type = uint8_type->get_backend(gogo);
7830 Type* int_type = Type::lookup_integer_type("int");
7832 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
7833 int_type, bloc);
7834 Translate_context context(gogo, NULL, NULL, NULL);
7835 Bexpression* blength = e->get_backend(&context);
7837 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
7839 std::string zname = Map_type::zero_value->name();
7840 std::string asm_name(go_selectively_encode_id(zname));
7841 Bvariable* zvar =
7842 gogo->backend()->implicit_variable(zname, asm_name,
7843 barray_type, false, false, true,
7844 Map_type::zero_value_align);
7845 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
7846 false, false, true, NULL);
7847 return zvar;
7850 // Traversal.
7853 Map_type::do_traverse(Traverse* traverse)
7855 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
7856 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
7857 return TRAVERSE_EXIT;
7858 return TRAVERSE_CONTINUE;
7861 // Check that the map type is OK.
7863 bool
7864 Map_type::do_verify()
7866 // The runtime support uses "map[void]void".
7867 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
7868 go_error_at(this->location_, "invalid map key type");
7869 if (!this->key_type_->in_heap())
7870 go_error_at(this->location_, "go:notinheap map key not allowed");
7871 if (!this->val_type_->in_heap())
7872 go_error_at(this->location_, "go:notinheap map value not allowed");
7873 return true;
7876 // Whether two map types are identical.
7878 bool
7879 Map_type::is_identical(const Map_type* t, Cmp_tags cmp_tags,
7880 bool errors_are_identical) const
7882 return (Type::are_identical_cmp_tags(this->key_type(), t->key_type(),
7883 cmp_tags, errors_are_identical, NULL)
7884 && Type::are_identical_cmp_tags(this->val_type(), t->val_type(),
7885 cmp_tags, errors_are_identical,
7886 NULL));
7889 // Hash code.
7891 unsigned int
7892 Map_type::do_hash_for_method(Gogo* gogo) const
7894 return (this->key_type_->hash_for_method(gogo)
7895 + this->val_type_->hash_for_method(gogo)
7896 + 2);
7899 // Get the backend representation for a map type. A map type is
7900 // represented as a pointer to a struct. The struct is hmap in
7901 // runtime/hashmap.go.
7903 Btype*
7904 Map_type::do_get_backend(Gogo* gogo)
7906 static Btype* backend_map_type;
7907 if (backend_map_type == NULL)
7909 std::vector<Backend::Btyped_identifier> bfields(9);
7911 Location bloc = Linemap::predeclared_location();
7913 Type* int_type = Type::lookup_integer_type("int");
7914 bfields[0].name = "count";
7915 bfields[0].btype = int_type->get_backend(gogo);
7916 bfields[0].location = bloc;
7918 Type* uint8_type = Type::lookup_integer_type("uint8");
7919 bfields[1].name = "flags";
7920 bfields[1].btype = uint8_type->get_backend(gogo);
7921 bfields[1].location = bloc;
7923 bfields[2].name = "B";
7924 bfields[2].btype = bfields[1].btype;
7925 bfields[2].location = bloc;
7927 Type* uint16_type = Type::lookup_integer_type("uint16");
7928 bfields[3].name = "noverflow";
7929 bfields[3].btype = uint16_type->get_backend(gogo);
7930 bfields[3].location = bloc;
7932 Type* uint32_type = Type::lookup_integer_type("uint32");
7933 bfields[4].name = "hash0";
7934 bfields[4].btype = uint32_type->get_backend(gogo);
7935 bfields[4].location = bloc;
7937 Btype* bvt = gogo->backend()->void_type();
7938 Btype* bpvt = gogo->backend()->pointer_type(bvt);
7939 bfields[5].name = "buckets";
7940 bfields[5].btype = bpvt;
7941 bfields[5].location = bloc;
7943 bfields[6].name = "oldbuckets";
7944 bfields[6].btype = bpvt;
7945 bfields[6].location = bloc;
7947 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7948 bfields[7].name = "nevacuate";
7949 bfields[7].btype = uintptr_type->get_backend(gogo);
7950 bfields[7].location = bloc;
7952 bfields[8].name = "extra";
7953 bfields[8].btype = bpvt;
7954 bfields[8].location = bloc;
7956 Btype *bt = gogo->backend()->struct_type(bfields);
7957 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
7958 backend_map_type = gogo->backend()->pointer_type(bt);
7960 return backend_map_type;
7963 // The type of a map type descriptor.
7965 Type*
7966 Map_type::make_map_type_descriptor_type()
7968 static Type* ret;
7969 if (ret == NULL)
7971 Type* tdt = Type::make_type_descriptor_type();
7972 Type* ptdt = Type::make_type_descriptor_ptr_type();
7973 Type* uint8_type = Type::lookup_integer_type("uint8");
7974 Type* uint16_type = Type::lookup_integer_type("uint16");
7975 Type* bool_type = Type::lookup_bool_type();
7977 Struct_type* sf =
7978 Type::make_builtin_struct_type(11,
7979 "", tdt,
7980 "key", ptdt,
7981 "elem", ptdt,
7982 "bucket", ptdt,
7983 "keysize", uint8_type,
7984 "indirectkey", bool_type,
7985 "valuesize", uint8_type,
7986 "indirectvalue", bool_type,
7987 "bucketsize", uint16_type,
7988 "reflexivekey", bool_type,
7989 "needkeyupdate", bool_type);
7991 ret = Type::make_builtin_named_type("MapType", sf);
7994 return ret;
7997 // Build a type descriptor for a map type.
7999 Expression*
8000 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8002 Location bloc = Linemap::predeclared_location();
8004 Type* mtdt = Map_type::make_map_type_descriptor_type();
8005 Type* uint8_type = Type::lookup_integer_type("uint8");
8006 Type* uint16_type = Type::lookup_integer_type("uint16");
8008 int64_t keysize;
8009 if (!this->key_type_->backend_type_size(gogo, &keysize))
8011 go_error_at(this->location_, "error determining map key type size");
8012 return Expression::make_error(this->location_);
8015 int64_t valsize;
8016 if (!this->val_type_->backend_type_size(gogo, &valsize))
8018 go_error_at(this->location_, "error determining map value type size");
8019 return Expression::make_error(this->location_);
8022 int64_t ptrsize;
8023 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8025 go_assert(saw_errors());
8026 return Expression::make_error(this->location_);
8029 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8030 if (bucket_type == NULL)
8032 go_assert(saw_errors());
8033 return Expression::make_error(this->location_);
8036 int64_t bucketsize;
8037 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8039 go_assert(saw_errors());
8040 return Expression::make_error(this->location_);
8043 const Struct_field_list* fields = mtdt->struct_type()->fields();
8045 Expression_list* vals = new Expression_list();
8046 vals->reserve(12);
8048 Struct_field_list::const_iterator p = fields->begin();
8049 go_assert(p->is_field_name("_type"));
8050 vals->push_back(this->type_descriptor_constructor(gogo,
8051 RUNTIME_TYPE_KIND_MAP,
8052 name, NULL, true));
8054 ++p;
8055 go_assert(p->is_field_name("key"));
8056 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8058 ++p;
8059 go_assert(p->is_field_name("elem"));
8060 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8062 ++p;
8063 go_assert(p->is_field_name("bucket"));
8064 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8066 ++p;
8067 go_assert(p->is_field_name("keysize"));
8068 if (keysize > Map_type::max_key_size)
8069 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8070 else
8071 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8073 ++p;
8074 go_assert(p->is_field_name("indirectkey"));
8075 vals->push_back(Expression::make_boolean(keysize > Map_type::max_key_size,
8076 bloc));
8078 ++p;
8079 go_assert(p->is_field_name("valuesize"));
8080 if (valsize > Map_type::max_val_size)
8081 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8082 else
8083 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8085 ++p;
8086 go_assert(p->is_field_name("indirectvalue"));
8087 vals->push_back(Expression::make_boolean(valsize > Map_type::max_val_size,
8088 bloc));
8090 ++p;
8091 go_assert(p->is_field_name("bucketsize"));
8092 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8093 bloc));
8095 ++p;
8096 go_assert(p->is_field_name("reflexivekey"));
8097 vals->push_back(Expression::make_boolean(this->key_type_->is_reflexive(),
8098 bloc));
8100 ++p;
8101 go_assert(p->is_field_name("needkeyupdate"));
8102 vals->push_back(Expression::make_boolean(this->key_type_->needs_key_update(),
8103 bloc));
8105 ++p;
8106 go_assert(p == fields->end());
8108 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8111 // Return the bucket type to use for a map type. This must correspond
8112 // to libgo/go/runtime/hashmap.go.
8114 Type*
8115 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8117 if (this->bucket_type_ != NULL)
8118 return this->bucket_type_;
8120 Type* key_type = this->key_type_;
8121 if (keysize > Map_type::max_key_size)
8122 key_type = Type::make_pointer_type(key_type);
8124 Type* val_type = this->val_type_;
8125 if (valsize > Map_type::max_val_size)
8126 val_type = Type::make_pointer_type(val_type);
8128 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8129 NULL, this->location_);
8131 Type* uint8_type = Type::lookup_integer_type("uint8");
8132 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8133 topbits_type->set_is_array_incomparable();
8134 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8135 keys_type->set_is_array_incomparable();
8136 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8137 values_type->set_is_array_incomparable();
8139 // If keys and values have no pointers, the map implementation can
8140 // keep a list of overflow pointers on the side so that buckets can
8141 // be marked as having no pointers. Arrange for the bucket to have
8142 // no pointers by changing the type of the overflow field to uintptr
8143 // in this case. See comment on the hmap.overflow field in
8144 // libgo/go/runtime/hashmap.go.
8145 Type* overflow_type;
8146 if (!key_type->has_pointer() && !val_type->has_pointer())
8147 overflow_type = Type::lookup_integer_type("uintptr");
8148 else
8150 // This should really be a pointer to the bucket type itself,
8151 // but that would require us to construct a Named_type for it to
8152 // give it a way to refer to itself. Since nothing really cares
8153 // (except perhaps for someone using a debugger) just use an
8154 // unsafe pointer.
8155 overflow_type = Type::make_pointer_type(Type::make_void_type());
8158 // Make sure the overflow pointer is the last memory in the struct,
8159 // because the runtime assumes it can use size-ptrSize as the offset
8160 // of the overflow pointer. We double-check that property below
8161 // once the offsets and size are computed.
8163 int64_t topbits_field_size, topbits_field_align;
8164 int64_t keys_field_size, keys_field_align;
8165 int64_t values_field_size, values_field_align;
8166 int64_t overflow_field_size, overflow_field_align;
8167 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8168 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8169 || !keys_type->backend_type_size(gogo, &keys_field_size)
8170 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8171 || !values_type->backend_type_size(gogo, &values_field_size)
8172 || !values_type->backend_type_field_align(gogo, &values_field_align)
8173 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8174 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8176 go_assert(saw_errors());
8177 return NULL;
8180 Struct_type* ret;
8181 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8182 values_field_align);
8183 if (max_align <= overflow_field_align)
8184 ret = make_builtin_struct_type(4,
8185 "topbits", topbits_type,
8186 "keys", keys_type,
8187 "values", values_type,
8188 "overflow", overflow_type);
8189 else
8191 size_t off = topbits_field_size;
8192 off = ((off + keys_field_align - 1)
8193 &~ static_cast<size_t>(keys_field_align - 1));
8194 off += keys_field_size;
8195 off = ((off + values_field_align - 1)
8196 &~ static_cast<size_t>(values_field_align - 1));
8197 off += values_field_size;
8199 int64_t padded_overflow_field_size =
8200 ((overflow_field_size + max_align - 1)
8201 &~ static_cast<size_t>(max_align - 1));
8203 size_t ovoff = off;
8204 ovoff = ((ovoff + max_align - 1)
8205 &~ static_cast<size_t>(max_align - 1));
8206 size_t pad = (ovoff - off
8207 + padded_overflow_field_size - overflow_field_size);
8209 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8210 this->location_);
8211 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8212 pad_type->set_is_array_incomparable();
8214 ret = make_builtin_struct_type(5,
8215 "topbits", topbits_type,
8216 "keys", keys_type,
8217 "values", values_type,
8218 "pad", pad_type,
8219 "overflow", overflow_type);
8222 // Verify that the overflow field is just before the end of the
8223 // bucket type.
8225 Btype* btype = ret->get_backend(gogo);
8226 int64_t offset = gogo->backend()->type_field_offset(btype,
8227 ret->field_count() - 1);
8228 int64_t size;
8229 if (!ret->backend_type_size(gogo, &size))
8231 go_assert(saw_errors());
8232 return NULL;
8235 int64_t ptr_size;
8236 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8238 go_assert(saw_errors());
8239 return NULL;
8242 go_assert(offset + ptr_size == size);
8244 ret->set_is_struct_incomparable();
8246 this->bucket_type_ = ret;
8247 return ret;
8250 // Return the hashmap type for a map type.
8252 Type*
8253 Map_type::hmap_type(Type* bucket_type)
8255 if (this->hmap_type_ != NULL)
8256 return this->hmap_type_;
8258 Type* int_type = Type::lookup_integer_type("int");
8259 Type* uint8_type = Type::lookup_integer_type("uint8");
8260 Type* uint16_type = Type::lookup_integer_type("uint16");
8261 Type* uint32_type = Type::lookup_integer_type("uint32");
8262 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8263 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8265 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8267 Struct_type* ret = make_builtin_struct_type(9,
8268 "count", int_type,
8269 "flags", uint8_type,
8270 "B", uint8_type,
8271 "noverflow", uint16_type,
8272 "hash0", uint32_type,
8273 "buckets", ptr_bucket_type,
8274 "oldbuckets", ptr_bucket_type,
8275 "nevacuate", uintptr_type,
8276 "extra", void_ptr_type);
8277 ret->set_is_struct_incomparable();
8278 this->hmap_type_ = ret;
8279 return ret;
8282 // Return the iterator type for a map type. This is the type of the
8283 // value used when doing a range over a map.
8285 Type*
8286 Map_type::hiter_type(Gogo* gogo)
8288 if (this->hiter_type_ != NULL)
8289 return this->hiter_type_;
8291 int64_t keysize, valsize;
8292 if (!this->key_type_->backend_type_size(gogo, &keysize)
8293 || !this->val_type_->backend_type_size(gogo, &valsize))
8295 go_assert(saw_errors());
8296 return NULL;
8299 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8300 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8301 Type* uint8_type = Type::lookup_integer_type("uint8");
8302 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8303 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8304 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8305 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8306 Type* hmap_type = this->hmap_type(bucket_type);
8307 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8308 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8309 Type* bool_type = Type::lookup_bool_type();
8311 Struct_type* ret = make_builtin_struct_type(15,
8312 "key", key_ptr_type,
8313 "val", val_ptr_type,
8314 "t", uint8_ptr_type,
8315 "h", hmap_ptr_type,
8316 "buckets", bucket_ptr_type,
8317 "bptr", bucket_ptr_type,
8318 "overflow", void_ptr_type,
8319 "oldoverflow", void_ptr_type,
8320 "startBucket", uintptr_type,
8321 "offset", uint8_type,
8322 "wrapped", bool_type,
8323 "B", uint8_type,
8324 "i", uint8_type,
8325 "bucket", uintptr_type,
8326 "checkBucket", uintptr_type);
8327 ret->set_is_struct_incomparable();
8328 this->hiter_type_ = ret;
8329 return ret;
8332 // Reflection string for a map.
8334 void
8335 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8337 ret->append("map[");
8338 this->append_reflection(this->key_type_, gogo, ret);
8339 ret->append("]");
8340 this->append_reflection(this->val_type_, gogo, ret);
8343 // Export a map type.
8345 void
8346 Map_type::do_export(Export* exp) const
8348 exp->write_c_string("map [");
8349 exp->write_type(this->key_type_);
8350 exp->write_c_string("] ");
8351 exp->write_type(this->val_type_);
8354 // Import a map type.
8356 Map_type*
8357 Map_type::do_import(Import* imp)
8359 imp->require_c_string("map [");
8360 Type* key_type = imp->read_type();
8361 imp->require_c_string("] ");
8362 Type* val_type = imp->read_type();
8363 return Type::make_map_type(key_type, val_type, imp->location());
8366 // Make a map type.
8368 Map_type*
8369 Type::make_map_type(Type* key_type, Type* val_type, Location location)
8371 return new Map_type(key_type, val_type, location);
8374 // Class Channel_type.
8376 // Verify.
8378 bool
8379 Channel_type::do_verify()
8381 // We have no location for this error, but this is not something the
8382 // ordinary user will see.
8383 if (!this->element_type_->in_heap())
8384 go_error_at(Linemap::unknown_location(),
8385 "chan of go:notinheap type not allowed");
8386 return true;
8389 // Hash code.
8391 unsigned int
8392 Channel_type::do_hash_for_method(Gogo* gogo) const
8394 unsigned int ret = 0;
8395 if (this->may_send_)
8396 ret += 1;
8397 if (this->may_receive_)
8398 ret += 2;
8399 if (this->element_type_ != NULL)
8400 ret += this->element_type_->hash_for_method(gogo) << 2;
8401 return ret << 3;
8404 // Whether this type is the same as T.
8406 bool
8407 Channel_type::is_identical(const Channel_type* t, Cmp_tags cmp_tags,
8408 bool errors_are_identical) const
8410 if (!Type::are_identical_cmp_tags(this->element_type(), t->element_type(),
8411 cmp_tags, errors_are_identical, NULL))
8412 return false;
8413 return (this->may_send_ == t->may_send_
8414 && this->may_receive_ == t->may_receive_);
8417 // Return the backend representation for a channel type. A channel is a pointer
8418 // to a __go_channel struct. The __go_channel struct is defined in
8419 // libgo/runtime/channel.h.
8421 Btype*
8422 Channel_type::do_get_backend(Gogo* gogo)
8424 static Btype* backend_channel_type;
8425 if (backend_channel_type == NULL)
8427 std::vector<Backend::Btyped_identifier> bfields;
8428 Btype* bt = gogo->backend()->struct_type(bfields);
8429 bt = gogo->backend()->named_type("__go_channel", bt,
8430 Linemap::predeclared_location());
8431 backend_channel_type = gogo->backend()->pointer_type(bt);
8433 return backend_channel_type;
8436 // Build a type descriptor for a channel type.
8438 Type*
8439 Channel_type::make_chan_type_descriptor_type()
8441 static Type* ret;
8442 if (ret == NULL)
8444 Type* tdt = Type::make_type_descriptor_type();
8445 Type* ptdt = Type::make_type_descriptor_ptr_type();
8447 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8449 Struct_type* sf =
8450 Type::make_builtin_struct_type(3,
8451 "", tdt,
8452 "elem", ptdt,
8453 "dir", uintptr_type);
8455 ret = Type::make_builtin_named_type("ChanType", sf);
8458 return ret;
8461 // Build a type descriptor for a map type.
8463 Expression*
8464 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8466 Location bloc = Linemap::predeclared_location();
8468 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
8470 const Struct_field_list* fields = ctdt->struct_type()->fields();
8472 Expression_list* vals = new Expression_list();
8473 vals->reserve(3);
8475 Struct_field_list::const_iterator p = fields->begin();
8476 go_assert(p->is_field_name("_type"));
8477 vals->push_back(this->type_descriptor_constructor(gogo,
8478 RUNTIME_TYPE_KIND_CHAN,
8479 name, NULL, true));
8481 ++p;
8482 go_assert(p->is_field_name("elem"));
8483 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8485 ++p;
8486 go_assert(p->is_field_name("dir"));
8487 // These bits must match the ones in libgo/runtime/go-type.h.
8488 int val = 0;
8489 if (this->may_receive_)
8490 val |= 1;
8491 if (this->may_send_)
8492 val |= 2;
8493 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
8495 ++p;
8496 go_assert(p == fields->end());
8498 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
8501 // Reflection string.
8503 void
8504 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
8506 if (!this->may_send_)
8507 ret->append("<-");
8508 ret->append("chan");
8509 if (!this->may_receive_)
8510 ret->append("<-");
8511 ret->push_back(' ');
8512 this->append_reflection(this->element_type_, gogo, ret);
8515 // Export.
8517 void
8518 Channel_type::do_export(Export* exp) const
8520 exp->write_c_string("chan ");
8521 if (this->may_send_ && !this->may_receive_)
8522 exp->write_c_string("-< ");
8523 else if (this->may_receive_ && !this->may_send_)
8524 exp->write_c_string("<- ");
8525 exp->write_type(this->element_type_);
8528 // Import.
8530 Channel_type*
8531 Channel_type::do_import(Import* imp)
8533 imp->require_c_string("chan ");
8535 bool may_send;
8536 bool may_receive;
8537 if (imp->match_c_string("-< "))
8539 imp->advance(3);
8540 may_send = true;
8541 may_receive = false;
8543 else if (imp->match_c_string("<- "))
8545 imp->advance(3);
8546 may_receive = true;
8547 may_send = false;
8549 else
8551 may_send = true;
8552 may_receive = true;
8555 Type* element_type = imp->read_type();
8557 return Type::make_channel_type(may_send, may_receive, element_type);
8560 // Return the type that the runtime package uses for one case of a
8561 // select statement. An array of values of this type is allocated on
8562 // the stack. This must match scase in libgo/go/runtime/select.go.
8564 Type*
8565 Channel_type::select_case_type()
8567 static Struct_type* scase_type;
8568 if (scase_type == NULL)
8570 Type* unsafe_pointer_type =
8571 Type::make_pointer_type(Type::make_void_type());
8572 Type* uint16_type = Type::lookup_integer_type("uint16");
8573 Type* int64_type = Type::lookup_integer_type("int64");
8574 scase_type =
8575 Type::make_builtin_struct_type(4,
8576 "c", unsafe_pointer_type,
8577 "elem", unsafe_pointer_type,
8578 "kind", uint16_type,
8579 "releasetime", int64_type);
8580 scase_type->set_is_struct_incomparable();
8582 return scase_type;
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_)
10763 return gogo->backend()->circular_pointer_type(bt, true);
10764 this->seen_in_get_backend_ = true;
10765 bt1 = Type::get_named_base_btype(gogo, base);
10766 this->seen_in_get_backend_ = false;
10767 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10768 bt = gogo->backend()->error_type();
10769 return bt;
10771 case TYPE_POINTER:
10772 // Don't build a circular data structure. GENERIC can't handle
10773 // it.
10774 if (this->seen_in_get_backend_)
10775 return gogo->backend()->circular_pointer_type(bt, false);
10776 this->seen_in_get_backend_ = true;
10777 bt1 = Type::get_named_base_btype(gogo, base);
10778 this->seen_in_get_backend_ = false;
10779 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
10780 bt = gogo->backend()->error_type();
10781 return bt;
10783 default:
10784 case TYPE_SINK:
10785 case TYPE_CALL_MULTIPLE_RESULT:
10786 case TYPE_NAMED:
10787 case TYPE_FORWARD:
10788 go_unreachable();
10791 go_unreachable();
10794 // Build a type descriptor for a named type.
10796 Expression*
10797 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10799 if (this->is_error_)
10800 return Expression::make_error(this->location_);
10801 if (name == NULL && this->is_alias_)
10803 if (this->seen_alias_)
10804 return Expression::make_error(this->location_);
10805 this->seen_alias_ = true;
10806 Expression* ret = this->type_->type_descriptor(gogo, NULL);
10807 this->seen_alias_ = false;
10808 return ret;
10811 // If NAME is not NULL, then we don't really want the type
10812 // descriptor for this type; we want the descriptor for the
10813 // underlying type, giving it the name NAME.
10814 return this->named_type_descriptor(gogo, this->type_,
10815 name == NULL ? this : name);
10818 // Add to the reflection string. This is used mostly for the name of
10819 // the type used in a type descriptor, not for actual reflection
10820 // strings.
10822 void
10823 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
10825 this->append_reflection_type_name(gogo, false, ret);
10828 // Add to the reflection string. For an alias we normally use the
10829 // real name, but if USE_ALIAS is true we use the alias name itself.
10831 void
10832 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
10833 std::string* ret) const
10835 if (this->is_error_)
10836 return;
10837 if (this->is_alias_ && !use_alias)
10839 if (this->seen_alias_)
10840 return;
10841 this->seen_alias_ = true;
10842 this->append_reflection(this->type_, gogo, ret);
10843 this->seen_alias_ = false;
10844 return;
10846 if (!this->is_builtin())
10848 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
10849 // make a unique reflection string, so that the type
10850 // canonicalization in the reflect package will work. In order
10851 // to be compatible with the gc compiler, we put tabs into the
10852 // package path, so that the reflect methods can discard it.
10853 const Package* package = this->named_object_->package();
10854 ret->push_back('\t');
10855 ret->append(package != NULL
10856 ? package->pkgpath_symbol()
10857 : gogo->pkgpath_symbol());
10858 ret->push_back('\t');
10859 ret->append(package != NULL
10860 ? package->package_name()
10861 : gogo->package_name());
10862 ret->push_back('.');
10864 if (this->in_function_ != NULL)
10866 ret->push_back('\t');
10867 const Typed_identifier* rcvr =
10868 this->in_function_->func_value()->type()->receiver();
10869 if (rcvr != NULL)
10871 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
10872 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
10873 ret->push_back('.');
10875 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
10876 ret->push_back('$');
10877 if (this->in_function_index_ > 0)
10879 char buf[30];
10880 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
10881 ret->append(buf);
10882 ret->push_back('$');
10884 ret->push_back('\t');
10886 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
10889 // Export the type. This is called to export a global type.
10891 void
10892 Named_type::export_named_type(Export* exp, const std::string&) const
10894 // We don't need to write the name of the type here, because it will
10895 // be written by Export::write_type anyhow.
10896 exp->write_c_string("type ");
10897 exp->write_type(this);
10898 exp->write_c_string(";\n");
10901 // Import a named type.
10903 void
10904 Named_type::import_named_type(Import* imp, Named_type** ptype)
10906 imp->require_c_string("type ");
10907 Type *type = imp->read_type();
10908 *ptype = type->named_type();
10909 go_assert(*ptype != NULL);
10910 imp->require_c_string(";\n");
10913 // Export the type when it is referenced by another type. In this
10914 // case Export::export_type will already have issued the name.
10916 void
10917 Named_type::do_export(Export* exp) const
10919 exp->write_type(this->type_);
10921 // To save space, we only export the methods directly attached to
10922 // this type.
10923 Bindings* methods = this->local_methods_;
10924 if (methods == NULL)
10925 return;
10927 exp->write_c_string("\n");
10928 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
10929 p != methods->end_definitions();
10930 ++p)
10932 exp->write_c_string(" ");
10933 (*p)->export_named_object(exp);
10936 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
10937 p != methods->end_declarations();
10938 ++p)
10940 if (p->second->is_function_declaration())
10942 exp->write_c_string(" ");
10943 p->second->export_named_object(exp);
10948 // Make a named type.
10950 Named_type*
10951 Type::make_named_type(Named_object* named_object, Type* type,
10952 Location location)
10954 return new Named_type(named_object, type, location);
10957 // Finalize the methods for TYPE. It will be a named type or a struct
10958 // type. This sets *ALL_METHODS to the list of methods, and builds
10959 // all required stubs.
10961 void
10962 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
10963 Methods** all_methods)
10965 *all_methods = new Methods();
10966 std::vector<const Named_type*> seen;
10967 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
10968 if ((*all_methods)->empty())
10970 delete *all_methods;
10971 *all_methods = NULL;
10973 Type::build_stub_methods(gogo, type, *all_methods, location);
10976 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
10977 // build up the struct field indexes as we go. DEPTH is the depth of
10978 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
10979 // adding these methods for an anonymous field with pointer type.
10980 // NEEDS_STUB_METHOD is true if we need to use a stub method which
10981 // calls the real method. TYPES_SEEN is used to avoid infinite
10982 // recursion.
10984 void
10985 Type::add_methods_for_type(const Type* type,
10986 const Method::Field_indexes* field_indexes,
10987 unsigned int depth,
10988 bool is_embedded_pointer,
10989 bool needs_stub_method,
10990 std::vector<const Named_type*>* seen,
10991 Methods* methods)
10993 // Pointer types may not have methods.
10994 if (type->points_to() != NULL)
10995 return;
10997 const Named_type* nt = type->named_type();
10998 if (nt != NULL)
11000 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11001 p != seen->end();
11002 ++p)
11004 if (*p == nt)
11005 return;
11008 seen->push_back(nt);
11010 Type::add_local_methods_for_type(nt, field_indexes, depth,
11011 is_embedded_pointer, needs_stub_method,
11012 methods);
11015 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11016 is_embedded_pointer, needs_stub_method,
11017 seen, methods);
11019 // If we are called with depth > 0, then we are looking at an
11020 // anonymous field of a struct. If such a field has interface type,
11021 // then we need to add the interface methods. We don't want to add
11022 // them when depth == 0, because we will already handle them
11023 // following the usual rules for an interface type.
11024 if (depth > 0)
11025 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11027 if (nt != NULL)
11028 seen->pop_back();
11031 // Add the local methods for the named type NT to *METHODS. The
11032 // parameters are as for add_methods_to_type.
11034 void
11035 Type::add_local_methods_for_type(const Named_type* nt,
11036 const Method::Field_indexes* field_indexes,
11037 unsigned int depth,
11038 bool is_embedded_pointer,
11039 bool needs_stub_method,
11040 Methods* methods)
11042 const Bindings* local_methods = nt->local_methods();
11043 if (local_methods == NULL)
11044 return;
11046 for (Bindings::const_declarations_iterator p =
11047 local_methods->begin_declarations();
11048 p != local_methods->end_declarations();
11049 ++p)
11051 Named_object* no = p->second;
11052 bool is_value_method = (is_embedded_pointer
11053 || !Type::method_expects_pointer(no));
11054 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11055 (needs_stub_method || depth > 0));
11056 if (!methods->insert(no->name(), m))
11057 delete m;
11061 // Add the embedded methods for TYPE to *METHODS. These are the
11062 // methods attached to anonymous fields. The parameters are as for
11063 // add_methods_to_type.
11065 void
11066 Type::add_embedded_methods_for_type(const Type* type,
11067 const Method::Field_indexes* field_indexes,
11068 unsigned int depth,
11069 bool is_embedded_pointer,
11070 bool needs_stub_method,
11071 std::vector<const Named_type*>* seen,
11072 Methods* methods)
11074 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11075 // struct.
11076 const Struct_type* st = type->struct_type();
11077 if (st == NULL)
11078 return;
11080 const Struct_field_list* fields = st->fields();
11081 if (fields == NULL)
11082 return;
11084 unsigned int i = 0;
11085 for (Struct_field_list::const_iterator pf = fields->begin();
11086 pf != fields->end();
11087 ++pf, ++i)
11089 if (!pf->is_anonymous())
11090 continue;
11092 Type* ftype = pf->type();
11093 bool is_pointer = false;
11094 if (ftype->points_to() != NULL)
11096 ftype = ftype->points_to();
11097 is_pointer = true;
11099 Named_type* fnt = ftype->named_type();
11100 if (fnt == NULL)
11102 // This is an error, but it will be diagnosed elsewhere.
11103 continue;
11106 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11107 sub_field_indexes->next = field_indexes;
11108 sub_field_indexes->field_index = i;
11110 Methods tmp_methods;
11111 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11112 (is_embedded_pointer || is_pointer),
11113 (needs_stub_method
11114 || is_pointer
11115 || i > 0),
11116 seen,
11117 &tmp_methods);
11118 // Check if there are promoted methods that conflict with field names and
11119 // don't add them to the method map.
11120 for (Methods::const_iterator p = tmp_methods.begin();
11121 p != tmp_methods.end();
11122 ++p)
11124 bool found = false;
11125 for (Struct_field_list::const_iterator fp = fields->begin();
11126 fp != fields->end();
11127 ++fp)
11129 if (fp->field_name() == p->first)
11131 found = true;
11132 break;
11135 if (!found &&
11136 !methods->insert(p->first, p->second))
11137 delete p->second;
11142 // If TYPE is an interface type, then add its method to *METHODS.
11143 // This is for interface methods attached to an anonymous field. The
11144 // parameters are as for add_methods_for_type.
11146 void
11147 Type::add_interface_methods_for_type(const Type* type,
11148 const Method::Field_indexes* field_indexes,
11149 unsigned int depth,
11150 Methods* methods)
11152 const Interface_type* it = type->interface_type();
11153 if (it == NULL)
11154 return;
11156 const Typed_identifier_list* imethods = it->methods();
11157 if (imethods == NULL)
11158 return;
11160 for (Typed_identifier_list::const_iterator pm = imethods->begin();
11161 pm != imethods->end();
11162 ++pm)
11164 Function_type* fntype = pm->type()->function_type();
11165 if (fntype == NULL)
11167 // This is an error, but it should be reported elsewhere
11168 // when we look at the methods for IT.
11169 continue;
11171 go_assert(!fntype->is_method());
11172 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
11173 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
11174 field_indexes, depth);
11175 if (!methods->insert(pm->name(), m))
11176 delete m;
11180 // Build stub methods for TYPE as needed. METHODS is the set of
11181 // methods for the type. A stub method may be needed when a type
11182 // inherits a method from an anonymous field. When we need the
11183 // address of the method, as in a type descriptor, we need to build a
11184 // little stub which does the required field dereferences and jumps to
11185 // the real method. LOCATION is the location of the type definition.
11187 void
11188 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
11189 Location location)
11191 if (methods == NULL)
11192 return;
11193 for (Methods::const_iterator p = methods->begin();
11194 p != methods->end();
11195 ++p)
11197 Method* m = p->second;
11198 if (m->is_ambiguous() || !m->needs_stub_method())
11199 continue;
11201 const std::string& name(p->first);
11203 // Build a stub method.
11205 const Function_type* fntype = m->type();
11207 static unsigned int counter;
11208 char buf[100];
11209 snprintf(buf, sizeof buf, "$this%u", counter);
11210 ++counter;
11212 Type* receiver_type = const_cast<Type*>(type);
11213 if (!m->is_value_method())
11214 receiver_type = Type::make_pointer_type(receiver_type);
11215 Location receiver_location = m->receiver_location();
11216 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
11217 receiver_location);
11219 const Typed_identifier_list* fnparams = fntype->parameters();
11220 Typed_identifier_list* stub_params;
11221 if (fnparams == NULL || fnparams->empty())
11222 stub_params = NULL;
11223 else
11225 // We give each stub parameter a unique name.
11226 stub_params = new Typed_identifier_list();
11227 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
11228 pp != fnparams->end();
11229 ++pp)
11231 char pbuf[100];
11232 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
11233 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
11234 pp->location()));
11235 ++counter;
11239 const Typed_identifier_list* fnresults = fntype->results();
11240 Typed_identifier_list* stub_results;
11241 if (fnresults == NULL || fnresults->empty())
11242 stub_results = NULL;
11243 else
11245 // We create the result parameters without any names, since
11246 // we won't refer to them.
11247 stub_results = new Typed_identifier_list();
11248 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
11249 pr != fnresults->end();
11250 ++pr)
11251 stub_results->push_back(Typed_identifier("", pr->type(),
11252 pr->location()));
11255 Function_type* stub_type = Type::make_function_type(receiver,
11256 stub_params,
11257 stub_results,
11258 fntype->location());
11259 if (fntype->is_varargs())
11260 stub_type->set_is_varargs();
11262 // We only create the function in the package which creates the
11263 // type.
11264 const Package* package;
11265 if (type->named_type() == NULL)
11266 package = NULL;
11267 else
11268 package = type->named_type()->named_object()->package();
11269 std::string stub_name = gogo->stub_method_name(package, name);
11270 Named_object* stub;
11271 if (package != NULL)
11272 stub = Named_object::make_function_declaration(stub_name, package,
11273 stub_type, location);
11274 else
11276 stub = gogo->start_function(stub_name, stub_type, false,
11277 fntype->location());
11278 Type::build_one_stub_method(gogo, m, buf, stub_params,
11279 fntype->is_varargs(), location);
11280 gogo->finish_function(fntype->location());
11282 if (type->named_type() == NULL && stub->is_function())
11283 stub->func_value()->set_is_unnamed_type_stub_method();
11284 if (m->nointerface() && stub->is_function())
11285 stub->func_value()->set_nointerface();
11288 m->set_stub_object(stub);
11292 // Build a stub method which adjusts the receiver as required to call
11293 // METHOD. RECEIVER_NAME is the name we used for the receiver.
11294 // PARAMS is the list of function parameters.
11296 void
11297 Type::build_one_stub_method(Gogo* gogo, Method* method,
11298 const char* receiver_name,
11299 const Typed_identifier_list* params,
11300 bool is_varargs,
11301 Location location)
11303 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
11304 go_assert(receiver_object != NULL);
11306 Expression* expr = Expression::make_var_reference(receiver_object, location);
11307 expr = Type::apply_field_indexes(expr, method->field_indexes(), location);
11308 if (expr->type()->points_to() == NULL)
11309 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11311 Expression_list* arguments;
11312 if (params == NULL || params->empty())
11313 arguments = NULL;
11314 else
11316 arguments = new Expression_list();
11317 for (Typed_identifier_list::const_iterator p = params->begin();
11318 p != params->end();
11319 ++p)
11321 Named_object* param = gogo->lookup(p->name(), NULL);
11322 go_assert(param != NULL);
11323 Expression* param_ref = Expression::make_var_reference(param,
11324 location);
11325 arguments->push_back(param_ref);
11329 Expression* func = method->bind_method(expr, location);
11330 go_assert(func != NULL);
11331 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
11332 location);
11334 gogo->add_statement(Statement::make_return_from_call(call, location));
11337 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
11338 // in reverse order.
11340 Expression*
11341 Type::apply_field_indexes(Expression* expr,
11342 const Method::Field_indexes* field_indexes,
11343 Location location)
11345 if (field_indexes == NULL)
11346 return expr;
11347 expr = Type::apply_field_indexes(expr, field_indexes->next, location);
11348 Struct_type* stype = expr->type()->deref()->struct_type();
11349 go_assert(stype != NULL
11350 && field_indexes->field_index < stype->field_count());
11351 if (expr->type()->struct_type() == NULL)
11353 go_assert(expr->type()->points_to() != NULL);
11354 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11355 location);
11356 go_assert(expr->type()->struct_type() == stype);
11358 return Expression::make_field_reference(expr, field_indexes->field_index,
11359 location);
11362 // Return whether NO is a method for which the receiver is a pointer.
11364 bool
11365 Type::method_expects_pointer(const Named_object* no)
11367 const Function_type *fntype;
11368 if (no->is_function())
11369 fntype = no->func_value()->type();
11370 else if (no->is_function_declaration())
11371 fntype = no->func_declaration_value()->type();
11372 else
11373 go_unreachable();
11374 return fntype->receiver()->type()->points_to() != NULL;
11377 // Given a set of methods for a type, METHODS, return the method NAME,
11378 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
11379 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
11380 // but is ambiguous (and return NULL).
11382 Method*
11383 Type::method_function(const Methods* methods, const std::string& name,
11384 bool* is_ambiguous)
11386 if (is_ambiguous != NULL)
11387 *is_ambiguous = false;
11388 if (methods == NULL)
11389 return NULL;
11390 Methods::const_iterator p = methods->find(name);
11391 if (p == methods->end())
11392 return NULL;
11393 Method* m = p->second;
11394 if (m->is_ambiguous())
11396 if (is_ambiguous != NULL)
11397 *is_ambiguous = true;
11398 return NULL;
11400 return m;
11403 // Return a pointer to the interface method table for TYPE for the
11404 // interface INTERFACE.
11406 Expression*
11407 Type::interface_method_table(Type* type,
11408 Interface_type *interface,
11409 bool is_pointer,
11410 Interface_method_tables** method_tables,
11411 Interface_method_tables** pointer_tables)
11413 go_assert(!interface->is_empty());
11415 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
11417 if (*pimt == NULL)
11418 *pimt = new Interface_method_tables(5);
11420 std::pair<Interface_type*, Expression*> val(interface, NULL);
11421 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
11423 Location loc = Linemap::predeclared_location();
11424 if (ins.second)
11426 // This is a new entry in the hash table.
11427 go_assert(ins.first->second == NULL);
11428 ins.first->second =
11429 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
11431 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
11434 // Look for field or method NAME for TYPE. Return an Expression for
11435 // the field or method bound to EXPR. If there is no such field or
11436 // method, give an appropriate error and return an error expression.
11438 Expression*
11439 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
11440 const std::string& name,
11441 Location location)
11443 if (type->deref()->is_error_type())
11444 return Expression::make_error(location);
11446 const Named_type* nt = type->deref()->named_type();
11447 const Struct_type* st = type->deref()->struct_type();
11448 const Interface_type* it = type->interface_type();
11450 // If this is a pointer to a pointer, then it is possible that the
11451 // pointed-to type has methods.
11452 bool dereferenced = false;
11453 if (nt == NULL
11454 && st == NULL
11455 && it == NULL
11456 && type->points_to() != NULL
11457 && type->points_to()->points_to() != NULL)
11459 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
11460 location);
11461 type = type->points_to();
11462 if (type->deref()->is_error_type())
11463 return Expression::make_error(location);
11464 nt = type->points_to()->named_type();
11465 st = type->points_to()->struct_type();
11466 dereferenced = true;
11469 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
11470 || expr->is_addressable());
11471 std::vector<const Named_type*> seen;
11472 bool is_method = false;
11473 bool found_pointer_method = false;
11474 std::string ambig1;
11475 std::string ambig2;
11476 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
11477 &seen, NULL, &is_method,
11478 &found_pointer_method, &ambig1, &ambig2))
11480 Expression* ret;
11481 if (!is_method)
11483 go_assert(st != NULL);
11484 if (type->struct_type() == NULL)
11486 if (dereferenced)
11488 go_error_at(location, "pointer type has no field %qs",
11489 Gogo::message_name(name).c_str());
11490 return Expression::make_error(location);
11492 go_assert(type->points_to() != NULL);
11493 expr = Expression::make_dereference(expr,
11494 Expression::NIL_CHECK_DEFAULT,
11495 location);
11496 go_assert(expr->type()->struct_type() == st);
11498 ret = st->field_reference(expr, name, location);
11499 if (ret == NULL)
11501 go_error_at(location, "type has no field %qs",
11502 Gogo::message_name(name).c_str());
11503 return Expression::make_error(location);
11506 else if (it != NULL && it->find_method(name) != NULL)
11507 ret = Expression::make_interface_field_reference(expr, name,
11508 location);
11509 else
11511 Method* m;
11512 if (nt != NULL)
11513 m = nt->method_function(name, NULL);
11514 else if (st != NULL)
11515 m = st->method_function(name, NULL);
11516 else
11517 go_unreachable();
11518 go_assert(m != NULL);
11519 if (dereferenced)
11521 go_error_at(location,
11522 "calling method %qs requires explicit dereference",
11523 Gogo::message_name(name).c_str());
11524 return Expression::make_error(location);
11526 if (!m->is_value_method() && expr->type()->points_to() == NULL)
11527 expr = Expression::make_unary(OPERATOR_AND, expr, location);
11528 ret = m->bind_method(expr, location);
11530 go_assert(ret != NULL);
11531 return ret;
11533 else
11535 if (Gogo::is_erroneous_name(name))
11537 // An error was already reported.
11539 else if (!ambig1.empty())
11540 go_error_at(location, "%qs is ambiguous via %qs and %qs",
11541 Gogo::message_name(name).c_str(), ambig1.c_str(),
11542 ambig2.c_str());
11543 else if (found_pointer_method)
11544 go_error_at(location, "method requires a pointer receiver");
11545 else if (nt == NULL && st == NULL && it == NULL)
11546 go_error_at(location,
11547 ("reference to field %qs in object which "
11548 "has no fields or methods"),
11549 Gogo::message_name(name).c_str());
11550 else
11552 bool is_unexported;
11553 // The test for 'a' and 'z' is to handle builtin names,
11554 // which are not hidden.
11555 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
11556 is_unexported = false;
11557 else
11559 std::string unpacked = Gogo::unpack_hidden_name(name);
11560 seen.clear();
11561 is_unexported = Type::is_unexported_field_or_method(gogo, type,
11562 unpacked,
11563 &seen);
11565 if (is_unexported)
11566 go_error_at(location, "reference to unexported field or method %qs",
11567 Gogo::message_name(name).c_str());
11568 else
11569 go_error_at(location, "reference to undefined field or method %qs",
11570 Gogo::message_name(name).c_str());
11572 return Expression::make_error(location);
11576 // Look in TYPE for a field or method named NAME, return true if one
11577 // is found. This looks through embedded anonymous fields and handles
11578 // ambiguity. If a method is found, sets *IS_METHOD to true;
11579 // otherwise, if a field is found, set it to false. If
11580 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
11581 // whose address can not be taken. SEEN is used to avoid infinite
11582 // recursion on invalid types.
11584 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
11585 // method we couldn't use because it requires a pointer. LEVEL is
11586 // used for recursive calls, and can be NULL for a non-recursive call.
11587 // When this function returns false because it finds that the name is
11588 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
11589 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
11590 // will be unchanged.
11592 // This function just returns whether or not there is a field or
11593 // method, and whether it is a field or method. It doesn't build an
11594 // expression to refer to it. If it is a method, we then look in the
11595 // list of all methods for the type. If it is a field, the search has
11596 // to be done again, looking only for fields, and building up the
11597 // expression as we go.
11599 bool
11600 Type::find_field_or_method(const Type* type,
11601 const std::string& name,
11602 bool receiver_can_be_pointer,
11603 std::vector<const Named_type*>* seen,
11604 int* level,
11605 bool* is_method,
11606 bool* found_pointer_method,
11607 std::string* ambig1,
11608 std::string* ambig2)
11610 // Named types can have locally defined methods.
11611 const Named_type* nt = type->unalias()->named_type();
11612 if (nt == NULL && type->points_to() != NULL)
11613 nt = type->points_to()->unalias()->named_type();
11614 if (nt != NULL)
11616 Named_object* no = nt->find_local_method(name);
11617 if (no != NULL)
11619 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
11621 *is_method = true;
11622 return true;
11625 // Record that we have found a pointer method in order to
11626 // give a better error message if we don't find anything
11627 // else.
11628 *found_pointer_method = true;
11631 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11632 p != seen->end();
11633 ++p)
11635 if (*p == nt)
11637 // We've already seen this type when searching for methods.
11638 return false;
11643 // Interface types can have methods.
11644 const Interface_type* it = type->interface_type();
11645 if (it != NULL && it->find_method(name) != NULL)
11647 *is_method = true;
11648 return true;
11651 // Struct types can have fields. They can also inherit fields and
11652 // methods from anonymous fields.
11653 const Struct_type* st = type->deref()->struct_type();
11654 if (st == NULL)
11655 return false;
11656 const Struct_field_list* fields = st->fields();
11657 if (fields == NULL)
11658 return false;
11660 if (nt != NULL)
11661 seen->push_back(nt);
11663 int found_level = 0;
11664 bool found_is_method = false;
11665 std::string found_ambig1;
11666 std::string found_ambig2;
11667 const Struct_field* found_parent = NULL;
11668 for (Struct_field_list::const_iterator pf = fields->begin();
11669 pf != fields->end();
11670 ++pf)
11672 if (pf->is_field_name(name))
11674 *is_method = false;
11675 if (nt != NULL)
11676 seen->pop_back();
11677 return true;
11680 if (!pf->is_anonymous())
11681 continue;
11683 if (pf->type()->deref()->is_error_type()
11684 || pf->type()->deref()->is_undefined())
11685 continue;
11687 Named_type* fnt = pf->type()->named_type();
11688 if (fnt == NULL)
11689 fnt = pf->type()->deref()->named_type();
11690 go_assert(fnt != NULL);
11692 // Methods with pointer receivers on embedded field are
11693 // inherited by the pointer to struct, and also by the struct
11694 // type if the field itself is a pointer.
11695 bool can_be_pointer = (receiver_can_be_pointer
11696 || pf->type()->points_to() != NULL);
11697 int sublevel = level == NULL ? 1 : *level + 1;
11698 bool sub_is_method;
11699 std::string subambig1;
11700 std::string subambig2;
11701 bool subfound = Type::find_field_or_method(fnt,
11702 name,
11703 can_be_pointer,
11704 seen,
11705 &sublevel,
11706 &sub_is_method,
11707 found_pointer_method,
11708 &subambig1,
11709 &subambig2);
11710 if (!subfound)
11712 if (!subambig1.empty())
11714 // The name was found via this field, but is ambiguous.
11715 // if the ambiguity is lower or at the same level as
11716 // anything else we have already found, then we want to
11717 // pass the ambiguity back to the caller.
11718 if (found_level == 0 || sublevel <= found_level)
11720 found_ambig1 = (Gogo::message_name(pf->field_name())
11721 + '.' + subambig1);
11722 found_ambig2 = (Gogo::message_name(pf->field_name())
11723 + '.' + subambig2);
11724 found_level = sublevel;
11728 else
11730 // The name was found via this field. Use the level to see
11731 // if we want to use this one, or whether it introduces an
11732 // ambiguity.
11733 if (found_level == 0 || sublevel < found_level)
11735 found_level = sublevel;
11736 found_is_method = sub_is_method;
11737 found_ambig1.clear();
11738 found_ambig2.clear();
11739 found_parent = &*pf;
11741 else if (sublevel > found_level)
11743 else if (found_ambig1.empty())
11745 // We found an ambiguity.
11746 go_assert(found_parent != NULL);
11747 found_ambig1 = Gogo::message_name(found_parent->field_name());
11748 found_ambig2 = Gogo::message_name(pf->field_name());
11750 else
11752 // We found an ambiguity, but we already know of one.
11753 // Just report the earlier one.
11758 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
11759 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
11760 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
11761 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
11763 if (nt != NULL)
11764 seen->pop_back();
11766 if (found_level == 0)
11767 return false;
11768 else if (found_is_method
11769 && type->named_type() != NULL
11770 && type->points_to() != NULL)
11772 // If this is a method inherited from a struct field in a named pointer
11773 // type, it is invalid to automatically dereference the pointer to the
11774 // struct to find this method.
11775 if (level != NULL)
11776 *level = found_level;
11777 *is_method = true;
11778 return false;
11780 else if (!found_ambig1.empty())
11782 go_assert(!found_ambig1.empty());
11783 ambig1->assign(found_ambig1);
11784 ambig2->assign(found_ambig2);
11785 if (level != NULL)
11786 *level = found_level;
11787 return false;
11789 else
11791 if (level != NULL)
11792 *level = found_level;
11793 *is_method = found_is_method;
11794 return true;
11798 // Return whether NAME is an unexported field or method for TYPE.
11800 bool
11801 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
11802 const std::string& name,
11803 std::vector<const Named_type*>* seen)
11805 const Named_type* nt = type->named_type();
11806 if (nt == NULL)
11807 nt = type->deref()->named_type();
11808 if (nt != NULL)
11810 if (nt->is_unexported_local_method(gogo, name))
11811 return true;
11813 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11814 p != seen->end();
11815 ++p)
11817 if (*p == nt)
11819 // We've already seen this type.
11820 return false;
11825 const Interface_type* it = type->interface_type();
11826 if (it != NULL && it->is_unexported_method(gogo, name))
11827 return true;
11829 type = type->deref();
11831 const Struct_type* st = type->struct_type();
11832 if (st != NULL && st->is_unexported_local_field(gogo, name))
11833 return true;
11835 if (st == NULL)
11836 return false;
11838 const Struct_field_list* fields = st->fields();
11839 if (fields == NULL)
11840 return false;
11842 if (nt != NULL)
11843 seen->push_back(nt);
11845 for (Struct_field_list::const_iterator pf = fields->begin();
11846 pf != fields->end();
11847 ++pf)
11849 if (pf->is_anonymous()
11850 && !pf->type()->deref()->is_error_type()
11851 && !pf->type()->deref()->is_undefined())
11853 Named_type* subtype = pf->type()->named_type();
11854 if (subtype == NULL)
11855 subtype = pf->type()->deref()->named_type();
11856 if (subtype == NULL)
11858 // This is an error, but it will be diagnosed elsewhere.
11859 continue;
11861 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
11863 if (nt != NULL)
11864 seen->pop_back();
11865 return true;
11870 if (nt != NULL)
11871 seen->pop_back();
11873 return false;
11876 // Class Forward_declaration.
11878 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
11879 : Type(TYPE_FORWARD),
11880 named_object_(named_object->resolve()), warned_(false)
11882 go_assert(this->named_object_->is_unknown()
11883 || this->named_object_->is_type_declaration());
11886 // Return the named object.
11888 Named_object*
11889 Forward_declaration_type::named_object()
11891 return this->named_object_->resolve();
11894 const Named_object*
11895 Forward_declaration_type::named_object() const
11897 return this->named_object_->resolve();
11900 // Return the name of the forward declared type.
11902 const std::string&
11903 Forward_declaration_type::name() const
11905 return this->named_object()->name();
11908 // Warn about a use of a type which has been declared but not defined.
11910 void
11911 Forward_declaration_type::warn() const
11913 Named_object* no = this->named_object_->resolve();
11914 if (no->is_unknown())
11916 // The name was not defined anywhere.
11917 if (!this->warned_)
11919 go_error_at(this->named_object_->location(),
11920 "use of undefined type %qs",
11921 no->message_name().c_str());
11922 this->warned_ = true;
11925 else if (no->is_type_declaration())
11927 // The name was seen as a type, but the type was never defined.
11928 if (no->type_declaration_value()->using_type())
11930 go_error_at(this->named_object_->location(),
11931 "use of undefined type %qs",
11932 no->message_name().c_str());
11933 this->warned_ = true;
11936 else
11938 // The name was defined, but not as a type.
11939 if (!this->warned_)
11941 go_error_at(this->named_object_->location(), "expected type");
11942 this->warned_ = true;
11947 // Get the base type of a declaration. This gives an error if the
11948 // type has not yet been defined.
11950 Type*
11951 Forward_declaration_type::real_type()
11953 if (this->is_defined())
11955 Named_type* nt = this->named_object()->type_value();
11956 if (!nt->is_valid())
11957 return Type::make_error_type();
11958 return this->named_object()->type_value();
11960 else
11962 this->warn();
11963 return Type::make_error_type();
11967 const Type*
11968 Forward_declaration_type::real_type() const
11970 if (this->is_defined())
11972 const Named_type* nt = this->named_object()->type_value();
11973 if (!nt->is_valid())
11974 return Type::make_error_type();
11975 return this->named_object()->type_value();
11977 else
11979 this->warn();
11980 return Type::make_error_type();
11984 // Return whether the base type is defined.
11986 bool
11987 Forward_declaration_type::is_defined() const
11989 return this->named_object()->is_type();
11992 // Add a method. This is used when methods are defined before the
11993 // type.
11995 Named_object*
11996 Forward_declaration_type::add_method(const std::string& name,
11997 Function* function)
11999 Named_object* no = this->named_object();
12000 if (no->is_unknown())
12001 no->declare_as_type();
12002 return no->type_declaration_value()->add_method(name, function);
12005 // Add a method declaration. This is used when methods are declared
12006 // before the type.
12008 Named_object*
12009 Forward_declaration_type::add_method_declaration(const std::string& name,
12010 Package* package,
12011 Function_type* type,
12012 Location location)
12014 Named_object* no = this->named_object();
12015 if (no->is_unknown())
12016 no->declare_as_type();
12017 Type_declaration* td = no->type_declaration_value();
12018 return td->add_method_declaration(name, package, type, location);
12021 // Add an already created object as a method.
12023 void
12024 Forward_declaration_type::add_existing_method(Named_object* nom)
12026 Named_object* no = this->named_object();
12027 if (no->is_unknown())
12028 no->declare_as_type();
12029 no->type_declaration_value()->add_existing_method(nom);
12032 // Traversal.
12035 Forward_declaration_type::do_traverse(Traverse* traverse)
12037 if (this->is_defined()
12038 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
12039 return TRAVERSE_EXIT;
12040 return TRAVERSE_CONTINUE;
12043 // Verify the type.
12045 bool
12046 Forward_declaration_type::do_verify()
12048 if (!this->is_defined() && !this->is_nil_constant_as_type())
12050 this->warn();
12051 return false;
12053 return true;
12056 // Get the backend representation for the type.
12058 Btype*
12059 Forward_declaration_type::do_get_backend(Gogo* gogo)
12061 if (this->is_defined())
12062 return Type::get_named_base_btype(gogo, this->real_type());
12064 if (this->warned_)
12065 return gogo->backend()->error_type();
12067 // We represent an undefined type as a struct with no fields. That
12068 // should work fine for the backend, since the same case can arise
12069 // in C.
12070 std::vector<Backend::Btyped_identifier> fields;
12071 Btype* bt = gogo->backend()->struct_type(fields);
12072 return gogo->backend()->named_type(this->name(), bt,
12073 this->named_object()->location());
12076 // Build a type descriptor for a forwarded type.
12078 Expression*
12079 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
12081 Location ploc = Linemap::predeclared_location();
12082 if (!this->is_defined())
12083 return Expression::make_error(ploc);
12084 else
12086 Type* t = this->real_type();
12087 if (name != NULL)
12088 return this->named_type_descriptor(gogo, t, name);
12089 else
12090 return Expression::make_error(this->named_object_->location());
12094 // The reflection string.
12096 void
12097 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
12099 this->append_reflection(this->real_type(), gogo, ret);
12102 // Export a forward declaration. This can happen when a defined type
12103 // refers to a type which is only declared (and is presumably defined
12104 // in some other file in the same package).
12106 void
12107 Forward_declaration_type::do_export(Export*) const
12109 // If there is a base type, that should be exported instead of this.
12110 go_assert(!this->is_defined());
12112 // We don't output anything.
12115 // Make a forward declaration.
12117 Type*
12118 Type::make_forward_declaration(Named_object* named_object)
12120 return new Forward_declaration_type(named_object);
12123 // Class Typed_identifier_list.
12125 // Sort the entries by name.
12127 struct Typed_identifier_list_sort
12129 public:
12130 bool
12131 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
12133 return (Gogo::unpack_hidden_name(t1.name())
12134 < Gogo::unpack_hidden_name(t2.name()));
12138 void
12139 Typed_identifier_list::sort_by_name()
12141 std::sort(this->entries_.begin(), this->entries_.end(),
12142 Typed_identifier_list_sort());
12145 // Traverse types.
12148 Typed_identifier_list::traverse(Traverse* traverse)
12150 for (Typed_identifier_list::const_iterator p = this->begin();
12151 p != this->end();
12152 ++p)
12154 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
12155 return TRAVERSE_EXIT;
12157 return TRAVERSE_CONTINUE;
12160 // Copy the list.
12162 Typed_identifier_list*
12163 Typed_identifier_list::copy() const
12165 Typed_identifier_list* ret = new Typed_identifier_list();
12166 for (Typed_identifier_list::const_iterator p = this->begin();
12167 p != this->end();
12168 ++p)
12169 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
12170 return ret;