Remove m_nloops field from loop_versioning
[official-gcc.git] / gcc / go / gofrontend / types.cc
bloba39cfbf7679ac665e112e127c653fad76dc8738f
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 "go-sha1.h"
16 #include "operator.h"
17 #include "expressions.h"
18 #include "statements.h"
19 #include "export.h"
20 #include "import.h"
21 #include "backend.h"
22 #include "types.h"
24 // Forward declarations so that we don't have to make types.h #include
25 // backend.h.
27 static void
28 get_backend_struct_fields(Gogo* gogo, Struct_type* type, 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 // Note that this type is an error. This is called by children when
265 // they discover an error during the verify_types pass.
267 void
268 Type::set_is_error()
270 this->classification_ = TYPE_ERROR;
273 // Return a string version of this type to use in an error message.
275 std::string
276 Type::message_name() const
278 std::string ret;
279 this->do_message_name(&ret);
280 return ret;
283 // If this is a pointer type, return the type to which it points.
284 // Otherwise, return NULL.
286 Type*
287 Type::points_to() const
289 const Pointer_type* ptype = this->convert<const Pointer_type,
290 TYPE_POINTER>();
291 return ptype == NULL ? NULL : ptype->points_to();
294 // Return whether this is a slice type.
296 bool
297 Type::is_slice_type() const
299 return this->array_type() != NULL && this->array_type()->length() == NULL;
302 // Return whether this is the predeclared constant nil being used as a
303 // type.
305 bool
306 Type::is_nil_constant_as_type() const
308 const Type* t = this->forwarded();
309 if (t->forward_declaration_type() != NULL)
311 const Named_object* no = t->forward_declaration_type()->named_object();
312 if (no->is_unknown())
313 no = no->unknown_value()->real_named_object();
314 if (no != NULL
315 && no->is_const()
316 && no->const_value()->expr()->is_nil_expression())
317 return true;
319 return false;
322 // Traverse a type.
325 Type::traverse(Type* type, Traverse* traverse)
327 go_assert((traverse->traverse_mask() & Traverse::traverse_types) != 0
328 || (traverse->traverse_mask()
329 & Traverse::traverse_expressions) != 0);
330 if (traverse->remember_type(type))
332 // We have already traversed this type.
333 return TRAVERSE_CONTINUE;
335 if ((traverse->traverse_mask() & Traverse::traverse_types) != 0)
337 int t = traverse->type(type);
338 if (t == TRAVERSE_EXIT)
339 return TRAVERSE_EXIT;
340 else if (t == TRAVERSE_SKIP_COMPONENTS)
341 return TRAVERSE_CONTINUE;
343 // An array type has an expression which we need to traverse if
344 // traverse_expressions is set.
345 if (type->do_traverse(traverse) == TRAVERSE_EXIT)
346 return TRAVERSE_EXIT;
347 return TRAVERSE_CONTINUE;
350 // Default implementation for do_traverse for child class.
353 Type::do_traverse(Traverse*)
355 return TRAVERSE_CONTINUE;
358 // Return whether two types are identical. If REASON is not NULL,
359 // optionally set *REASON to the reason the types are not identical.
361 bool
362 Type::are_identical(const Type* t1, const Type* t2, int flags,
363 std::string* reason)
365 if (t1 == NULL || t2 == NULL)
367 // Something is wrong.
368 return (flags & COMPARE_ERRORS) == 0 ? true : t1 == t2;
371 // Skip defined forward declarations.
372 t1 = t1->forwarded();
373 t2 = t2->forwarded();
375 if ((flags & COMPARE_ALIASES) == 0)
377 // Ignore aliases.
378 t1 = t1->unalias();
379 t2 = t2->unalias();
382 if (t1 == t2)
383 return true;
385 // An undefined forward declaration is an error.
386 if (t1->forward_declaration_type() != NULL
387 || t2->forward_declaration_type() != NULL)
388 return (flags & COMPARE_ERRORS) == 0;
390 // Avoid cascading errors with error types.
391 if (t1->is_error_type() || t2->is_error_type())
393 if ((flags & COMPARE_ERRORS) == 0)
394 return true;
395 return t1->is_error_type() && t2->is_error_type();
398 // Get a good reason for the sink type. Note that the sink type on
399 // the left hand side of an assignment is handled in are_assignable.
400 if (t1->is_sink_type() || t2->is_sink_type())
402 if (reason != NULL)
403 *reason = "invalid use of _";
404 return false;
407 // A named type is only identical to itself.
408 if (t1->named_type() != NULL || t2->named_type() != NULL)
409 return false;
411 // Check type shapes.
412 if (t1->classification() != t2->classification())
413 return false;
415 switch (t1->classification())
417 case TYPE_VOID:
418 case TYPE_BOOLEAN:
419 case TYPE_STRING:
420 case TYPE_NIL:
421 // These types are always identical.
422 return true;
424 case TYPE_INTEGER:
425 return t1->integer_type()->is_identical(t2->integer_type());
427 case TYPE_FLOAT:
428 return t1->float_type()->is_identical(t2->float_type());
430 case TYPE_COMPLEX:
431 return t1->complex_type()->is_identical(t2->complex_type());
433 case TYPE_FUNCTION:
434 return t1->function_type()->is_identical(t2->function_type(),
435 false, flags, reason);
437 case TYPE_POINTER:
438 return Type::are_identical(t1->points_to(), t2->points_to(), flags,
439 reason);
441 case TYPE_STRUCT:
442 return t1->struct_type()->is_identical(t2->struct_type(), flags);
444 case TYPE_ARRAY:
445 return t1->array_type()->is_identical(t2->array_type(), flags);
447 case TYPE_MAP:
448 return t1->map_type()->is_identical(t2->map_type(), flags);
450 case TYPE_CHANNEL:
451 return t1->channel_type()->is_identical(t2->channel_type(), flags);
453 case TYPE_INTERFACE:
454 return t1->interface_type()->is_identical(t2->interface_type(), flags);
456 case TYPE_CALL_MULTIPLE_RESULT:
457 if (reason != NULL)
458 *reason = "invalid use of multiple-value function call";
459 return false;
461 default:
462 go_unreachable();
466 // Return true if it's OK to have a binary operation with types LHS
467 // and RHS. This is not used for shifts or comparisons.
469 bool
470 Type::are_compatible_for_binop(const Type* lhs, const Type* rhs)
472 if (Type::are_identical(lhs, rhs, Type::COMPARE_TAGS, NULL))
473 return true;
475 // A constant of abstract bool type may be mixed with any bool type.
476 if ((rhs->is_abstract_boolean_type() && lhs->is_boolean_type())
477 || (lhs->is_abstract_boolean_type() && rhs->is_boolean_type()))
478 return true;
480 // A constant of abstract string type may be mixed with any string
481 // type.
482 if ((rhs->is_abstract_string_type() && lhs->is_string_type())
483 || (lhs->is_abstract_string_type() && rhs->is_string_type()))
484 return true;
486 lhs = lhs->base();
487 rhs = rhs->base();
489 // A constant of abstract integer, float, or complex type may be
490 // mixed with an integer, float, or complex type.
491 if ((rhs->is_abstract()
492 && (rhs->integer_type() != NULL
493 || rhs->float_type() != NULL
494 || rhs->complex_type() != NULL)
495 && (lhs->integer_type() != NULL
496 || lhs->float_type() != NULL
497 || lhs->complex_type() != NULL))
498 || (lhs->is_abstract()
499 && (lhs->integer_type() != NULL
500 || lhs->float_type() != NULL
501 || lhs->complex_type() != NULL)
502 && (rhs->integer_type() != NULL
503 || rhs->float_type() != NULL
504 || rhs->complex_type() != NULL)))
505 return true;
507 // The nil type may be compared to a pointer, an interface type, a
508 // slice type, a channel type, a map type, or a function type.
509 if (lhs->is_nil_type()
510 && (rhs->points_to() != NULL
511 || rhs->interface_type() != NULL
512 || rhs->is_slice_type()
513 || rhs->map_type() != NULL
514 || rhs->channel_type() != NULL
515 || rhs->function_type() != NULL))
516 return true;
517 if (rhs->is_nil_type()
518 && (lhs->points_to() != NULL
519 || lhs->interface_type() != NULL
520 || lhs->is_slice_type()
521 || lhs->map_type() != NULL
522 || lhs->channel_type() != NULL
523 || lhs->function_type() != NULL))
524 return true;
526 return false;
529 // Return true if a value with type T1 may be compared with a value of
530 // type T2. IS_EQUALITY_OP is true for == or !=, false for <, etc.
532 bool
533 Type::are_compatible_for_comparison(bool is_equality_op, const Type *t1,
534 const Type *t2, std::string *reason)
536 if (t1 != t2
537 && !Type::are_assignable(t1, t2, NULL)
538 && !Type::are_assignable(t2, t1, NULL))
540 if (reason != NULL)
541 *reason = "incompatible types in binary expression";
542 return false;
545 if (!is_equality_op)
547 if (t1->integer_type() == NULL
548 && t1->float_type() == NULL
549 && !t1->is_string_type())
551 if (reason != NULL)
552 *reason = _("invalid comparison of non-ordered type");
553 return false;
556 else if (t1->is_slice_type()
557 || t1->map_type() != NULL
558 || t1->function_type() != NULL
559 || t2->is_slice_type()
560 || t2->map_type() != NULL
561 || t2->function_type() != NULL)
563 if (!t1->is_nil_type() && !t2->is_nil_type())
565 if (reason != NULL)
567 if (t1->is_slice_type() || t2->is_slice_type())
568 *reason = _("slice can only be compared to nil");
569 else if (t1->map_type() != NULL || t2->map_type() != NULL)
570 *reason = _("map can only be compared to nil");
571 else
572 *reason = _("func can only be compared to nil");
574 // Match 6g error messages.
575 if (t1->interface_type() != NULL || t2->interface_type() != NULL)
577 char buf[200];
578 snprintf(buf, sizeof buf, _("invalid operation (%s)"),
579 reason->c_str());
580 *reason = buf;
583 return false;
586 else
588 if (!t1->is_boolean_type()
589 && t1->integer_type() == NULL
590 && t1->float_type() == NULL
591 && t1->complex_type() == NULL
592 && !t1->is_string_type()
593 && t1->points_to() == NULL
594 && t1->channel_type() == NULL
595 && t1->interface_type() == NULL
596 && t1->struct_type() == NULL
597 && t1->array_type() == NULL
598 && !t1->is_nil_type())
600 if (reason != NULL)
601 *reason = _("invalid comparison of non-comparable type");
602 return false;
605 if (t1->unalias()->named_type() != NULL)
606 return t1->unalias()->named_type()->named_type_is_comparable(reason);
607 else if (t2->unalias()->named_type() != NULL)
608 return t2->unalias()->named_type()->named_type_is_comparable(reason);
609 else if (t1->struct_type() != NULL)
611 if (t1->struct_type()->is_struct_incomparable())
613 if (reason != NULL)
614 *reason = _("invalid comparison of generated struct");
615 return false;
617 const Struct_field_list* fields = t1->struct_type()->fields();
618 for (Struct_field_list::const_iterator p = fields->begin();
619 p != fields->end();
620 ++p)
622 if (!p->type()->is_comparable())
624 if (reason != NULL)
625 *reason = _("invalid comparison of non-comparable struct");
626 return false;
630 else if (t1->array_type() != NULL)
632 if (t1->array_type()->is_array_incomparable())
634 if (reason != NULL)
635 *reason = _("invalid comparison of generated array");
636 return false;
638 if (t1->array_type()->length()->is_nil_expression()
639 || !t1->array_type()->element_type()->is_comparable())
641 if (reason != NULL)
642 *reason = _("invalid comparison of non-comparable array");
643 return false;
648 return true;
651 // Return true if a value with type RHS may be assigned to a variable
652 // with type LHS. If REASON is not NULL, set *REASON to the reason
653 // the types are not assignable.
655 bool
656 Type::are_assignable(const Type* lhs, const Type* rhs, std::string* reason)
658 // Do some checks first. Make sure the types are defined.
659 if (rhs != NULL && !rhs->is_undefined())
661 if (rhs->is_void_type())
663 if (reason != NULL)
664 *reason = "non-value used as value";
665 return false;
667 if (rhs->is_call_multiple_result_type())
669 if (reason != NULL)
670 reason->assign(_("multiple-value function call in "
671 "single-value context"));
672 return false;
676 // Any value may be assigned to the blank identifier.
677 if (lhs != NULL
678 && !lhs->is_undefined()
679 && lhs->is_sink_type())
680 return true;
682 // Identical types are assignable.
683 if (Type::are_identical(lhs, rhs, Type::COMPARE_TAGS, reason))
684 return true;
686 // Ignore aliases, except for error messages.
687 const Type* lhs_orig = lhs;
688 const Type* rhs_orig = rhs;
689 lhs = lhs->unalias();
690 rhs = rhs->unalias();
692 // The types are assignable if they have identical underlying types
693 // and either LHS or RHS is not a named type.
694 if (((lhs->named_type() != NULL && rhs->named_type() == NULL)
695 || (rhs->named_type() != NULL && lhs->named_type() == NULL))
696 && Type::are_identical(lhs->base(), rhs->base(), Type::COMPARE_TAGS,
697 reason))
698 return true;
700 // The types are assignable if LHS is an interface type and RHS
701 // implements the required methods.
702 const Interface_type* lhs_interface_type = lhs->interface_type();
703 if (lhs_interface_type != NULL)
705 if (lhs_interface_type->implements_interface(rhs, reason))
706 return true;
707 const Interface_type* rhs_interface_type = rhs->interface_type();
708 if (rhs_interface_type != NULL
709 && lhs_interface_type->is_compatible_for_assign(rhs_interface_type,
710 reason))
711 return true;
714 // The type are assignable if RHS is a bidirectional channel type,
715 // LHS is a channel type, they have identical element types, and
716 // either LHS or RHS is not a named type.
717 if (lhs->channel_type() != NULL
718 && rhs->channel_type() != NULL
719 && rhs->channel_type()->may_send()
720 && rhs->channel_type()->may_receive()
721 && (lhs->named_type() == NULL || rhs->named_type() == NULL)
722 && Type::are_identical(lhs->channel_type()->element_type(),
723 rhs->channel_type()->element_type(),
724 Type::COMPARE_TAGS,
725 reason))
726 return true;
728 // The nil type may be assigned to a pointer, function, slice, map,
729 // channel, or interface type.
730 if (rhs->is_nil_type()
731 && (lhs->points_to() != NULL
732 || lhs->function_type() != NULL
733 || lhs->is_slice_type()
734 || lhs->map_type() != NULL
735 || lhs->channel_type() != NULL
736 || lhs->interface_type() != NULL))
737 return true;
739 // An untyped numeric constant may be assigned to a numeric type if
740 // it is representable in that type.
741 if ((rhs->is_abstract()
742 && (rhs->integer_type() != NULL
743 || rhs->float_type() != NULL
744 || rhs->complex_type() != NULL))
745 && (lhs->integer_type() != NULL
746 || lhs->float_type() != NULL
747 || lhs->complex_type() != NULL))
748 return true;
750 // Give some better error messages.
751 if (reason != NULL && reason->empty())
753 if (rhs->interface_type() != NULL)
754 reason->assign(_("need explicit conversion"));
755 else
757 const std::string& lhs_name(lhs_orig->message_name());
758 const std::string& rhs_name(rhs_orig->message_name());
759 size_t len = lhs_name.length() + rhs_name.length() + 100;
760 char* buf = new char[len];
761 snprintf(buf, len, _("cannot use type %s as type %s"),
762 rhs_name.c_str(), lhs_name.c_str());
763 reason->assign(buf);
764 delete[] buf;
768 return false;
771 // Return true if a value with type RHS may be converted to type LHS.
772 // If REASON is not NULL, set *REASON to the reason the types are not
773 // convertible.
775 bool
776 Type::are_convertible(const Type* lhs, const Type* rhs, std::string* reason)
778 // The types are convertible if they are assignable.
779 if (Type::are_assignable(lhs, rhs, reason))
780 return true;
782 // Ignore aliases.
783 lhs = lhs->unalias();
784 rhs = rhs->unalias();
786 // A pointer to a regular type may not be converted to a pointer to
787 // a type that may not live in the heap, except when converting from
788 // unsafe.Pointer.
789 if (lhs->points_to() != NULL
790 && rhs->points_to() != NULL
791 && !lhs->points_to()->in_heap()
792 && rhs->points_to()->in_heap()
793 && !rhs->is_unsafe_pointer_type())
795 if (reason != NULL)
796 reason->assign(_("conversion from normal type to notinheap type"));
797 return false;
800 // The types are convertible if they have identical underlying
801 // types, ignoring struct field tags.
802 if (Type::are_identical(lhs->base(), rhs->base(), 0, reason))
803 return true;
805 // The types are convertible if they are both unnamed pointer types
806 // and their pointer base types have identical underlying types,
807 // ignoring struct field tags.
808 if (lhs->named_type() == NULL
809 && rhs->named_type() == NULL
810 && lhs->points_to() != NULL
811 && rhs->points_to() != NULL
812 && (lhs->points_to()->named_type() != NULL
813 || rhs->points_to()->named_type() != NULL)
814 && Type::are_identical(lhs->points_to()->base(),
815 rhs->points_to()->base(),
816 0, 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 // A slice may be converted to a pointer-to-array.
853 if (rhs->is_slice_type()
854 && lhs->points_to() != NULL
855 && lhs->points_to()->array_type() != NULL
856 && !lhs->points_to()->is_slice_type()
857 && Type::are_identical(lhs->points_to()->array_type()->element_type(),
858 rhs->array_type()->element_type(), 0, reason))
859 return true;
861 // An unsafe.Pointer type may be converted to any pointer type or to
862 // a type whose underlying type is uintptr, and vice-versa.
863 if (lhs->is_unsafe_pointer_type()
864 && (rhs->points_to() != NULL
865 || (rhs->integer_type() != NULL
866 && rhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
867 return true;
868 if (rhs->is_unsafe_pointer_type()
869 && (lhs->points_to() != NULL
870 || (lhs->integer_type() != NULL
871 && lhs->integer_type() == Type::lookup_integer_type("uintptr")->real_type())))
872 return true;
874 // Give a better error message.
875 if (reason != NULL)
877 if (reason->empty())
878 *reason = "invalid type conversion";
879 else
881 std::string s = "invalid type conversion (";
882 s += *reason;
883 s += ')';
884 *reason = s;
888 return false;
891 // Copy expressions if it may change the size.
893 // The only type that has an expression is an array type. The only
894 // types whose size can be changed by the size of an array type are an
895 // array type itself, or a struct type with an array field.
896 Type*
897 Type::copy_expressions()
899 // This is run during parsing, so types may not be valid yet.
900 // We only have to worry about array type literals.
901 switch (this->classification_)
903 default:
904 return this;
906 case TYPE_ARRAY:
908 Array_type* at = this->array_type();
909 if (at->length() == NULL)
910 return this;
911 Expression* len = at->length()->copy();
912 if (at->length() == len)
913 return this;
914 return Type::make_array_type(at->element_type(), len);
917 case TYPE_STRUCT:
919 Struct_type* st = this->struct_type();
920 const Struct_field_list* sfl = st->fields();
921 if (sfl == NULL)
922 return this;
923 bool changed = false;
924 Struct_field_list *nsfl = new Struct_field_list();
925 for (Struct_field_list::const_iterator pf = sfl->begin();
926 pf != sfl->end();
927 ++pf)
929 Type* ft = pf->type()->copy_expressions();
930 Struct_field nf(Typed_identifier((pf->is_anonymous()
931 ? ""
932 : pf->field_name()),
934 pf->location()));
935 if (pf->has_tag())
936 nf.set_tag(pf->tag());
937 nsfl->push_back(nf);
938 if (ft != pf->type())
939 changed = true;
941 if (!changed)
943 delete(nsfl);
944 return this;
946 return Type::make_struct_type(nsfl, st->location());
950 go_unreachable();
953 // Return a hash code for the type to be used for method lookup.
955 unsigned int
956 Type::hash_for_method(Gogo* gogo, int flags) const
958 const Type* t = this->forwarded();
959 if (t->named_type() != NULL && t->named_type()->is_alias())
961 unsigned int r =
962 t->named_type()->real_type()->hash_for_method(gogo, flags);
963 if ((flags & Type::COMPARE_ALIASES) != 0)
964 r += TYPE_FORWARD;
965 return r;
967 unsigned int ret = t->classification_;
968 return ret + t->do_hash_for_method(gogo, flags);
971 // Default implementation of do_hash_for_method. This is appropriate
972 // for types with no subfields.
974 unsigned int
975 Type::do_hash_for_method(Gogo*, int) const
977 return 0;
980 // A hash table mapping unnamed types to the backend representation of
981 // those types.
983 Type::Type_btypes Type::type_btypes;
985 // Return the backend representation for this type.
987 Btype*
988 Type::get_backend(Gogo* gogo)
990 if (this->btype_ != NULL)
991 return this->btype_;
993 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 // We set the has_padding field of a Struct_type when we convert
1034 // to the backend type, so if we have multiple Struct_type's
1035 // mapping to the same backend type we need to copy the
1036 // has_padding field. FIXME: This is awkward. We shouldn't
1037 // really change the type when setting the backend type, but
1038 // there isn't any other good time to add the padding field.
1039 if (ins.first->first->struct_type() != NULL
1040 && ins.first->first->struct_type()->has_padding())
1041 this->struct_type()->set_has_padding();
1043 return ins.first->second.btype;
1046 Btype* bt = this->get_btype_without_hash(gogo);
1048 if (ins.first->second.btype == NULL)
1050 ins.first->second.btype = bt;
1051 ins.first->second.is_placeholder = false;
1053 else
1055 // We have already created a backend representation for this
1056 // type. This can happen when an unnamed type is defined using
1057 // a named type which in turns uses an identical unnamed type.
1058 // Use the representation we created earlier and ignore the one we just
1059 // built.
1060 if (this->btype_ == bt)
1061 this->btype_ = ins.first->second.btype;
1062 bt = ins.first->second.btype;
1065 return bt;
1068 // Return the backend representation for a type without looking in the
1069 // hash table for identical types. This is used for named types,
1070 // since a named type is never identical to any other type.
1072 Btype*
1073 Type::get_btype_without_hash(Gogo* gogo)
1075 if (this->btype_ == NULL)
1077 Btype* bt = this->do_get_backend(gogo);
1079 // For a recursive function or pointer type, we will temporarily
1080 // return a circular pointer type during the recursion. We
1081 // don't want to record that for a forwarding type, as it may
1082 // confuse us later.
1083 if (this->forward_declaration_type() != NULL
1084 && gogo->backend()->is_circular_pointer_type(bt))
1085 return bt;
1087 if (gogo == NULL || !gogo->named_types_are_converted())
1088 return bt;
1090 this->btype_ = bt;
1092 return this->btype_;
1095 // Get the backend representation of a type without forcing the
1096 // creation of the backend representation of all supporting types.
1097 // This will return a backend type that has the correct size but may
1098 // be incomplete. E.g., a pointer will just be a placeholder pointer,
1099 // and will not contain the final representation of the type to which
1100 // it points. This is used while converting all named types to the
1101 // backend representation, to avoid problems with indirect references
1102 // to types which are not yet complete. When this is called, the
1103 // sizes of all direct references (e.g., a struct field) should be
1104 // known, but the sizes of indirect references (e.g., the type to
1105 // which a pointer points) may not.
1107 Btype*
1108 Type::get_backend_placeholder(Gogo* gogo)
1110 if (gogo->named_types_are_converted())
1111 return this->get_backend(gogo);
1112 if (this->btype_ != NULL)
1113 return this->btype_;
1115 Btype* bt;
1116 switch (this->classification_)
1118 case TYPE_ERROR:
1119 case TYPE_VOID:
1120 case TYPE_BOOLEAN:
1121 case TYPE_INTEGER:
1122 case TYPE_FLOAT:
1123 case TYPE_COMPLEX:
1124 case TYPE_STRING:
1125 case TYPE_NIL:
1126 // These are simple types that can just be created directly.
1127 return this->get_backend(gogo);
1129 case TYPE_MAP:
1130 case TYPE_CHANNEL:
1131 // All maps and channels have the same backend representation.
1132 return this->get_backend(gogo);
1134 case TYPE_NAMED:
1135 case TYPE_FORWARD:
1136 // Named types keep track of their own dependencies and manage
1137 // their own placeholders.
1138 if (this->named_type() != NULL && this->named_type()->is_alias())
1139 return this->unalias()->get_backend_placeholder(gogo);
1140 return this->get_backend(gogo);
1142 case TYPE_INTERFACE:
1143 if (this->interface_type()->is_empty())
1144 return Interface_type::get_backend_empty_interface_type(gogo);
1145 break;
1147 default:
1148 break;
1151 std::pair<Type*, Type_btype_entry> val;
1152 val.first = this;
1153 val.second.btype = NULL;
1154 val.second.is_placeholder = false;
1155 std::pair<Type_btypes::iterator, bool> ins =
1156 Type::type_btypes.insert(val);
1157 if (!ins.second && ins.first->second.btype != NULL)
1158 return ins.first->second.btype;
1160 switch (this->classification_)
1162 case TYPE_FUNCTION:
1164 // A Go function type is a pointer to a struct type.
1165 Location loc = this->function_type()->location();
1166 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1167 Type::placeholder_pointers.push_back(this);
1169 break;
1171 case TYPE_POINTER:
1173 Location loc = Linemap::unknown_location();
1174 bt = gogo->backend()->placeholder_pointer_type("", loc, false);
1175 Type::placeholder_pointers.push_back(this);
1177 break;
1179 case TYPE_STRUCT:
1180 // We don't have to make the struct itself be a placeholder. We
1181 // are promised that we know the sizes of the struct fields.
1182 // But we may have to use a placeholder for any particular
1183 // struct field.
1185 std::vector<Backend::Btyped_identifier> bfields;
1186 get_backend_struct_fields(gogo, this->struct_type(), true, &bfields);
1187 bt = gogo->backend()->struct_type(bfields);
1189 break;
1191 case TYPE_ARRAY:
1192 if (this->is_slice_type())
1194 std::vector<Backend::Btyped_identifier> bfields;
1195 get_backend_slice_fields(gogo, this->array_type(), true, &bfields);
1196 bt = gogo->backend()->struct_type(bfields);
1198 else
1200 Btype* element = this->array_type()->get_backend_element(gogo, true);
1201 Bexpression* len = this->array_type()->get_backend_length(gogo);
1202 bt = gogo->backend()->array_type(element, len);
1204 break;
1206 case TYPE_INTERFACE:
1208 go_assert(!this->interface_type()->is_empty());
1209 std::vector<Backend::Btyped_identifier> bfields;
1210 get_backend_interface_fields(gogo, this->interface_type(), true,
1211 &bfields);
1212 bt = gogo->backend()->struct_type(bfields);
1214 break;
1216 case TYPE_SINK:
1217 case TYPE_CALL_MULTIPLE_RESULT:
1218 /* Note that various classifications were handled in the earlier
1219 switch. */
1220 default:
1221 go_unreachable();
1224 if (ins.first->second.btype == NULL)
1226 ins.first->second.btype = bt;
1227 ins.first->second.is_placeholder = true;
1229 else
1231 // A placeholder for this type got created along the way. Use
1232 // that one and ignore the one we just built.
1233 bt = ins.first->second.btype;
1236 return bt;
1239 // Complete the backend representation. This is called for a type
1240 // using a placeholder type.
1242 void
1243 Type::finish_backend(Gogo* gogo, Btype *placeholder)
1245 switch (this->classification_)
1247 case TYPE_ERROR:
1248 case TYPE_VOID:
1249 case TYPE_BOOLEAN:
1250 case TYPE_INTEGER:
1251 case TYPE_FLOAT:
1252 case TYPE_COMPLEX:
1253 case TYPE_STRING:
1254 case TYPE_NIL:
1255 go_unreachable();
1257 case TYPE_FUNCTION:
1259 Btype* bt = this->do_get_backend(gogo);
1260 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1261 go_assert(saw_errors());
1263 break;
1265 case TYPE_POINTER:
1267 Btype* bt = this->do_get_backend(gogo);
1268 if (!gogo->backend()->set_placeholder_pointer_type(placeholder, bt))
1269 go_assert(saw_errors());
1271 break;
1273 case TYPE_STRUCT:
1274 // The struct type itself is done, but we have to make sure that
1275 // all the field types are converted.
1276 this->struct_type()->finish_backend_fields(gogo);
1277 break;
1279 case TYPE_ARRAY:
1280 // The array type itself is done, but make sure the element type
1281 // is converted.
1282 this->array_type()->finish_backend_element(gogo);
1283 break;
1285 case TYPE_MAP:
1286 case TYPE_CHANNEL:
1287 go_unreachable();
1289 case TYPE_INTERFACE:
1290 // The interface type itself is done, but make sure the method
1291 // types are converted.
1292 this->interface_type()->finish_backend_methods(gogo);
1293 break;
1295 case TYPE_NAMED:
1296 case TYPE_FORWARD:
1297 go_unreachable();
1299 case TYPE_SINK:
1300 case TYPE_CALL_MULTIPLE_RESULT:
1301 default:
1302 go_unreachable();
1305 this->btype_ = placeholder;
1308 // Return a pointer to the type descriptor for this type.
1310 Bexpression*
1311 Type::type_descriptor_pointer(Gogo* gogo, Location location)
1313 Type* t = this->unalias();
1314 if (t->type_descriptor_var_ == NULL)
1316 t->make_type_descriptor_var(gogo);
1317 go_assert(t->type_descriptor_var_ != NULL);
1319 Bexpression* var_expr =
1320 gogo->backend()->var_expression(t->type_descriptor_var_, location);
1321 Bexpression* var_addr =
1322 gogo->backend()->address_expression(var_expr, location);
1323 Type* td_type = Type::make_type_descriptor_type();
1324 Btype* td_btype = td_type->get_backend(gogo);
1325 Btype* ptd_btype = gogo->backend()->pointer_type(td_btype);
1326 return gogo->backend()->convert_expression(ptd_btype, var_addr, location);
1329 // A mapping from unnamed types to type descriptor variables.
1331 Type::Type_descriptor_vars Type::type_descriptor_vars;
1333 // Build the type descriptor for this type.
1335 void
1336 Type::make_type_descriptor_var(Gogo* gogo)
1338 go_assert(this->type_descriptor_var_ == NULL);
1340 Named_type* nt = this->named_type();
1342 // We can have multiple instances of unnamed types, but we only want
1343 // to emit the type descriptor once. We use a hash table. This is
1344 // not necessary for named types, as they are unique, and we store
1345 // the type descriptor in the type itself.
1346 Bvariable** phash = NULL;
1347 if (nt == NULL)
1349 Bvariable* bvnull = NULL;
1350 std::pair<Type_descriptor_vars::iterator, bool> ins =
1351 Type::type_descriptor_vars.insert(std::make_pair(this, bvnull));
1352 if (!ins.second)
1354 // We've already built a type descriptor for this type.
1355 this->type_descriptor_var_ = ins.first->second;
1356 return;
1358 phash = &ins.first->second;
1361 // The type descriptor symbol for the unsafe.Pointer type is defined in
1362 // libgo/go-unsafe-pointer.c, so we just return a reference to that
1363 // symbol if necessary.
1364 if (this->is_unsafe_pointer_type())
1366 Location bloc = Linemap::predeclared_location();
1368 Type* td_type = Type::make_type_descriptor_type();
1369 Btype* td_btype = td_type->get_backend(gogo);
1370 Backend_name bname;
1371 gogo->type_descriptor_backend_name(this, nt, &bname);
1372 this->type_descriptor_var_ =
1373 gogo->backend()->immutable_struct_reference(bname.name(),
1374 bname.optional_asm_name(),
1375 td_btype,
1376 bloc);
1378 if (phash != NULL)
1379 *phash = this->type_descriptor_var_;
1380 return;
1383 Backend_name bname;
1384 gogo->type_descriptor_backend_name(this, nt, &bname);
1386 // Build the contents of the type descriptor.
1387 Expression* initializer = this->do_type_descriptor(gogo, NULL);
1388 initializer->determine_type_no_context(gogo);
1390 Btype* initializer_btype = initializer->type()->get_backend(gogo);
1392 Location loc = nt == NULL ? Linemap::predeclared_location() : nt->location();
1394 const Package* dummy;
1395 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
1397 this->type_descriptor_var_ =
1398 gogo->backend()->immutable_struct_reference(bname.name(),
1399 bname.optional_asm_name(),
1400 initializer_btype,
1401 loc);
1402 if (phash != NULL)
1403 *phash = this->type_descriptor_var_;
1404 return;
1407 // See if this type descriptor can appear in multiple packages.
1408 bool is_common = false;
1409 if (nt != NULL)
1411 // We create the descriptor for a builtin type whenever we need
1412 // it.
1413 is_common = nt->is_builtin();
1415 else
1417 // This is an unnamed type. The descriptor could be defined in
1418 // any package where it is needed, and the linker will pick one
1419 // descriptor to keep.
1420 is_common = true;
1423 // We are going to build the type descriptor in this package. We
1424 // must create the variable before we convert the initializer to the
1425 // backend representation, because the initializer may refer to the
1426 // type descriptor of this type. By setting type_descriptor_var_ we
1427 // ensure that type_descriptor_pointer will work if called while
1428 // converting INITIALIZER.
1430 unsigned int flags = 0;
1431 if (is_common)
1432 flags |= Backend::variable_is_common;
1433 this->type_descriptor_var_ =
1434 gogo->backend()->immutable_struct(bname.name(), bname.optional_asm_name(),
1435 flags, initializer_btype, loc);
1436 if (phash != NULL)
1437 *phash = this->type_descriptor_var_;
1439 Translate_context context(gogo, NULL, NULL, NULL);
1440 context.set_is_const();
1441 Bexpression* binitializer = initializer->get_backend(&context);
1443 gogo->backend()->immutable_struct_set_init(this->type_descriptor_var_,
1444 bname.name(), flags,
1445 initializer_btype, loc,
1446 binitializer);
1448 // For types that may be created by reflection, add it to the
1449 // list of which we will register the type descriptor to the
1450 // runtime.
1451 // Do not add generated incomparable array/struct types, see
1452 // issue #22605.
1453 if (is_common
1454 && (this->points_to() != NULL
1455 || this->channel_type() != NULL
1456 || this->map_type() != NULL
1457 || this->function_type() != NULL
1458 || this->is_slice_type()
1459 || (this->struct_type() != NULL
1460 && !this->struct_type()->is_struct_incomparable())
1461 || (this->array_type() != NULL
1462 && !this->array_type()->is_array_incomparable())))
1463 gogo->add_type_descriptor(this);
1466 // Return true if this type descriptor is defined in a different
1467 // package. If this returns true it sets *PACKAGE to the package.
1469 bool
1470 Type::type_descriptor_defined_elsewhere(Named_type* nt,
1471 const Package** package)
1473 if (nt != NULL)
1475 if (nt->named_object()->package() != NULL)
1477 // This is a named type defined in a different package. The
1478 // type descriptor should be defined in that package.
1479 *package = nt->named_object()->package();
1480 return true;
1483 else
1485 if (this->points_to() != NULL
1486 && this->points_to()->unalias()->named_type() != NULL
1487 && this->points_to()->unalias()->named_type()->named_object()->package() != NULL)
1489 // This is an unnamed pointer to a named type defined in a
1490 // different package. The descriptor should be defined in
1491 // that package.
1492 *package = this->points_to()->unalias()->named_type()->named_object()->package();
1493 return true;
1496 return false;
1499 // Return a composite literal for a type descriptor.
1501 Expression*
1502 Type::type_descriptor(Gogo* gogo, Type* type)
1504 Expression* ret = type->do_type_descriptor(gogo, NULL);
1505 ret->determine_type_no_context(gogo);
1506 return ret;
1509 // Return a composite literal for a type descriptor with a name.
1511 Expression*
1512 Type::named_type_descriptor(Gogo* gogo, Type* type, Named_type* name)
1514 go_assert(name != NULL && type->named_type() != name);
1515 Expression* ret = type->do_type_descriptor(gogo, name);
1516 ret->determine_type_no_context(gogo);
1517 return ret;
1520 // Make a builtin struct type from a list of fields. The fields are
1521 // pairs of a name and a type.
1523 Struct_type*
1524 Type::make_builtin_struct_type(int nfields, ...)
1526 va_list ap;
1527 va_start(ap, nfields);
1529 Location bloc = Linemap::predeclared_location();
1530 Struct_field_list* sfl = new Struct_field_list();
1531 for (int i = 0; i < nfields; i++)
1533 const char* field_name = va_arg(ap, const char *);
1534 Type* type = va_arg(ap, Type*);
1535 sfl->push_back(Struct_field(Typed_identifier(field_name, type, bloc)));
1538 va_end(ap);
1540 Struct_type* ret = Type::make_struct_type(sfl, bloc);
1541 ret->set_is_struct_incomparable();
1542 return ret;
1545 // A list of builtin named types.
1547 std::vector<Named_type*> Type::named_builtin_types;
1549 // Make a builtin named type.
1551 Named_type*
1552 Type::make_builtin_named_type(const char* name, Type* type)
1554 Location bloc = Linemap::predeclared_location();
1555 Named_object* no = Named_object::make_type(name, NULL, type, bloc);
1556 Named_type* ret = no->type_value();
1557 Type::named_builtin_types.push_back(ret);
1558 return ret;
1561 // Convert the named builtin types.
1563 void
1564 Type::convert_builtin_named_types(Gogo* gogo)
1566 for (std::vector<Named_type*>::const_iterator p =
1567 Type::named_builtin_types.begin();
1568 p != Type::named_builtin_types.end();
1569 ++p)
1571 bool r = (*p)->verify(gogo);
1572 go_assert(r);
1573 (*p)->convert(gogo);
1577 // Values to store in the tflag field of a type descriptor. This must
1578 // match the definitions in libgo/go/runtime/type.go.
1580 const int TFLAG_REGULAR_MEMORY = 1 << 3;
1582 // Return the type of a type descriptor. We should really tie this to
1583 // runtime.Type rather than copying it. This must match the struct "_type"
1584 // declared in libgo/go/runtime/type.go.
1586 Type*
1587 Type::make_type_descriptor_type()
1589 static Type* ret;
1590 if (ret == NULL)
1592 Location bloc = Linemap::predeclared_location();
1594 Type* uint8_type = Type::lookup_integer_type("uint8");
1595 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
1596 Type* uint32_type = Type::lookup_integer_type("uint32");
1597 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1598 Type* string_type = Type::lookup_string_type();
1599 Type* pointer_string_type = Type::make_pointer_type(string_type);
1601 // This is an unnamed version of unsafe.Pointer. Perhaps we
1602 // should use the named version instead, although that would
1603 // require us to create the unsafe package if it has not been
1604 // imported. It probably doesn't matter.
1605 Type* void_type = Type::make_void_type();
1606 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1608 Typed_identifier_list* params = new Typed_identifier_list();
1609 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
1610 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
1612 Typed_identifier_list* results = new Typed_identifier_list();
1613 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
1615 Type* equal_fntype = Type::make_function_type(NULL, params, results,
1616 bloc);
1618 // Forward declaration for the type descriptor type.
1619 Named_object* named_type_descriptor_type =
1620 Named_object::make_type_declaration("_type", NULL, bloc);
1621 Type* ft = Type::make_forward_declaration(named_type_descriptor_type);
1622 Type* pointer_type_descriptor_type = Type::make_pointer_type(ft);
1624 // The type of a method on a concrete type.
1625 Struct_type* method_type =
1626 Type::make_builtin_struct_type(5,
1627 "name", pointer_string_type,
1628 "pkgPath", pointer_string_type,
1629 "mtyp", pointer_type_descriptor_type,
1630 "typ", pointer_type_descriptor_type,
1631 "tfn", unsafe_pointer_type);
1632 Named_type* named_method_type =
1633 Type::make_builtin_named_type("method", method_type);
1635 // Information for types with a name or methods.
1636 Type* slice_named_method_type =
1637 Type::make_array_type(named_method_type, NULL);
1638 Struct_type* uncommon_type =
1639 Type::make_builtin_struct_type(3,
1640 "name", pointer_string_type,
1641 "pkgPath", pointer_string_type,
1642 "methods", slice_named_method_type);
1643 Named_type* named_uncommon_type =
1644 Type::make_builtin_named_type("uncommonType", uncommon_type);
1646 Type* pointer_uncommon_type =
1647 Type::make_pointer_type(named_uncommon_type);
1649 // The type descriptor type.
1651 Struct_type* type_descriptor_type =
1652 Type::make_builtin_struct_type(12,
1653 "size", uintptr_type,
1654 "ptrdata", uintptr_type,
1655 "hash", uint32_type,
1656 "tflag", uint8_type,
1657 "align", uint8_type,
1658 "fieldAlign", uint8_type,
1659 "kind", uint8_type,
1660 "equal", equal_fntype,
1661 "gcdata", pointer_uint8_type,
1662 "string", pointer_string_type,
1663 "", pointer_uncommon_type,
1664 "ptrToThis",
1665 pointer_type_descriptor_type);
1667 Named_type* named = Type::make_builtin_named_type("_type",
1668 type_descriptor_type);
1670 named_type_descriptor_type->set_type_value(named);
1672 ret = named;
1675 return ret;
1678 // Make the type of a pointer to a type descriptor as represented in
1679 // Go.
1681 Type*
1682 Type::make_type_descriptor_ptr_type()
1684 static Type* ret;
1685 if (ret == NULL)
1686 ret = Type::make_pointer_type(Type::make_type_descriptor_type());
1687 return ret;
1690 // Return the alignment required by the memequalN function. N is a
1691 // type size: 16, 32, 64, or 128. The memequalN functions are defined
1692 // in libgo/go/runtime/alg.go.
1694 int64_t
1695 Type::memequal_align(Gogo* gogo, int size)
1697 const char* tn;
1698 switch (size)
1700 case 16:
1701 tn = "int16";
1702 break;
1703 case 32:
1704 tn = "int32";
1705 break;
1706 case 64:
1707 tn = "int64";
1708 break;
1709 case 128:
1710 // The code uses [2]int64, which must have the same alignment as
1711 // int64.
1712 tn = "int64";
1713 break;
1714 default:
1715 go_unreachable();
1718 Type* t = Type::lookup_integer_type(tn);
1720 int64_t ret;
1721 if (!t->backend_type_align(gogo, &ret))
1722 go_unreachable();
1723 return ret;
1726 // Return whether this type needs specially built type functions.
1727 // This returns true for types that are comparable and either can not
1728 // use an identity comparison, or are a non-standard size.
1730 bool
1731 Type::needs_specific_type_functions(Gogo* gogo)
1733 Named_type* nt = this->named_type();
1734 if (nt != NULL && nt->is_alias())
1735 return false;
1736 if (!this->is_comparable())
1737 return false;
1738 if (!this->compare_is_identity(gogo))
1739 return true;
1741 // We create a few predeclared types for type descriptors; they are
1742 // really just for the backend and don't need hash or equality
1743 // functions.
1744 if (nt != NULL && Linemap::is_predeclared_location(nt->location()))
1745 return false;
1747 int64_t size, align;
1748 if (!this->backend_type_size(gogo, &size)
1749 || !this->backend_type_align(gogo, &align))
1751 go_assert(saw_errors());
1752 return false;
1754 // This switch matches the one in Type::equal_function.
1755 switch (size)
1757 case 0:
1758 case 1:
1759 case 2:
1760 return align < Type::memequal_align(gogo, 16);
1761 case 4:
1762 return align < Type::memequal_align(gogo, 32);
1763 case 8:
1764 return align < Type::memequal_align(gogo, 64);
1765 case 16:
1766 return align < Type::memequal_align(gogo, 128);
1767 default:
1768 return true;
1772 // Return the runtime function that computes the hash of this type.
1773 // HASH_FNTYPE is the type of the hash function function, for
1774 // convenience; it may be NULL. This returns NULL if the type is not
1775 // comparable.
1777 Named_object*
1778 Type::hash_function(Gogo* gogo, Function_type* hash_fntype)
1780 if (this->named_type() != NULL)
1781 go_assert(!this->named_type()->is_alias());
1783 if (!this->is_comparable())
1784 return NULL;
1786 if (hash_fntype == NULL)
1788 Location bloc = Linemap::predeclared_location();
1789 Type* uintptr_type = Type::lookup_integer_type("uintptr");
1790 Type* void_type = Type::make_void_type();
1791 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
1792 Typed_identifier_list* params = new Typed_identifier_list();
1793 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
1794 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
1795 Typed_identifier_list* results = new Typed_identifier_list();
1796 results->push_back(Typed_identifier("", uintptr_type, bloc));
1797 hash_fntype = Type::make_function_type(NULL, params, results, bloc);
1800 const char* hash_fnname;
1801 if (this->compare_is_identity(gogo))
1803 int64_t size;
1804 if (!this->backend_type_size(gogo, &size))
1806 go_assert(saw_errors());
1807 return NULL;
1809 switch (size)
1811 case 0:
1812 hash_fnname = "runtime.memhash0";
1813 break;
1814 case 1:
1815 hash_fnname = "runtime.memhash8";
1816 break;
1817 case 2:
1818 hash_fnname = "runtime.memhash16";
1819 break;
1820 case 4:
1821 hash_fnname = "runtime.memhash32";
1822 break;
1823 case 8:
1824 hash_fnname = "runtime.memhash64";
1825 break;
1826 case 16:
1827 hash_fnname = "runtime.memhash128";
1828 break;
1829 default:
1830 // We don't have a built-in function for a type of this
1831 // size. Build a function to use that calls the generic
1832 // hash functions for identity, passing the size.
1833 return this->build_hash_function(gogo, size, hash_fntype);
1836 else
1838 switch (this->base()->classification())
1840 case Type::TYPE_ERROR:
1841 case Type::TYPE_VOID:
1842 case Type::TYPE_NIL:
1843 case Type::TYPE_FUNCTION:
1844 case Type::TYPE_MAP:
1845 // For these types is_comparable should have returned false.
1846 go_unreachable();
1848 case Type::TYPE_BOOLEAN:
1849 case Type::TYPE_INTEGER:
1850 case Type::TYPE_POINTER:
1851 case Type::TYPE_CHANNEL:
1852 // For these types compare_is_identity should have returned true.
1853 go_unreachable();
1855 case Type::TYPE_FLOAT:
1856 switch (this->float_type()->bits())
1858 case 32:
1859 hash_fnname = "runtime.f32hash";
1860 break;
1861 case 64:
1862 hash_fnname = "runtime.f64hash";
1863 break;
1864 default:
1865 go_unreachable();
1867 break;
1869 case Type::TYPE_COMPLEX:
1870 switch (this->complex_type()->bits())
1872 case 64:
1873 hash_fnname = "runtime.c64hash";
1874 break;
1875 case 128:
1876 hash_fnname = "runtime.c128hash";
1877 break;
1878 default:
1879 go_unreachable();
1881 break;
1883 case Type::TYPE_STRING:
1884 hash_fnname = "runtime.strhash";
1885 break;
1887 case Type::TYPE_STRUCT:
1888 // This is a struct which can not be compared using a simple
1889 // identity function. We need to build a function to
1890 // compute the hash.
1891 return this->build_hash_function(gogo, -1, hash_fntype);
1893 case Type::TYPE_ARRAY:
1894 if (this->is_slice_type())
1896 // Type::is_compatible_for_comparison should have
1897 // returned false.
1898 go_unreachable();
1900 else
1902 // This is an array which can not be compared using a
1903 // simple identity function. We need to build a
1904 // function to compute the hash.
1905 return this->build_hash_function(gogo, -1, hash_fntype);
1907 break;
1909 case Type::TYPE_INTERFACE:
1910 if (this->interface_type()->is_empty())
1911 hash_fnname = "runtime.nilinterhash";
1912 else
1913 hash_fnname = "runtime.interhash";
1914 break;
1916 case Type::TYPE_NAMED:
1917 case Type::TYPE_FORWARD:
1918 go_unreachable();
1920 default:
1921 go_unreachable();
1925 Location bloc = Linemap::predeclared_location();
1926 Named_object *hash_fn = Named_object::make_function_declaration(hash_fnname,
1927 NULL,
1928 hash_fntype,
1929 bloc);
1930 hash_fn->func_declaration_value()->set_asm_name(hash_fnname);
1931 return hash_fn;
1934 // A hash table mapping types to the specific hash functions.
1936 Type::Type_function Type::type_hash_functions_table;
1938 // Build a hash function that is specific to a type: if SIZE == -1,
1939 // this is a struct or array type that cannot use an identity
1940 // comparison. Otherwise, it is a type that uses an identity
1941 // comparison but is not one of the standard supported sizes.
1943 // Unlike an equality function, hash functions are not in type
1944 // descriptors, so we can't assume that a named type has defined a
1945 // hash function in the package that defines the type. So hash
1946 // functions are always defined locally. FIXME: It would be better to
1947 // define hash functions with comdat linkage so that duplicate hash
1948 // functions can be coalesced at link time.
1950 Named_object*
1951 Type::build_hash_function(Gogo* gogo, int64_t size, Function_type* hash_fntype)
1953 Type* type = this->base();
1955 std::pair<Type*, Named_object*> val(type, NULL);
1956 std::pair<Type_function::iterator, bool> ins =
1957 Type::type_hash_functions_table.insert(val);
1958 if (!ins.second)
1960 // We already have a function for this type.
1961 return ins.first->second;
1964 Backend_name bname;
1965 gogo->hash_function_name(type, &bname);
1967 Location bloc = Linemap::predeclared_location();
1969 Named_object* hash_fn = gogo->declare_package_function(bname.name(),
1970 hash_fntype, bloc);
1972 ins.first->second = hash_fn;
1974 if (gogo->in_global_scope())
1975 type->write_hash_function(gogo, size, &bname, hash_fntype);
1976 else
1977 gogo->queue_hash_function(type, size, &bname, hash_fntype);
1979 return hash_fn;
1982 // Write the hash function for a type that needs it written specially.
1984 void
1985 Type::write_hash_function(Gogo* gogo, int64_t size, const Backend_name* bname,
1986 Function_type* hash_fntype)
1988 Location bloc = Linemap::predeclared_location();
1990 if (gogo->specific_type_functions_are_written())
1992 go_assert(saw_errors());
1993 return;
1996 go_assert(this->is_comparable());
1998 Named_object* hash_fn = gogo->start_function(bname->name(), hash_fntype,
1999 false, bloc);
2000 hash_fn->func_value()->set_asm_name(bname->asm_name());
2001 hash_fn->func_value()->set_is_type_specific_function();
2002 gogo->start_block(bloc);
2004 if (size != -1)
2005 this->write_identity_hash(gogo, hash_fn, size);
2006 else if (this->struct_type() != NULL)
2007 this->struct_type()->write_hash_function(gogo, hash_fn, hash_fntype);
2008 else if (this->array_type() != NULL)
2009 this->array_type()->write_hash_function(gogo, hash_fn, hash_fntype);
2010 else
2011 go_unreachable();
2013 Block* b = gogo->finish_block(bloc);
2014 gogo->add_block(b, bloc);
2015 b->determine_types(gogo);
2016 gogo->lower_block(hash_fn, b);
2017 gogo->order_block(b);
2018 gogo->remove_shortcuts_in_block(b);
2019 gogo->finish_function(bloc);
2021 // Build the function descriptor for the type descriptor to refer to.
2022 hash_fn->func_value()->descriptor(gogo, hash_fn);
2025 // Write a hash function for a type that can use an identity hash but
2026 // is not one of the standard supported sizes. For example, this
2027 // would be used for the type [3]byte. This builds a return statement
2028 // that returns a call to the memhash function, passing the key and
2029 // seed from the function arguments (already constructed before this
2030 // is called), and the constant size.
2032 void
2033 Type::write_identity_hash(Gogo* gogo, Named_object* function, int64_t size)
2035 Location bloc = Linemap::predeclared_location();
2037 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2038 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2040 Typed_identifier_list* params = new Typed_identifier_list();
2041 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
2042 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
2043 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2045 Typed_identifier_list* results = new Typed_identifier_list();
2046 results->push_back(Typed_identifier("", uintptr_type, bloc));
2048 Function_type* memhash_fntype = Type::make_function_type(NULL, params,
2049 results, bloc);
2051 Named_object* memhash =
2052 Named_object::make_function_declaration("runtime.memhash", NULL,
2053 memhash_fntype, bloc);
2054 memhash->func_declaration_value()->set_asm_name("runtime.memhash");
2056 Named_object* key_arg = gogo->lookup("key", NULL);
2057 go_assert(key_arg != NULL);
2058 Named_object* seed_arg = gogo->lookup("seed", NULL);
2059 go_assert(seed_arg != NULL);
2061 Expression* key_ref = Expression::make_var_reference(key_arg, bloc);
2062 Expression* seed_ref = Expression::make_var_reference(seed_arg, bloc);
2063 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2064 bloc);
2065 Expression_list* args = new Expression_list();
2066 args->push_back(key_ref);
2067 args->push_back(seed_ref);
2068 args->push_back(size_arg);
2069 Expression* func = Expression::make_func_reference(memhash, NULL, bloc);
2070 Expression* call = Expression::make_call(func, args, false, bloc);
2072 Expression_list* vals = new Expression_list();
2073 vals->push_back(call);
2074 Statement* s = Statement::make_return_statement(function, vals, bloc);
2075 s->determine_types(gogo);
2076 gogo->add_statement(s);
2079 // Return the runtime function that compares whether two values of
2080 // this type are equal. If NAME is not NULL it is the name of this
2081 // type. EQUAL_FNTYPE is the type of the equality function, for
2082 // convenience; it may be NULL. This returns NULL if the type is not
2083 // comparable.
2085 Named_object*
2086 Type::equal_function(Gogo* gogo, Named_type* name, Function_type* equal_fntype)
2088 if (this->named_type() != NULL)
2089 go_assert(!this->named_type()->is_alias());
2091 // If the unaliased type is not a named type, then the type does not
2092 // have a name after all.
2093 if (name != NULL)
2094 name = name->unalias()->named_type();
2096 if (!this->is_comparable())
2097 return NULL;
2099 if (equal_fntype == NULL)
2101 Location bloc = Linemap::predeclared_location();
2102 Type* void_type = Type::make_void_type();
2103 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
2104 Typed_identifier_list* params = new Typed_identifier_list();
2105 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2106 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2107 Typed_identifier_list* results = new Typed_identifier_list();
2108 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2109 equal_fntype = Type::make_function_type(NULL, params, results, bloc);
2112 const char* equal_fnname;
2113 if (this->compare_is_identity(gogo))
2115 int64_t size, align;
2116 if (!this->backend_type_size(gogo, &size)
2117 || !this->backend_type_align(gogo, &align))
2119 go_assert(saw_errors());
2120 return NULL;
2122 bool build_function = false;
2123 // This switch matches the one in Type::needs_specific_type_functions.
2124 // The alignment tests are because of the memequal functions,
2125 // which assume that the values are aligned as required for an
2126 // integer of that size.
2127 switch (size)
2129 case 0:
2130 equal_fnname = "runtime.memequal0";
2131 break;
2132 case 1:
2133 equal_fnname = "runtime.memequal8";
2134 break;
2135 case 2:
2136 if (align < Type::memequal_align(gogo, 16))
2137 build_function = true;
2138 else
2139 equal_fnname = "runtime.memequal16";
2140 break;
2141 case 4:
2142 if (align < Type::memequal_align(gogo, 32))
2143 build_function = true;
2144 else
2145 equal_fnname = "runtime.memequal32";
2146 break;
2147 case 8:
2148 if (align < Type::memequal_align(gogo, 64))
2149 build_function = true;
2150 else
2151 equal_fnname = "runtime.memequal64";
2152 break;
2153 case 16:
2154 if (align < Type::memequal_align(gogo, 128))
2155 build_function = true;
2156 else
2157 equal_fnname = "runtime.memequal128";
2158 break;
2159 default:
2160 build_function = true;
2161 break;
2163 if (build_function)
2165 // We don't have a built-in function for a type of this size
2166 // and alignment. Build a function to use that calls the
2167 // generic equality functions for identity, passing the size.
2168 return this->build_equal_function(gogo, name, size, equal_fntype);
2171 else
2173 switch (this->base()->classification())
2175 case Type::TYPE_ERROR:
2176 case Type::TYPE_VOID:
2177 case Type::TYPE_NIL:
2178 case Type::TYPE_FUNCTION:
2179 case Type::TYPE_MAP:
2180 // For these types is_comparable should have returned false.
2181 go_unreachable();
2183 case Type::TYPE_BOOLEAN:
2184 case Type::TYPE_INTEGER:
2185 case Type::TYPE_POINTER:
2186 case Type::TYPE_CHANNEL:
2187 // For these types compare_is_identity should have returned true.
2188 go_unreachable();
2190 case Type::TYPE_FLOAT:
2191 switch (this->float_type()->bits())
2193 case 32:
2194 equal_fnname = "runtime.f32equal";
2195 break;
2196 case 64:
2197 equal_fnname = "runtime.f64equal";
2198 break;
2199 default:
2200 go_unreachable();
2202 break;
2204 case Type::TYPE_COMPLEX:
2205 switch (this->complex_type()->bits())
2207 case 64:
2208 equal_fnname = "runtime.c64equal";
2209 break;
2210 case 128:
2211 equal_fnname = "runtime.c128equal";
2212 break;
2213 default:
2214 go_unreachable();
2216 break;
2218 case Type::TYPE_STRING:
2219 equal_fnname = "runtime.strequal";
2220 break;
2222 case Type::TYPE_STRUCT:
2223 // This is a struct which can not be compared using a simple
2224 // identity function. We need to build a function for
2225 // comparison.
2226 return this->build_equal_function(gogo, name, -1, equal_fntype);
2228 case Type::TYPE_ARRAY:
2229 if (this->is_slice_type())
2231 // Type::is_compatible_for_comparison should have
2232 // returned false.
2233 go_unreachable();
2235 else
2237 // This is an array which can not be compared using a
2238 // simple identity function. We need to build a
2239 // function for comparison.
2240 return this->build_equal_function(gogo, name, -1, equal_fntype);
2242 break;
2244 case Type::TYPE_INTERFACE:
2245 if (this->interface_type()->is_empty())
2246 equal_fnname = "runtime.nilinterequal";
2247 else
2248 equal_fnname = "runtime.interequal";
2249 break;
2251 case Type::TYPE_NAMED:
2252 case Type::TYPE_FORWARD:
2253 go_unreachable();
2255 default:
2256 go_unreachable();
2260 Location bloc = Linemap::predeclared_location();
2261 Named_object* equal_fn =
2262 Named_object::make_function_declaration(equal_fnname, NULL, equal_fntype,
2263 bloc);
2264 equal_fn->func_declaration_value()->set_asm_name(equal_fnname);
2265 return equal_fn;
2268 // A hash table mapping types to the specific equal functions.
2270 Type::Type_function Type::type_equal_functions_table;
2272 // Build an equality function that is specific to a type: if SIZE ==
2273 // -1, this is a struct or array type that cannot use an identity
2274 // comparison. Otherwise, it is a type that uses an identity
2275 // comparison but is not one of the standard supported sizes or it is
2276 // not aligned as needed.
2278 Named_object*
2279 Type::build_equal_function(Gogo* gogo, Named_type* name, int64_t size,
2280 Function_type* equal_fntype)
2282 std::pair<Type*, Named_object*> val(name != NULL ? name : this, nullptr);
2283 std::pair<Type_function::iterator, bool> ins =
2284 Type::type_equal_functions_table.insert(val);
2285 if (!ins.second)
2287 // We already have a function for this type.
2288 return ins.first->second;
2291 Backend_name bname;
2292 gogo->equal_function_name(this, name, &bname);
2294 Location bloc = Linemap::predeclared_location();
2296 const Package* package = NULL;
2297 bool is_defined_elsewhere =
2298 this->type_descriptor_defined_elsewhere(name, &package);
2300 Named_object* equal_fn;
2301 if (is_defined_elsewhere)
2302 equal_fn = Named_object::make_function_declaration(bname.name(), package,
2303 equal_fntype, bloc);
2304 else
2305 equal_fn = gogo->declare_package_function(bname.name(), equal_fntype, bloc);
2307 ins.first->second = equal_fn;
2309 if (is_defined_elsewhere)
2310 equal_fn->func_declaration_value()->set_asm_name(bname.asm_name());
2311 else
2313 if (gogo->in_global_scope())
2314 this->write_equal_function(gogo, name, size, &bname, equal_fntype);
2315 else
2316 gogo->queue_equal_function(this, name, size, &bname, equal_fntype);
2319 return equal_fn;
2322 // Write the equal function for a type that needs it written
2323 // specially.
2325 void
2326 Type::write_equal_function(Gogo* gogo, Named_type* name, int64_t size,
2327 const Backend_name* bname,
2328 Function_type* equal_fntype)
2330 Location bloc = Linemap::predeclared_location();
2332 if (gogo->specific_type_functions_are_written())
2334 go_assert(saw_errors());
2335 return;
2338 go_assert(this->is_comparable());
2340 Named_object* equal_fn = gogo->start_function(bname->name(), equal_fntype,
2341 false, bloc);
2342 equal_fn->func_value()->set_asm_name(bname->asm_name());
2343 equal_fn->func_value()->set_is_type_specific_function();
2344 gogo->start_block(bloc);
2346 if (size != -1)
2347 this->write_identity_equal(gogo, equal_fn, size);
2348 else if (name != NULL && name->real_type()->named_type() != NULL)
2349 this->write_named_equal(gogo, equal_fn, name);
2350 else if (this->struct_type() != NULL)
2351 this->struct_type()->write_equal_function(gogo, equal_fn, name);
2352 else if (this->array_type() != NULL)
2353 this->array_type()->write_equal_function(gogo, equal_fn, name);
2354 else
2355 go_unreachable();
2357 Block* b = gogo->finish_block(bloc);
2358 gogo->add_block(b, bloc);
2359 b->determine_types(gogo);
2360 gogo->lower_block(equal_fn, b);
2361 gogo->order_block(b);
2362 gogo->remove_shortcuts_in_block(b);
2363 gogo->finish_function(bloc);
2365 // Build the function descriptor for the type descriptor to refer to.
2366 equal_fn->func_value()->descriptor(gogo, equal_fn);
2369 // Write an equality function for a type that can use an identity
2370 // equality comparison but is not one of the standard supported sizes.
2371 // For example, this would be used for the type [3]byte. This builds
2372 // a return statement that returns a call to the memequal function,
2373 // passing the two keys from the function arguments (already
2374 // constructed before this is called), and the constant size.
2376 void
2377 Type::write_identity_equal(Gogo* gogo, Named_object* function, int64_t size)
2379 Location bloc = Linemap::predeclared_location();
2381 Type* unsafe_pointer_type = Type::make_pointer_type(Type::make_void_type());
2382 Type* uintptr_type = Type::lookup_integer_type("uintptr");
2384 Typed_identifier_list* params = new Typed_identifier_list();
2385 params->push_back(Typed_identifier("key1", unsafe_pointer_type, bloc));
2386 params->push_back(Typed_identifier("key2", unsafe_pointer_type, bloc));
2387 params->push_back(Typed_identifier("size", uintptr_type, bloc));
2389 Typed_identifier_list* results = new Typed_identifier_list();
2390 results->push_back(Typed_identifier("", Type::lookup_bool_type(), bloc));
2392 Function_type* memequal_fntype = Type::make_function_type(NULL, params,
2393 results, bloc);
2395 Named_object* memequal =
2396 Named_object::make_function_declaration("runtime.memequal", NULL,
2397 memequal_fntype, bloc);
2398 memequal->func_declaration_value()->set_asm_name("runtime.memequal");
2400 Named_object* key1_arg = gogo->lookup("key1", NULL);
2401 go_assert(key1_arg != NULL);
2402 Named_object* key2_arg = gogo->lookup("key2", NULL);
2403 go_assert(key2_arg != NULL);
2405 Expression* key1_ref = Expression::make_var_reference(key1_arg, bloc);
2406 Expression* key2_ref = Expression::make_var_reference(key2_arg, bloc);
2407 Expression* size_arg = Expression::make_integer_int64(size, uintptr_type,
2408 bloc);
2409 Expression_list* args = new Expression_list();
2410 args->push_back(key1_ref);
2411 args->push_back(key2_ref);
2412 args->push_back(size_arg);
2413 Expression* func = Expression::make_func_reference(memequal, NULL, bloc);
2414 Expression* call = Expression::make_call(func, args, false, bloc);
2416 Expression_list* vals = new Expression_list();
2417 vals->push_back(call);
2418 Statement* s = Statement::make_return_statement(function, vals, bloc);
2419 s->determine_types(gogo);
2420 gogo->add_statement(s);
2423 // Write an equality function that simply calls the equality function
2424 // for a named type. This is used when one named type is defined as
2425 // another. This ensures that this case works when the other named
2426 // type is defined in another package and relies on calling equality
2427 // functions defined only in that package.
2429 void
2430 Type::write_named_equal(Gogo* gogo, Named_object* function, Named_type* name)
2432 Location bloc = Linemap::predeclared_location();
2434 // The pointers to the types we are going to compare. These have
2435 // type unsafe.Pointer.
2436 Named_object* key1_arg = gogo->lookup("key1", NULL);
2437 Named_object* key2_arg = gogo->lookup("key2", NULL);
2438 go_assert(key1_arg != NULL && key2_arg != NULL);
2440 Named_type* base_type = name->real_type()->named_type();
2441 go_assert(base_type != NULL);
2443 // Build temporaries with the base type.
2444 Type* pt = Type::make_pointer_type(base_type);
2446 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
2447 ref = Expression::make_cast(pt, ref, bloc);
2448 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
2449 p1->determine_types(gogo);
2450 gogo->add_statement(p1);
2452 ref = Expression::make_var_reference(key2_arg, bloc);
2453 ref = Expression::make_cast(pt, ref, bloc);
2454 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
2455 p2->determine_types(gogo);
2456 gogo->add_statement(p2);
2458 // Compare the values for equality.
2459 Expression* t1 = Expression::make_temporary_reference(p1, bloc);
2460 t1 = Expression::make_dereference(t1, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2462 Expression* t2 = Expression::make_temporary_reference(p2, bloc);
2463 t2 = Expression::make_dereference(t2, Expression::NIL_CHECK_NOT_NEEDED, bloc);
2465 Expression* cond = Expression::make_binary(OPERATOR_EQEQ, t1, t2, bloc);
2467 // Return the equality comparison.
2468 Expression_list* vals = new Expression_list();
2469 vals->push_back(cond);
2470 Statement* s = Statement::make_return_statement(function, vals, bloc);
2471 s->determine_types(gogo);
2472 gogo->add_statement(s);
2475 // Return whether this type is stored directly in an interface's
2476 // data word.
2478 // Since finalize_methods runs before type checking, we may see a
2479 // malformed type like 'type T struct { x T }'. Use a visited map
2480 // to avoid infinite recursion.
2482 bool
2483 Type::is_direct_iface_type() const
2485 Unordered_set(const Type*) visited;
2486 return this->is_direct_iface_type_helper(&visited);
2489 bool
2490 Type::is_direct_iface_type_helper(Unordered_set(const Type*)* visited) const
2492 if (this->points_to() != NULL)
2494 // Pointers to notinheap types must be stored indirectly. See
2495 // https://golang.org/issue/42076.
2496 if (!this->points_to()->in_heap())
2497 return false;
2498 return true;
2501 if (this->channel_type() != NULL
2502 || this->function_type() != NULL
2503 || this->map_type() != NULL)
2504 return true;
2506 std::pair<Unordered_set(const Type*)::iterator, bool> ins
2507 = visited->insert(this);
2508 if (!ins.second)
2509 // malformed circular type
2510 return false;
2512 const Struct_type* st = this->struct_type();
2513 if (st != NULL)
2514 return (st->field_count() == 1
2515 && st->field(0)->type()->is_direct_iface_type_helper(visited));
2516 const Array_type* at = this->array_type();
2517 if (at != NULL && !at->is_slice_type())
2519 int64_t len;
2520 return (at->int_length(&len) && len == 1
2521 && at->element_type()->is_direct_iface_type_helper(visited));
2523 return false;
2526 // Return a composite literal for the type descriptor for a plain type
2527 // of kind RUNTIME_TYPE_KIND named NAME.
2529 Expression*
2530 Type::type_descriptor_constructor(Gogo* gogo, int runtime_type_kind,
2531 Named_type* name, const Methods* methods,
2532 bool only_value_methods)
2534 Location bloc = Linemap::predeclared_location();
2536 Type* td_type = Type::make_type_descriptor_type();
2537 const Struct_field_list* fields = td_type->struct_type()->fields();
2539 Expression_list* vals = new Expression_list();
2540 vals->reserve(12);
2542 bool has_pointer;
2543 if (name != NULL)
2544 has_pointer = name->has_pointer();
2545 else
2546 has_pointer = this->has_pointer();
2547 if (!has_pointer)
2548 runtime_type_kind |= RUNTIME_TYPE_KIND_NO_POINTERS;
2549 if (this->is_direct_iface_type())
2550 runtime_type_kind |= RUNTIME_TYPE_KIND_DIRECT_IFACE;
2551 int64_t ptrsize;
2552 int64_t ptrdata;
2553 if (has_pointer && this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2554 runtime_type_kind |= RUNTIME_TYPE_KIND_GC_PROG;
2556 Struct_field_list::const_iterator p = fields->begin();
2557 go_assert(p->is_field_name("size"));
2558 Expression::Type_info type_info = Expression::TYPE_INFO_SIZE;
2559 vals->push_back(Expression::make_type_info(this, type_info));
2561 ++p;
2562 go_assert(p->is_field_name("ptrdata"));
2563 type_info = Expression::TYPE_INFO_DESCRIPTOR_PTRDATA;
2564 if (has_pointer)
2565 vals->push_back(Expression::make_type_info(this, type_info));
2566 else
2567 vals->push_back(Expression::make_integer_ul(0, p->type(), bloc));
2569 ++p;
2570 go_assert(p->is_field_name("hash"));
2571 unsigned int h;
2572 if (name != NULL)
2573 h = name->hash_for_method(gogo, Type::COMPARE_TAGS);
2574 else
2575 h = this->hash_for_method(gogo, Type::COMPARE_TAGS);
2576 vals->push_back(Expression::make_integer_ul(h, p->type(), bloc));
2578 ++p;
2579 go_assert(p->is_field_name("tflag"));
2580 unsigned long tflag = 0;
2581 if (this->compare_is_identity(gogo))
2582 tflag |= TFLAG_REGULAR_MEMORY;
2583 vals->push_back(Expression::make_integer_ul(tflag, p->type(), bloc));
2585 ++p;
2586 go_assert(p->is_field_name("align"));
2587 type_info = Expression::TYPE_INFO_ALIGNMENT;
2588 vals->push_back(Expression::make_type_info(this, type_info));
2590 ++p;
2591 go_assert(p->is_field_name("fieldAlign"));
2592 type_info = Expression::TYPE_INFO_FIELD_ALIGNMENT;
2593 vals->push_back(Expression::make_type_info(this, type_info));
2595 ++p;
2596 go_assert(p->is_field_name("kind"));
2597 vals->push_back(Expression::make_integer_ul(runtime_type_kind, p->type(),
2598 bloc));
2600 ++p;
2601 go_assert(p->is_field_name("equal"));
2602 Function_type* equal_fntype = p->type()->function_type();
2603 Named_object* equal_fn = this->equal_function(gogo, name, equal_fntype);
2604 if (equal_fn == NULL)
2605 vals->push_back(Expression::make_cast(equal_fntype,
2606 Expression::make_nil(bloc),
2607 bloc));
2608 else
2609 vals->push_back(Expression::make_func_reference(equal_fn, NULL, bloc));
2611 ++p;
2612 go_assert(p->is_field_name("gcdata"));
2613 if (has_pointer)
2614 vals->push_back(Expression::make_gc_symbol(this));
2615 else
2616 vals->push_back(Expression::make_cast(p->type(),
2617 Expression::make_nil(bloc),
2618 bloc));
2620 ++p;
2621 go_assert(p->is_field_name("string"));
2622 Expression* s = Expression::make_string((name != NULL
2623 ? name->reflection(gogo)
2624 : this->reflection(gogo)),
2625 bloc);
2626 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
2628 ++p;
2629 go_assert(p->is_field_name("uncommonType"));
2630 if (name == NULL && methods == NULL)
2631 vals->push_back(Expression::make_nil(bloc));
2632 else
2634 if (methods == NULL)
2635 methods = name->methods();
2636 vals->push_back(this->uncommon_type_constructor(gogo,
2637 p->type()->deref(),
2638 name, methods,
2639 only_value_methods));
2642 ++p;
2643 go_assert(p->is_field_name("ptrToThis"));
2644 if (name == NULL && methods == NULL)
2645 vals->push_back(Expression::make_nil(bloc));
2646 else
2648 Type* pt;
2649 if (name != NULL)
2650 pt = Type::make_pointer_type(name);
2651 else
2652 pt = Type::make_pointer_type(this);
2653 vals->push_back(Expression::make_type_descriptor(pt, bloc));
2656 ++p;
2657 go_assert(p == fields->end());
2659 return Expression::make_struct_composite_literal(td_type, vals, bloc);
2662 // The maximum length of a GC ptrmask bitmap. This corresponds to the
2663 // length used by the gc toolchain, and also appears in
2664 // libgo/go/reflect/type.go.
2666 static const int64_t max_ptrmask_bytes = 2048;
2668 // Return a pointer to the Garbage Collection information for this type.
2670 Bexpression*
2671 Type::gc_symbol_pointer(Gogo* gogo)
2673 Type* t = this->unalias();
2675 if (!t->has_pointer())
2676 return gogo->backend()->nil_pointer_expression();
2678 if (t->gc_symbol_var_ == NULL)
2680 t->make_gc_symbol_var(gogo);
2681 go_assert(t->gc_symbol_var_ != NULL);
2683 Location bloc = Linemap::predeclared_location();
2684 Bexpression* var_expr =
2685 gogo->backend()->var_expression(t->gc_symbol_var_, bloc);
2686 Bexpression* addr_expr =
2687 gogo->backend()->address_expression(var_expr, bloc);
2689 Type* uint8_type = Type::lookup_integer_type("uint8");
2690 Type* pointer_uint8_type = Type::make_pointer_type(uint8_type);
2691 Btype* ubtype = pointer_uint8_type->get_backend(gogo);
2692 return gogo->backend()->convert_expression(ubtype, addr_expr, bloc);
2695 // A mapping from unnamed types to GC symbol variables.
2697 Type::GC_symbol_vars Type::gc_symbol_vars;
2699 // Build the GC symbol for this type.
2701 void
2702 Type::make_gc_symbol_var(Gogo* gogo)
2704 go_assert(this->gc_symbol_var_ == NULL);
2706 Named_type* nt = this->named_type();
2708 // We can have multiple instances of unnamed types and similar to type
2709 // descriptors, we only want to the emit the GC data once, so we use a
2710 // hash table.
2711 Bvariable** phash = NULL;
2712 if (nt == NULL)
2714 Bvariable* bvnull = NULL;
2715 std::pair<GC_symbol_vars::iterator, bool> ins =
2716 Type::gc_symbol_vars.insert(std::make_pair(this, bvnull));
2717 if (!ins.second)
2719 // We've already built a gc symbol for this type.
2720 this->gc_symbol_var_ = ins.first->second;
2721 return;
2723 phash = &ins.first->second;
2726 int64_t ptrsize;
2727 int64_t ptrdata;
2728 if (!this->needs_gcprog(gogo, &ptrsize, &ptrdata))
2730 this->gc_symbol_var_ = this->gc_ptrmask_var(gogo, ptrsize, ptrdata);
2731 if (phash != NULL)
2732 *phash = this->gc_symbol_var_;
2733 return;
2736 std::string sym_name = gogo->gc_symbol_name(this);
2738 // Build the contents of the gc symbol.
2739 Expression* sym_init = this->gcprog_constructor(gogo, ptrsize, ptrdata);
2740 Btype* sym_btype = sym_init->type()->get_backend(gogo);
2742 // If the type descriptor for this type is defined somewhere else, so is the
2743 // GC symbol.
2744 const Package* dummy;
2745 if (this->type_descriptor_defined_elsewhere(nt, &dummy))
2747 this->gc_symbol_var_ =
2748 gogo->backend()->implicit_variable_reference(sym_name, "",
2749 sym_btype);
2750 if (phash != NULL)
2751 *phash = this->gc_symbol_var_;
2752 return;
2755 // See if this gc symbol can appear in multiple packages.
2756 bool is_common = false;
2757 if (nt != NULL)
2759 // We create the symbol for a builtin type whenever we need
2760 // it.
2761 is_common = nt->is_builtin();
2763 else
2765 // This is an unnamed type. The descriptor could be defined in
2766 // any package where it is needed, and the linker will pick one
2767 // descriptor to keep.
2768 is_common = true;
2771 // Since we are building the GC symbol in this package, we must create the
2772 // variable before converting the initializer to its backend representation
2773 // because the initializer may refer to the GC symbol for this type.
2774 unsigned int flags = Backend::variable_is_constant;
2775 if (is_common)
2776 flags |= Backend::variable_is_common;
2777 else
2778 flags |= Backend::variable_is_hidden;
2779 this->gc_symbol_var_ =
2780 gogo->backend()->implicit_variable(sym_name, "", sym_btype, flags, 0);
2781 if (phash != NULL)
2782 *phash = this->gc_symbol_var_;
2784 Translate_context context(gogo, NULL, NULL, NULL);
2785 context.set_is_const();
2786 Bexpression* sym_binit = sym_init->get_backend(&context);
2787 gogo->backend()->implicit_variable_set_init(this->gc_symbol_var_, sym_name,
2788 sym_btype, flags, sym_binit);
2791 // Return whether this type needs a GC program, and set *PTRDATA to
2792 // the size of the pointer data in bytes and *PTRSIZE to the size of a
2793 // pointer.
2795 bool
2796 Type::needs_gcprog(Gogo* gogo, int64_t* ptrsize, int64_t* ptrdata)
2798 Type* voidptr = Type::make_pointer_type(Type::make_void_type());
2799 if (!voidptr->backend_type_size(gogo, ptrsize))
2800 go_unreachable();
2802 if (!this->backend_type_ptrdata(gogo, ptrdata))
2804 go_assert(saw_errors());
2805 return false;
2808 return *ptrdata / *ptrsize > max_ptrmask_bytes;
2811 // A simple class used to build a GC ptrmask for a type.
2813 class Ptrmask
2815 public:
2816 Ptrmask(size_t count)
2817 : bits_((count + 7) / 8, 0)
2820 void
2821 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
2823 std::string
2824 symname() const;
2826 Expression*
2827 constructor() const;
2829 private:
2830 void
2831 set(size_t index)
2832 { this->bits_.at(index / 8) |= 1 << (index % 8); }
2834 // The actual bits.
2835 std::vector<unsigned char> bits_;
2838 // Set bits in ptrmask starting from OFFSET based on TYPE. OFFSET
2839 // counts in bytes. PTRSIZE is the size of a pointer on the target
2840 // system.
2842 void
2843 Ptrmask::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
2845 if (!type->has_pointer())
2846 return;
2848 switch (type->base()->classification())
2850 default:
2851 case Type::TYPE_NIL:
2852 case Type::TYPE_CALL_MULTIPLE_RESULT:
2853 case Type::TYPE_NAMED:
2854 case Type::TYPE_FORWARD:
2855 go_unreachable();
2857 case Type::TYPE_ERROR:
2858 case Type::TYPE_VOID:
2859 case Type::TYPE_BOOLEAN:
2860 case Type::TYPE_INTEGER:
2861 case Type::TYPE_FLOAT:
2862 case Type::TYPE_COMPLEX:
2863 case Type::TYPE_SINK:
2864 break;
2866 case Type::TYPE_FUNCTION:
2867 case Type::TYPE_POINTER:
2868 case Type::TYPE_MAP:
2869 case Type::TYPE_CHANNEL:
2870 // These types are all a single pointer.
2871 go_assert((offset % ptrsize) == 0);
2872 this->set(offset / ptrsize);
2873 break;
2875 case Type::TYPE_STRING:
2876 // A string starts with a single pointer.
2877 go_assert((offset % ptrsize) == 0);
2878 this->set(offset / ptrsize);
2879 break;
2881 case Type::TYPE_INTERFACE:
2882 // An interface is two pointers.
2883 go_assert((offset % ptrsize) == 0);
2884 this->set(offset / ptrsize);
2885 this->set((offset / ptrsize) + 1);
2886 break;
2888 case Type::TYPE_STRUCT:
2890 const Struct_field_list* fields = type->struct_type()->fields();
2891 int64_t soffset = 0;
2892 for (Struct_field_list::const_iterator pf = fields->begin();
2893 pf != fields->end();
2894 ++pf)
2896 int64_t field_align;
2897 if (!pf->type()->backend_type_field_align(gogo, &field_align))
2899 go_assert(saw_errors());
2900 return;
2902 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
2904 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
2906 int64_t field_size;
2907 if (!pf->type()->backend_type_size(gogo, &field_size))
2909 go_assert(saw_errors());
2910 return;
2912 soffset += field_size;
2915 break;
2917 case Type::TYPE_ARRAY:
2918 if (type->is_slice_type())
2920 // A slice starts with a single pointer.
2921 go_assert((offset % ptrsize) == 0);
2922 this->set(offset / ptrsize);
2923 break;
2925 else
2927 int64_t len;
2928 if (!type->array_type()->int_length(&len))
2930 go_assert(saw_errors());
2931 return;
2934 Type* element_type = type->array_type()->element_type();
2935 int64_t ele_size;
2936 if (!element_type->backend_type_size(gogo, &ele_size))
2938 go_assert(saw_errors());
2939 return;
2942 int64_t eoffset = 0;
2943 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
2944 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
2945 break;
2950 // Return a symbol name for this ptrmask. This is used to coalesce
2951 // identical ptrmasks, which are common. The symbol name must use
2952 // only characters that are valid in symbols. It's nice if it's
2953 // short. For smaller ptrmasks, we convert it to a string that uses
2954 // only 32 characters. For longer pointer masks, apply the same
2955 // process to the SHA1 digest of the bits, so as to avoid
2956 // pathologically long symbol names (see related Go issues #32083 and
2957 // #11583 for more on this). To avoid collisions between the two
2958 // encoding schemes, use a prefix ("X") for the SHA form to
2959 // disambiguate.
2961 std::string
2962 Ptrmask::symname() const
2964 const std::vector<unsigned char>* bits(&this->bits_);
2965 std::vector<unsigned char> shabits;
2966 std::string prefix;
2968 if (this->bits_.size() > 128)
2970 // Produce a SHA1 digest of the data.
2971 Go_sha1_helper* sha1_helper = go_create_sha1_helper();
2972 sha1_helper->process_bytes(&this->bits_[0], this->bits_.size());
2973 std::string digest = sha1_helper->finish();
2974 delete sha1_helper;
2976 // Redirect the bits vector to the digest, and update the prefix.
2977 prefix = "X";
2978 for (std::string::const_iterator p = digest.begin();
2979 p != digest.end();
2980 ++p)
2982 unsigned char c = *p;
2983 shabits.push_back(c);
2985 bits = &shabits;
2988 const char chars[33] = "abcdefghijklmnopqrstuvwxyzABCDEF";
2989 go_assert(chars[32] == '\0');
2990 std::string ret(prefix);
2991 unsigned int b = 0;
2992 int remaining = 0;
2993 for (std::vector<unsigned char>::const_iterator p = bits->begin();
2994 p != bits->end();
2995 ++p)
2997 b |= *p << remaining;
2998 remaining += 8;
2999 while (remaining >= 5)
3001 ret += chars[b & 0x1f];
3002 b >>= 5;
3003 remaining -= 5;
3006 while (remaining > 0)
3008 ret += chars[b & 0x1f];
3009 b >>= 5;
3010 remaining -= 5;
3012 return ret;
3015 // Return a constructor for this ptrmask. This will be used to
3016 // initialize the runtime ptrmask value.
3018 Expression*
3019 Ptrmask::constructor() const
3021 Location bloc = Linemap::predeclared_location();
3022 Type* byte_type = Type::lookup_integer_type("byte");
3023 Expression* len = Expression::make_integer_ul(this->bits_.size(), NULL,
3024 bloc);
3025 Array_type* at = Type::make_array_type(byte_type, len);
3026 Expression_list* vals = new Expression_list();
3027 vals->reserve(this->bits_.size());
3028 for (std::vector<unsigned char>::const_iterator p = this->bits_.begin();
3029 p != this->bits_.end();
3030 ++p)
3031 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3032 return Expression::make_array_composite_literal(at, vals, bloc);
3035 // The hash table mapping a ptrmask symbol name to the ptrmask variable.
3036 Type::GC_gcbits_vars Type::gc_gcbits_vars;
3038 // Return a ptrmask variable for a type. For a type descriptor this
3039 // is only used for variables that are small enough to not need a
3040 // gcprog, but for a global variable this is used for a variable of
3041 // any size. PTRDATA is the number of bytes of the type that contain
3042 // pointer data. PTRSIZE is the size of a pointer on the target
3043 // system.
3045 Bvariable*
3046 Type::gc_ptrmask_var(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3048 Ptrmask ptrmask(ptrdata / ptrsize);
3049 if (ptrdata >= ptrsize)
3050 ptrmask.set_from(gogo, this, ptrsize, 0);
3051 else
3053 // This can happen in error cases. Just build an empty gcbits.
3054 go_assert(saw_errors());
3057 std::string sym_name = gogo->ptrmask_symbol_name(ptrmask.symname());
3058 Bvariable* bvnull = NULL;
3059 std::pair<GC_gcbits_vars::iterator, bool> ins =
3060 Type::gc_gcbits_vars.insert(std::make_pair(sym_name, bvnull));
3061 if (!ins.second)
3063 // We've already built a GC symbol for this set of gcbits.
3064 return ins.first->second;
3067 Expression* val = ptrmask.constructor();
3068 Translate_context context(gogo, NULL, NULL, NULL);
3069 context.set_is_const();
3070 Bexpression* bval = val->get_backend(&context);
3072 Btype *btype = val->type()->get_backend(gogo);
3073 unsigned int flags = (Backend::variable_is_constant
3074 | Backend::variable_is_common);
3075 Bvariable* ret = gogo->backend()->implicit_variable(sym_name, "",
3076 btype, flags, 0);
3077 gogo->backend()->implicit_variable_set_init(ret, sym_name, btype, flags,
3078 bval);
3079 ins.first->second = ret;
3080 return ret;
3083 // A GCProg is used to build a program for the garbage collector.
3084 // This is used for types with a lot of pointer data, to reduce the
3085 // size of the data in the compiled program. The program is expanded
3086 // at runtime. For the format, see runGCProg in libgo/go/runtime/mbitmap.go.
3088 class GCProg
3090 public:
3091 GCProg()
3092 : bytes_(), index_(0), nb_(0)
3095 // The number of bits described so far.
3096 int64_t
3097 bit_index() const
3098 { return this->index_; }
3100 void
3101 set_from(Gogo*, Type*, int64_t ptrsize, int64_t offset);
3103 void
3104 end();
3106 Expression*
3107 constructor() const;
3109 private:
3110 void
3111 ptr(int64_t);
3113 bool
3114 should_repeat(int64_t, int64_t);
3116 void
3117 repeat(int64_t, int64_t);
3119 void
3120 zero_until(int64_t);
3122 void
3123 lit(unsigned char);
3125 void
3126 varint(int64_t);
3128 void
3129 flushlit();
3131 // Add a byte to the program.
3132 void
3133 byte(unsigned char x)
3134 { this->bytes_.push_back(x); }
3136 // The maximum number of bytes of literal bits.
3137 static const int max_literal = 127;
3139 // The program.
3140 std::vector<unsigned char> bytes_;
3141 // The index of the last bit described.
3142 int64_t index_;
3143 // The current set of literal bits.
3144 unsigned char b_[max_literal];
3145 // The current number of literal bits.
3146 int nb_;
3149 // Set data in gcprog starting from OFFSET based on TYPE. OFFSET
3150 // counts in bytes. PTRSIZE is the size of a pointer on the target
3151 // system.
3153 void
3154 GCProg::set_from(Gogo* gogo, Type* type, int64_t ptrsize, int64_t offset)
3156 switch (type->base()->classification())
3158 default:
3159 case Type::TYPE_NIL:
3160 case Type::TYPE_CALL_MULTIPLE_RESULT:
3161 case Type::TYPE_NAMED:
3162 case Type::TYPE_FORWARD:
3163 go_unreachable();
3165 case Type::TYPE_ERROR:
3166 case Type::TYPE_VOID:
3167 case Type::TYPE_BOOLEAN:
3168 case Type::TYPE_INTEGER:
3169 case Type::TYPE_FLOAT:
3170 case Type::TYPE_COMPLEX:
3171 case Type::TYPE_SINK:
3172 break;
3174 case Type::TYPE_FUNCTION:
3175 case Type::TYPE_POINTER:
3176 case Type::TYPE_MAP:
3177 case Type::TYPE_CHANNEL:
3178 // These types are all a single pointer.
3179 go_assert((offset % ptrsize) == 0);
3180 this->ptr(offset / ptrsize);
3181 break;
3183 case Type::TYPE_STRING:
3184 // A string starts with a single pointer.
3185 go_assert((offset % ptrsize) == 0);
3186 this->ptr(offset / ptrsize);
3187 break;
3189 case Type::TYPE_INTERFACE:
3190 // An interface is two pointers.
3191 go_assert((offset % ptrsize) == 0);
3192 this->ptr(offset / ptrsize);
3193 this->ptr((offset / ptrsize) + 1);
3194 break;
3196 case Type::TYPE_STRUCT:
3198 if (!type->has_pointer())
3199 return;
3201 const Struct_field_list* fields = type->struct_type()->fields();
3202 int64_t soffset = 0;
3203 for (Struct_field_list::const_iterator pf = fields->begin();
3204 pf != fields->end();
3205 ++pf)
3207 int64_t field_align;
3208 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3210 go_assert(saw_errors());
3211 return;
3213 soffset = (soffset + (field_align - 1)) &~ (field_align - 1);
3215 this->set_from(gogo, pf->type(), ptrsize, offset + soffset);
3217 int64_t field_size;
3218 if (!pf->type()->backend_type_size(gogo, &field_size))
3220 go_assert(saw_errors());
3221 return;
3223 soffset += field_size;
3226 break;
3228 case Type::TYPE_ARRAY:
3229 if (type->is_slice_type())
3231 // A slice starts with a single pointer.
3232 go_assert((offset % ptrsize) == 0);
3233 this->ptr(offset / ptrsize);
3234 break;
3236 else
3238 if (!type->has_pointer())
3239 return;
3241 int64_t len;
3242 if (!type->array_type()->int_length(&len))
3244 go_assert(saw_errors());
3245 return;
3248 Type* element_type = type->array_type()->element_type();
3250 // Flatten array of array to a big array by multiplying counts.
3251 while (element_type->array_type() != NULL
3252 && !element_type->is_slice_type())
3254 int64_t ele_len;
3255 if (!element_type->array_type()->int_length(&ele_len))
3257 go_assert(saw_errors());
3258 return;
3261 len *= ele_len;
3262 element_type = element_type->array_type()->element_type();
3265 int64_t ele_size;
3266 if (!element_type->backend_type_size(gogo, &ele_size))
3268 go_assert(saw_errors());
3269 return;
3272 go_assert(len > 0 && ele_size > 0);
3274 if (!this->should_repeat(ele_size / ptrsize, len))
3276 // Cheaper to just emit the bits.
3277 int64_t eoffset = 0;
3278 for (int64_t i = 0; i < len; i++, eoffset += ele_size)
3279 this->set_from(gogo, element_type, ptrsize, offset + eoffset);
3281 else
3283 go_assert((offset % ptrsize) == 0);
3284 go_assert((ele_size % ptrsize) == 0);
3285 this->set_from(gogo, element_type, ptrsize, offset);
3286 this->zero_until((offset + ele_size) / ptrsize);
3287 this->repeat(ele_size / ptrsize, len - 1);
3290 break;
3295 // Emit a 1 into the bit stream of a GC program at the given bit index.
3297 void
3298 GCProg::ptr(int64_t index)
3300 go_assert(index >= this->index_);
3301 this->zero_until(index);
3302 this->lit(1);
3305 // Return whether it is worthwhile to use a repeat to describe c
3306 // elements of n bits each, compared to just emitting c copies of the
3307 // n-bit description.
3309 bool
3310 GCProg::should_repeat(int64_t n, int64_t c)
3312 // Repeat if there is more than 1 item and if the total data doesn't
3313 // fit into four bytes.
3314 return c > 1 && c * n > 4 * 8;
3317 // Emit an instruction to repeat the description of the last n words c
3318 // times (including the initial description, so c + 1 times in total).
3320 void
3321 GCProg::repeat(int64_t n, int64_t c)
3323 if (n == 0 || c == 0)
3324 return;
3325 this->flushlit();
3326 if (n < 128)
3327 this->byte(0x80 | static_cast<unsigned char>(n & 0x7f));
3328 else
3330 this->byte(0x80);
3331 this->varint(n);
3333 this->varint(c);
3334 this->index_ += n * c;
3337 // Add zeros to the bit stream up to the given index.
3339 void
3340 GCProg::zero_until(int64_t index)
3342 go_assert(index >= this->index_);
3343 int64_t skip = index - this->index_;
3344 if (skip == 0)
3345 return;
3346 if (skip < 4 * 8)
3348 for (int64_t i = 0; i < skip; ++i)
3349 this->lit(0);
3350 return;
3352 this->lit(0);
3353 this->flushlit();
3354 this->repeat(1, skip - 1);
3357 // Add a single literal bit to the program.
3359 void
3360 GCProg::lit(unsigned char x)
3362 if (this->nb_ == GCProg::max_literal)
3363 this->flushlit();
3364 this->b_[this->nb_] = x;
3365 ++this->nb_;
3366 ++this->index_;
3369 // Emit the varint encoding of x.
3371 void
3372 GCProg::varint(int64_t x)
3374 go_assert(x >= 0);
3375 while (x >= 0x80)
3377 this->byte(0x80 | static_cast<unsigned char>(x & 0x7f));
3378 x >>= 7;
3380 this->byte(static_cast<unsigned char>(x & 0x7f));
3383 // Flush any pending literal bits.
3385 void
3386 GCProg::flushlit()
3388 if (this->nb_ == 0)
3389 return;
3390 this->byte(static_cast<unsigned char>(this->nb_));
3391 unsigned char bits = 0;
3392 for (int i = 0; i < this->nb_; ++i)
3394 bits |= this->b_[i] << (i % 8);
3395 if ((i + 1) % 8 == 0)
3397 this->byte(bits);
3398 bits = 0;
3401 if (this->nb_ % 8 != 0)
3402 this->byte(bits);
3403 this->nb_ = 0;
3406 // Mark the end of a GC program.
3408 void
3409 GCProg::end()
3411 this->flushlit();
3412 this->byte(0);
3415 // Return an Expression for the bytes in a GC program.
3417 Expression*
3418 GCProg::constructor() const
3420 Location bloc = Linemap::predeclared_location();
3422 // The first four bytes are the length of the program in target byte
3423 // order. Build a struct whose first type is uint32 to make this
3424 // work.
3426 Type* uint32_type = Type::lookup_integer_type("uint32");
3428 Type* byte_type = Type::lookup_integer_type("byte");
3429 Expression* len = Expression::make_integer_ul(this->bytes_.size(), NULL,
3430 bloc);
3431 Array_type* at = Type::make_array_type(byte_type, len);
3433 Struct_type* st = Type::make_builtin_struct_type(2, "len", uint32_type,
3434 "bytes", at);
3436 Expression_list* vals = new Expression_list();
3437 vals->reserve(this->bytes_.size());
3438 for (std::vector<unsigned char>::const_iterator p = this->bytes_.begin();
3439 p != this->bytes_.end();
3440 ++p)
3441 vals->push_back(Expression::make_integer_ul(*p, byte_type, bloc));
3442 Expression* bytes = Expression::make_array_composite_literal(at, vals, bloc);
3444 vals = new Expression_list();
3445 vals->push_back(Expression::make_integer_ul(this->bytes_.size(), uint32_type,
3446 bloc));
3447 vals->push_back(bytes);
3449 return Expression::make_struct_composite_literal(st, vals, bloc);
3452 // Return a composite literal for the garbage collection program for
3453 // this type. This is only used for types that are too large to use a
3454 // ptrmask.
3456 Expression*
3457 Type::gcprog_constructor(Gogo* gogo, int64_t ptrsize, int64_t ptrdata)
3459 Location bloc = Linemap::predeclared_location();
3461 GCProg prog;
3462 prog.set_from(gogo, this, ptrsize, 0);
3463 int64_t offset = prog.bit_index() * ptrsize;
3464 prog.end();
3466 int64_t type_size;
3467 if (!this->backend_type_size(gogo, &type_size))
3469 go_assert(saw_errors());
3470 return Expression::make_error(bloc);
3473 go_assert(offset >= ptrdata && offset <= type_size);
3475 return prog.constructor();
3478 // Return a composite literal for the uncommon type information for
3479 // this type. UNCOMMON_STRUCT_TYPE is the type of the uncommon type
3480 // struct. If name is not NULL, it is the name of the type. If
3481 // METHODS is not NULL, it is the list of methods. ONLY_VALUE_METHODS
3482 // is true if only value methods should be included. At least one of
3483 // NAME and METHODS must not be NULL.
3485 Expression*
3486 Type::uncommon_type_constructor(Gogo* gogo, Type* uncommon_type,
3487 Named_type* name, const Methods* methods,
3488 bool only_value_methods) const
3490 Location bloc = Linemap::predeclared_location();
3492 const Struct_field_list* fields = uncommon_type->struct_type()->fields();
3494 Expression_list* vals = new Expression_list();
3495 vals->reserve(3);
3497 Struct_field_list::const_iterator p = fields->begin();
3498 go_assert(p->is_field_name("name"));
3500 ++p;
3501 go_assert(p->is_field_name("pkgPath"));
3503 if (name == NULL)
3505 vals->push_back(Expression::make_nil(bloc));
3506 vals->push_back(Expression::make_nil(bloc));
3508 else
3510 Named_object* no = name->named_object();
3511 std::string n = Gogo::unpack_hidden_name(no->name());
3512 Expression* s = Expression::make_string(n, bloc);
3513 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3515 if (name->is_builtin())
3516 vals->push_back(Expression::make_nil(bloc));
3517 else
3519 const Package* package = no->package();
3520 const std::string& pkgpath(package == NULL
3521 ? gogo->pkgpath()
3522 : package->pkgpath());
3523 s = Expression::make_string(pkgpath, bloc);
3524 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3528 ++p;
3529 go_assert(p->is_field_name("methods"));
3530 vals->push_back(this->methods_constructor(gogo, p->type(), methods,
3531 only_value_methods));
3533 ++p;
3534 go_assert(p == fields->end());
3536 Expression* r = Expression::make_struct_composite_literal(uncommon_type,
3537 vals, bloc);
3538 return Expression::make_unary(OPERATOR_AND, r, bloc);
3541 // Sort methods by name.
3543 class Sort_methods
3545 public:
3546 bool
3547 operator()(const std::pair<std::string, const Method*>& m1,
3548 const std::pair<std::string, const Method*>& m2) const
3550 return (Gogo::unpack_hidden_name(m1.first)
3551 < Gogo::unpack_hidden_name(m2.first));
3555 // Return a composite literal for the type method table for this type.
3556 // METHODS_TYPE is the type of the table, and is a slice type.
3557 // METHODS is the list of methods. If ONLY_VALUE_METHODS is true,
3558 // then only value methods are used.
3560 Expression*
3561 Type::methods_constructor(Gogo* gogo, Type* methods_type,
3562 const Methods* methods,
3563 bool only_value_methods) const
3565 Location bloc = Linemap::predeclared_location();
3567 std::vector<std::pair<std::string, const Method*> > smethods;
3568 if (methods != NULL)
3570 smethods.reserve(methods->count());
3571 for (Methods::const_iterator p = methods->begin();
3572 p != methods->end();
3573 ++p)
3575 if (p->second->is_ambiguous())
3576 continue;
3577 if (only_value_methods && !p->second->is_value_method())
3578 continue;
3580 // This is where we implement the magic //go:nointerface
3581 // comment. If we saw that comment, we don't add this
3582 // method to the type descriptor.
3583 if (p->second->nointerface())
3584 continue;
3586 smethods.push_back(std::make_pair(p->first, p->second));
3590 if (smethods.empty())
3591 return Expression::make_slice_composite_literal(methods_type, NULL, bloc);
3593 std::sort(smethods.begin(), smethods.end(), Sort_methods());
3595 Type* method_type = methods_type->array_type()->element_type();
3597 Expression_list* vals = new Expression_list();
3598 vals->reserve(smethods.size());
3599 for (std::vector<std::pair<std::string, const Method*> >::const_iterator p
3600 = smethods.begin();
3601 p != smethods.end();
3602 ++p)
3603 vals->push_back(this->method_constructor(gogo, method_type, p->first,
3604 p->second, only_value_methods));
3606 return Expression::make_slice_composite_literal(methods_type, vals, bloc);
3609 // Return a composite literal for a single method. METHOD_TYPE is the
3610 // type of the entry. METHOD_NAME is the name of the method and M is
3611 // the method information.
3613 Expression*
3614 Type::method_constructor(Gogo*, Type* method_type,
3615 const std::string& method_name,
3616 const Method* m,
3617 bool only_value_methods) const
3619 Location bloc = Linemap::predeclared_location();
3621 const Struct_field_list* fields = method_type->struct_type()->fields();
3623 Expression_list* vals = new Expression_list();
3624 vals->reserve(5);
3626 Struct_field_list::const_iterator p = fields->begin();
3627 go_assert(p->is_field_name("name"));
3628 const std::string n = Gogo::unpack_hidden_name(method_name);
3629 Expression* s = Expression::make_string(n, bloc);
3630 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3632 ++p;
3633 go_assert(p->is_field_name("pkgPath"));
3634 if (!Gogo::is_hidden_name(method_name))
3635 vals->push_back(Expression::make_nil(bloc));
3636 else
3638 s = Expression::make_string(Gogo::hidden_name_pkgpath(method_name),
3639 bloc);
3640 vals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
3643 // The direct_iface_stub dereferences the value stored in the
3644 // interface when calling the method.
3646 // We need this for a value method if this type is a pointer to a
3647 // direct-iface type. For example, if we have "type C chan int" and M
3648 // is a value method on C, then since a channel is a direct-iface type
3649 // M expects a value of type C. We are generating the method table
3650 // for *C, so the value stored in the interface is *C. We have to
3651 // call the direct-iface stub to dereference *C to get C to pass to M.
3653 // We also need this for a pointer method if the pointer itself is not
3654 // a direct-iface type, as arises for notinheap types. In this case
3655 // we have "type NIH ..." where NIH is go:notinheap. Since NIH is
3656 // notinheap, *NIH is a pointer type that is not a direct-iface type,
3657 // so the value stored in the interface is actually **NIH. The method
3658 // expects *NIH, so we have to call the direct-iface stub to
3659 // dereference **NIH to get *NIH to pass to M. (This case doesn't
3660 // arise for value methods because pointer types can't have methods,
3661 // so there is no such thing as a value method for type *NIH.)
3663 bool use_direct_iface_stub = false;
3664 if (m->is_value_method()
3665 && this->points_to() != NULL
3666 && this->points_to()->is_direct_iface_type())
3667 use_direct_iface_stub = true;
3668 if (!m->is_value_method()
3669 && this->points_to() != NULL
3670 && !this->is_direct_iface_type())
3671 use_direct_iface_stub = true;
3673 Named_object* no = (use_direct_iface_stub
3674 ? m->iface_stub_object()
3675 : (m->needs_stub_method()
3676 ? m->stub_object()
3677 : m->named_object()));
3679 Function_type* mtype;
3680 if (no->is_function())
3681 mtype = no->func_value()->type();
3682 else
3683 mtype = no->func_declaration_value()->type();
3684 go_assert(mtype->is_method());
3685 Type* nonmethod_type = mtype->copy_without_receiver();
3687 ++p;
3688 go_assert(p->is_field_name("mtyp"));
3689 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3691 ++p;
3692 go_assert(p->is_field_name("typ"));
3693 bool want_pointer_receiver = (!only_value_methods && m->is_value_method()
3694 && !use_direct_iface_stub);
3695 nonmethod_type = mtype->copy_with_receiver_as_param(want_pointer_receiver);
3696 vals->push_back(Expression::make_type_descriptor(nonmethod_type, bloc));
3698 ++p;
3699 go_assert(p->is_field_name("tfn"));
3700 vals->push_back(Expression::make_func_code_reference(no, bloc));
3702 ++p;
3703 go_assert(p == fields->end());
3705 return Expression::make_struct_composite_literal(method_type, vals, bloc);
3708 // Return a composite literal for the type descriptor of a plain type.
3709 // RUNTIME_TYPE_KIND is the value of the kind field. If NAME is not
3710 // NULL, it is the name to use as well as the list of methods.
3712 Expression*
3713 Type::plain_type_descriptor(Gogo* gogo, int runtime_type_kind,
3714 Named_type* name)
3716 return this->type_descriptor_constructor(gogo, runtime_type_kind,
3717 name, NULL, true);
3720 // Return the type reflection string for this type.
3722 std::string
3723 Type::reflection(Gogo* gogo) const
3725 std::string ret;
3727 // The do_reflection virtual function should set RET to the
3728 // reflection string.
3729 this->do_reflection(gogo, &ret);
3731 return ret;
3734 // Return whether the backend size of the type is known.
3736 bool
3737 Type::is_backend_type_size_known(Gogo* gogo)
3739 switch (this->classification_)
3741 case TYPE_ERROR:
3742 case TYPE_VOID:
3743 case TYPE_BOOLEAN:
3744 case TYPE_INTEGER:
3745 case TYPE_FLOAT:
3746 case TYPE_COMPLEX:
3747 case TYPE_STRING:
3748 case TYPE_FUNCTION:
3749 case TYPE_POINTER:
3750 case TYPE_NIL:
3751 case TYPE_MAP:
3752 case TYPE_CHANNEL:
3753 case TYPE_INTERFACE:
3754 return true;
3756 case TYPE_STRUCT:
3758 const Struct_field_list* fields = this->struct_type()->fields();
3759 for (Struct_field_list::const_iterator pf = fields->begin();
3760 pf != fields->end();
3761 ++pf)
3762 if (!pf->type()->is_backend_type_size_known(gogo))
3763 return false;
3764 return true;
3767 case TYPE_ARRAY:
3769 const Array_type* at = this->array_type();
3770 if (at->length() == NULL)
3771 return true;
3772 else
3774 Numeric_constant nc;
3775 if (!at->length()->numeric_constant_value(&nc))
3776 return false;
3777 mpz_t ival;
3778 if (!nc.to_int(&ival))
3779 return false;
3780 mpz_clear(ival);
3781 return at->element_type()->is_backend_type_size_known(gogo);
3785 case TYPE_NAMED:
3786 this->named_type()->convert(gogo);
3787 return this->named_type()->is_named_backend_type_size_known();
3789 case TYPE_FORWARD:
3791 Forward_declaration_type* fdt = this->forward_declaration_type();
3792 return fdt->real_type()->is_backend_type_size_known(gogo);
3795 case TYPE_SINK:
3796 case TYPE_CALL_MULTIPLE_RESULT:
3797 go_unreachable();
3799 default:
3800 go_unreachable();
3804 // If the size of the type can be determined, set *PSIZE to the size
3805 // in bytes and return true. Otherwise, return false. This queries
3806 // the backend.
3808 bool
3809 Type::backend_type_size(Gogo* gogo, int64_t *psize)
3811 if (!this->is_backend_type_size_known(gogo))
3812 return false;
3813 if (this->is_error_type())
3814 return false;
3815 Btype* bt = this->get_backend_placeholder(gogo);
3816 *psize = gogo->backend()->type_size(bt);
3817 if (*psize == -1)
3819 if (this->named_type() != NULL)
3820 go_error_at(this->named_type()->location(),
3821 "type %s larger than address space",
3822 Gogo::message_name(this->named_type()->name()).c_str());
3823 else
3824 go_error_at(Linemap::unknown_location(),
3825 "type %s larger than address space",
3826 this->reflection(gogo).c_str());
3828 // Make this an error type to avoid knock-on errors.
3829 this->classification_ = TYPE_ERROR;
3830 return false;
3832 return true;
3835 // If the alignment of the type can be determined, set *PALIGN to
3836 // the alignment in bytes and return true. Otherwise, return false.
3838 bool
3839 Type::backend_type_align(Gogo* gogo, int64_t *palign)
3841 if (!this->is_backend_type_size_known(gogo))
3842 return false;
3843 Btype* bt = this->get_backend_placeholder(gogo);
3844 *palign = gogo->backend()->type_alignment(bt);
3845 return true;
3848 // Like backend_type_align, but return the alignment when used as a
3849 // field.
3851 bool
3852 Type::backend_type_field_align(Gogo* gogo, int64_t *palign)
3854 if (!this->is_backend_type_size_known(gogo))
3855 return false;
3856 Btype* bt = this->get_backend_placeholder(gogo);
3857 *palign = gogo->backend()->type_field_alignment(bt);
3858 return true;
3861 // Get the ptrdata value for a type. This is the size of the prefix
3862 // of the type that contains all pointers. Store the ptrdata in
3863 // *PPTRDATA and return whether we found it.
3865 bool
3866 Type::backend_type_ptrdata(Gogo* gogo, int64_t* pptrdata)
3868 *pptrdata = 0;
3870 if (!this->has_pointer())
3871 return true;
3873 if (!this->is_backend_type_size_known(gogo))
3874 return false;
3876 switch (this->classification_)
3878 case TYPE_ERROR:
3879 return true;
3881 case TYPE_FUNCTION:
3882 case TYPE_POINTER:
3883 case TYPE_MAP:
3884 case TYPE_CHANNEL:
3885 // These types are nothing but a pointer.
3886 return this->backend_type_size(gogo, pptrdata);
3888 case TYPE_INTERFACE:
3889 // An interface is a struct of two pointers.
3890 return this->backend_type_size(gogo, pptrdata);
3892 case TYPE_STRING:
3894 // A string is a struct whose first field is a pointer, and
3895 // whose second field is not.
3896 Type* uint8_type = Type::lookup_integer_type("uint8");
3897 Type* ptr = Type::make_pointer_type(uint8_type);
3898 return ptr->backend_type_size(gogo, pptrdata);
3901 case TYPE_NAMED:
3902 case TYPE_FORWARD:
3903 return this->base()->backend_type_ptrdata(gogo, pptrdata);
3905 case TYPE_STRUCT:
3907 const Struct_field_list* fields = this->struct_type()->fields();
3908 int64_t offset = 0;
3909 const Struct_field *ptr = NULL;
3910 int64_t ptr_offset = 0;
3911 for (Struct_field_list::const_iterator pf = fields->begin();
3912 pf != fields->end();
3913 ++pf)
3915 int64_t field_align;
3916 if (!pf->type()->backend_type_field_align(gogo, &field_align))
3917 return false;
3918 offset = (offset + (field_align - 1)) &~ (field_align - 1);
3920 if (pf->type()->has_pointer())
3922 ptr = &*pf;
3923 ptr_offset = offset;
3926 int64_t field_size;
3927 if (!pf->type()->backend_type_size(gogo, &field_size))
3928 return false;
3929 offset += field_size;
3932 if (ptr != NULL)
3934 int64_t ptr_ptrdata;
3935 if (!ptr->type()->backend_type_ptrdata(gogo, &ptr_ptrdata))
3936 return false;
3937 *pptrdata = ptr_offset + ptr_ptrdata;
3939 return true;
3942 case TYPE_ARRAY:
3943 if (this->is_slice_type())
3945 // A slice is a struct whose first field is a pointer, and
3946 // whose remaining fields are not.
3947 Type* element_type = this->array_type()->element_type();
3948 Type* ptr = Type::make_pointer_type(element_type);
3949 return ptr->backend_type_size(gogo, pptrdata);
3951 else
3953 Numeric_constant nc;
3954 if (!this->array_type()->length()->numeric_constant_value(&nc))
3955 return false;
3956 int64_t len;
3957 if (!nc.to_memory_size(&len))
3958 return false;
3960 Type* element_type = this->array_type()->element_type();
3961 int64_t ele_size;
3962 int64_t ele_ptrdata;
3963 if (!element_type->backend_type_size(gogo, &ele_size)
3964 || !element_type->backend_type_ptrdata(gogo, &ele_ptrdata))
3965 return false;
3966 go_assert(ele_size > 0 && ele_ptrdata > 0);
3968 *pptrdata = (len - 1) * ele_size + ele_ptrdata;
3969 return true;
3972 default:
3973 case TYPE_VOID:
3974 case TYPE_BOOLEAN:
3975 case TYPE_INTEGER:
3976 case TYPE_FLOAT:
3977 case TYPE_COMPLEX:
3978 case TYPE_SINK:
3979 case TYPE_NIL:
3980 case TYPE_CALL_MULTIPLE_RESULT:
3981 go_unreachable();
3985 // Get the ptrdata value to store in a type descriptor. This is
3986 // normally the same as backend_type_ptrdata, but for a type that is
3987 // large enough to use a gcprog we may need to store a different value
3988 // if it ends with an array. If the gcprog uses a repeat descriptor
3989 // for the array, and if the array element ends with non-pointer data,
3990 // then the gcprog will produce a value that describes the complete
3991 // array where the backend ptrdata will omit the non-pointer elements
3992 // of the final array element. This is a subtle difference but the
3993 // run time code checks it to verify that it has expanded a gcprog as
3994 // expected.
3996 bool
3997 Type::descriptor_ptrdata(Gogo* gogo, int64_t* pptrdata)
3999 int64_t backend_ptrdata;
4000 if (!this->backend_type_ptrdata(gogo, &backend_ptrdata))
4001 return false;
4003 int64_t ptrsize;
4004 if (!this->needs_gcprog(gogo, &ptrsize, &backend_ptrdata))
4006 *pptrdata = backend_ptrdata;
4007 return true;
4010 GCProg prog;
4011 prog.set_from(gogo, this, ptrsize, 0);
4012 int64_t offset = prog.bit_index() * ptrsize;
4014 go_assert(offset >= backend_ptrdata);
4015 *pptrdata = offset;
4016 return true;
4019 // Default function to export a type.
4021 void
4022 Type::do_export(Export*) const
4024 go_unreachable();
4027 // Import a type.
4029 Type*
4030 Type::import_type(Import* imp)
4032 if (imp->match_c_string("("))
4033 return Function_type::do_import(imp);
4034 else if (imp->match_c_string("*"))
4035 return Pointer_type::do_import(imp);
4036 else if (imp->match_c_string("struct "))
4037 return Struct_type::do_import(imp);
4038 else if (imp->match_c_string("["))
4039 return Array_type::do_import(imp);
4040 else if (imp->match_c_string("map "))
4041 return Map_type::do_import(imp);
4042 else if (imp->match_c_string("chan "))
4043 return Channel_type::do_import(imp);
4044 else if (imp->match_c_string("interface"))
4045 return Interface_type::do_import(imp);
4046 else
4048 go_error_at(imp->location(), "import error: expected type");
4049 return Type::make_error_type();
4053 // Class Error_type.
4055 // Return the backend representation of an Error type.
4057 Btype*
4058 Error_type::do_get_backend(Gogo* gogo)
4060 return gogo->backend()->error_type();
4063 // Return an expression for the type descriptor for an error type.
4066 Expression*
4067 Error_type::do_type_descriptor(Gogo*, Named_type*)
4069 return Expression::make_error(Linemap::predeclared_location());
4072 // We should not be asked for the reflection string for an error type.
4074 void
4075 Error_type::do_reflection(Gogo*, std::string*) const
4077 go_assert(saw_errors());
4080 Type*
4081 Type::make_error_type()
4083 static Error_type singleton_error_type;
4084 return &singleton_error_type;
4087 // Class Void_type.
4089 // Get the backend representation of a void type.
4091 Btype*
4092 Void_type::do_get_backend(Gogo* gogo)
4094 return gogo->backend()->void_type();
4097 Type*
4098 Type::make_void_type()
4100 static Void_type singleton_void_type;
4101 return &singleton_void_type;
4104 // Class Boolean_type.
4106 // Return the backend representation of the boolean type.
4108 Btype*
4109 Boolean_type::do_get_backend(Gogo* gogo)
4111 return gogo->backend()->bool_type();
4114 // Make the type descriptor.
4116 Expression*
4117 Boolean_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4119 if (name != NULL)
4120 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_BOOL, name);
4121 else
4123 Named_object* no = gogo->lookup_global("bool");
4124 go_assert(no != NULL);
4125 return Type::type_descriptor(gogo, no->type_value());
4129 Type*
4130 Type::make_boolean_type()
4132 static Boolean_type boolean_type;
4133 return &boolean_type;
4136 // The named type "bool".
4138 static Named_type* named_bool_type;
4140 // Get the named type "bool".
4142 Named_type*
4143 Type::lookup_bool_type()
4145 return named_bool_type;
4148 // Make the named type "bool".
4150 Named_type*
4151 Type::make_named_bool_type()
4153 Type* bool_type = Type::make_boolean_type();
4154 Named_object* named_object =
4155 Named_object::make_type("bool", NULL, bool_type,
4156 Linemap::predeclared_location());
4157 Named_type* named_type = named_object->type_value();
4158 named_bool_type = named_type;
4159 return named_type;
4162 // Class Integer_type.
4164 Integer_type::Named_integer_types Integer_type::named_integer_types;
4166 // Create a new integer type. Non-abstract integer types always have
4167 // names.
4169 Named_type*
4170 Integer_type::create_integer_type(const char* name, bool is_unsigned,
4171 int bits, int runtime_type_kind)
4173 Integer_type* integer_type = new Integer_type(false, is_unsigned, bits,
4174 runtime_type_kind);
4175 std::string sname(name);
4176 Named_object* named_object =
4177 Named_object::make_type(sname, NULL, integer_type,
4178 Linemap::predeclared_location());
4179 Named_type* named_type = named_object->type_value();
4180 std::pair<Named_integer_types::iterator, bool> ins =
4181 Integer_type::named_integer_types.insert(std::make_pair(sname, named_type));
4182 go_assert(ins.second);
4183 return named_type;
4186 // Look up an existing integer type.
4188 Named_type*
4189 Integer_type::lookup_integer_type(const char* name)
4191 Named_integer_types::const_iterator p =
4192 Integer_type::named_integer_types.find(name);
4193 go_assert(p != Integer_type::named_integer_types.end());
4194 return p->second;
4197 // Create a new abstract integer type.
4199 Integer_type*
4200 Integer_type::create_abstract_integer_type()
4202 static Integer_type* abstract_type;
4203 if (abstract_type == NULL)
4205 Type* int_type = Type::lookup_integer_type("int");
4206 abstract_type = new Integer_type(true, false,
4207 int_type->integer_type()->bits(),
4208 RUNTIME_TYPE_KIND_INT);
4210 return abstract_type;
4213 // Create a new abstract character type.
4215 Integer_type*
4216 Integer_type::create_abstract_character_type()
4218 static Integer_type* abstract_type;
4219 if (abstract_type == NULL)
4221 abstract_type = new Integer_type(true, false, 32,
4222 RUNTIME_TYPE_KIND_INT32);
4223 abstract_type->set_is_rune();
4225 return abstract_type;
4228 // Create an alias to an integer type. This is used for byte and rune.
4230 Named_type*
4231 Integer_type::create_integer_type_alias(const char* name,
4232 Named_type* real_type)
4234 std::string sname(name);
4235 Named_object* no = Named_object::make_type(sname, NULL, real_type,
4236 Linemap::predeclared_location());
4237 Named_type* nt = no->type_value();
4238 nt->set_is_alias();
4239 std::pair<Named_integer_types::iterator, bool> ins =
4240 Integer_type::named_integer_types.insert(std::make_pair(sname, nt));
4241 go_assert(ins.second);
4242 return nt;
4245 // Integer type compatibility.
4247 bool
4248 Integer_type::is_identical(const Integer_type* t) const
4250 if (this->is_unsigned_ != t->is_unsigned_ || this->bits_ != t->bits_)
4251 return false;
4252 return this->is_abstract_ == t->is_abstract_;
4255 // Message name.
4257 void
4258 Integer_type::do_message_name(std::string* ret) const
4260 ret->append("<untyped ");
4261 if (this->is_byte_)
4262 ret->append("byte");
4263 else if (this->is_rune_)
4264 ret->append("rune");
4265 else
4267 if (this->is_unsigned_)
4268 ret->push_back('u');
4269 if (this->is_abstract_)
4270 ret->append("int");
4271 else
4273 ret->append("int");
4274 char buf[10];
4275 snprintf(buf, sizeof buf, "%d", this->bits_);
4276 ret->append(buf);
4279 ret->push_back('>');
4282 // Hash code.
4284 unsigned int
4285 Integer_type::do_hash_for_method(Gogo*, int) const
4287 return ((this->bits_ << 4)
4288 + ((this->is_unsigned_ ? 1 : 0) << 8)
4289 + ((this->is_abstract_ ? 1 : 0) << 9));
4292 // Convert an Integer_type to the backend representation.
4294 Btype*
4295 Integer_type::do_get_backend(Gogo* gogo)
4297 if (this->is_abstract_)
4299 go_assert(saw_errors());
4300 return gogo->backend()->error_type();
4302 return gogo->backend()->integer_type(this->is_unsigned_, this->bits_);
4305 // The type descriptor for an integer type. Integer types are always
4306 // named.
4308 Expression*
4309 Integer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4311 go_assert(name != NULL || saw_errors());
4312 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4315 // We should not be asked for the reflection string of a basic type.
4317 void
4318 Integer_type::do_reflection(Gogo*, std::string*) const
4320 go_assert(saw_errors());
4323 // Make an integer type.
4325 Named_type*
4326 Type::make_integer_type(const char* name, bool is_unsigned, int bits,
4327 int runtime_type_kind)
4329 return Integer_type::create_integer_type(name, is_unsigned, bits,
4330 runtime_type_kind);
4333 // Make an abstract integer type.
4335 Integer_type*
4336 Type::make_abstract_integer_type()
4338 return Integer_type::create_abstract_integer_type();
4341 // Make an abstract character type.
4343 Integer_type*
4344 Type::make_abstract_character_type()
4346 return Integer_type::create_abstract_character_type();
4349 // Make an integer type alias.
4351 Named_type*
4352 Type::make_integer_type_alias(const char* name, Named_type* real_type)
4354 return Integer_type::create_integer_type_alias(name, real_type);
4357 // Look up an integer type.
4359 Named_type*
4360 Type::lookup_integer_type(const char* name)
4362 return Integer_type::lookup_integer_type(name);
4365 // Class Float_type.
4367 Float_type::Named_float_types Float_type::named_float_types;
4369 // Create a new float type. Non-abstract float types always have
4370 // names.
4372 Named_type*
4373 Float_type::create_float_type(const char* name, int bits,
4374 int runtime_type_kind)
4376 Float_type* float_type = new Float_type(false, bits, runtime_type_kind);
4377 std::string sname(name);
4378 Named_object* named_object =
4379 Named_object::make_type(sname, NULL, float_type,
4380 Linemap::predeclared_location());
4381 Named_type* named_type = named_object->type_value();
4382 std::pair<Named_float_types::iterator, bool> ins =
4383 Float_type::named_float_types.insert(std::make_pair(sname, named_type));
4384 go_assert(ins.second);
4385 return named_type;
4388 // Look up an existing float type.
4390 Named_type*
4391 Float_type::lookup_float_type(const char* name)
4393 Named_float_types::const_iterator p =
4394 Float_type::named_float_types.find(name);
4395 go_assert(p != Float_type::named_float_types.end());
4396 return p->second;
4399 // Create a new abstract float type.
4401 Float_type*
4402 Float_type::create_abstract_float_type()
4404 static Float_type* abstract_type;
4405 if (abstract_type == NULL)
4406 abstract_type = new Float_type(true, 64, RUNTIME_TYPE_KIND_FLOAT64);
4407 return abstract_type;
4410 // Whether this type is identical with T.
4412 bool
4413 Float_type::is_identical(const Float_type* t) const
4415 if (this->bits_ != t->bits_)
4416 return false;
4417 return this->is_abstract_ == t->is_abstract_;
4420 // Message name.
4422 void
4423 Float_type::do_message_name(std::string* ret) const
4425 ret->append("<untyped float");
4426 if (!this->is_abstract_)
4428 char buf[10];
4429 snprintf(buf, sizeof buf, "%d", this->bits_);
4430 ret->append(buf);
4432 ret->push_back('>');
4435 // Hash code.
4437 unsigned int
4438 Float_type::do_hash_for_method(Gogo*, int) const
4440 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4443 // Convert to the backend representation.
4445 Btype*
4446 Float_type::do_get_backend(Gogo* gogo)
4448 return gogo->backend()->float_type(this->bits_);
4451 // The type descriptor for a float type. Float types are always named.
4453 Expression*
4454 Float_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4456 go_assert(name != NULL || saw_errors());
4457 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4460 // We should not be asked for the reflection string of a basic type.
4462 void
4463 Float_type::do_reflection(Gogo*, std::string*) const
4465 go_assert(saw_errors());
4468 // Make a floating point type.
4470 Named_type*
4471 Type::make_float_type(const char* name, int bits, int runtime_type_kind)
4473 return Float_type::create_float_type(name, bits, runtime_type_kind);
4476 // Make an abstract float type.
4478 Float_type*
4479 Type::make_abstract_float_type()
4481 return Float_type::create_abstract_float_type();
4484 // Look up a float type.
4486 Named_type*
4487 Type::lookup_float_type(const char* name)
4489 return Float_type::lookup_float_type(name);
4492 // Class Complex_type.
4494 Complex_type::Named_complex_types Complex_type::named_complex_types;
4496 // Create a new complex type. Non-abstract complex types always have
4497 // names.
4499 Named_type*
4500 Complex_type::create_complex_type(const char* name, int bits,
4501 int runtime_type_kind)
4503 Complex_type* complex_type = new Complex_type(false, bits,
4504 runtime_type_kind);
4505 std::string sname(name);
4506 Named_object* named_object =
4507 Named_object::make_type(sname, NULL, complex_type,
4508 Linemap::predeclared_location());
4509 Named_type* named_type = named_object->type_value();
4510 std::pair<Named_complex_types::iterator, bool> ins =
4511 Complex_type::named_complex_types.insert(std::make_pair(sname,
4512 named_type));
4513 go_assert(ins.second);
4514 return named_type;
4517 // Look up an existing complex type.
4519 Named_type*
4520 Complex_type::lookup_complex_type(const char* name)
4522 Named_complex_types::const_iterator p =
4523 Complex_type::named_complex_types.find(name);
4524 go_assert(p != Complex_type::named_complex_types.end());
4525 return p->second;
4528 // Create a new abstract complex type.
4530 Complex_type*
4531 Complex_type::create_abstract_complex_type()
4533 static Complex_type* abstract_type;
4534 if (abstract_type == NULL)
4535 abstract_type = new Complex_type(true, 128, RUNTIME_TYPE_KIND_COMPLEX128);
4536 return abstract_type;
4539 // Whether this type is identical with T.
4541 bool
4542 Complex_type::is_identical(const Complex_type *t) const
4544 if (this->bits_ != t->bits_)
4545 return false;
4546 return this->is_abstract_ == t->is_abstract_;
4549 // Message name.
4551 void
4552 Complex_type::do_message_name(std::string* ret) const
4554 ret->append("<untyped complex");
4555 if (!this->is_abstract_)
4557 char buf[10];
4558 snprintf(buf, sizeof buf, "%d", this->bits_);
4559 ret->append(buf);
4561 ret->push_back('>');
4564 // Hash code.
4566 unsigned int
4567 Complex_type::do_hash_for_method(Gogo*, int) const
4569 return (this->bits_ << 4) + ((this->is_abstract_ ? 1 : 0) << 8);
4572 // Convert to the backend representation.
4574 Btype*
4575 Complex_type::do_get_backend(Gogo* gogo)
4577 return gogo->backend()->complex_type(this->bits_);
4580 // The type descriptor for a complex type. Complex types are always
4581 // named.
4583 Expression*
4584 Complex_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4586 go_assert(name != NULL || saw_errors());
4587 return this->plain_type_descriptor(gogo, this->runtime_type_kind_, name);
4590 // We should not be asked for the reflection string of a basic type.
4592 void
4593 Complex_type::do_reflection(Gogo*, std::string*) const
4595 go_assert(saw_errors());
4598 // Make a complex type.
4600 Named_type*
4601 Type::make_complex_type(const char* name, int bits, int runtime_type_kind)
4603 return Complex_type::create_complex_type(name, bits, runtime_type_kind);
4606 // Make an abstract complex type.
4608 Complex_type*
4609 Type::make_abstract_complex_type()
4611 return Complex_type::create_abstract_complex_type();
4614 // Look up a complex type.
4616 Named_type*
4617 Type::lookup_complex_type(const char* name)
4619 return Complex_type::lookup_complex_type(name);
4622 // Class String_type.
4624 // Convert String_type to the backend representation. A string is a
4625 // struct with two fields: a pointer to the characters and a length.
4627 Btype*
4628 String_type::do_get_backend(Gogo* gogo)
4630 static Btype* backend_string_type;
4631 if (backend_string_type == NULL)
4633 std::vector<Backend::Btyped_identifier> fields(2);
4635 Type* b = Type::lookup_integer_type("byte");
4636 Type* pb = Type::make_pointer_type(b);
4638 // We aren't going to get back to this field to finish the
4639 // backend representation, so force it to be finished now.
4640 if (!gogo->named_types_are_converted())
4642 Btype* bt = pb->get_backend_placeholder(gogo);
4643 pb->finish_backend(gogo, bt);
4646 fields[0].name = "__data";
4647 fields[0].btype = pb->get_backend(gogo);
4648 fields[0].location = Linemap::predeclared_location();
4650 Type* int_type = Type::lookup_integer_type("int");
4651 fields[1].name = "__length";
4652 fields[1].btype = int_type->get_backend(gogo);
4653 fields[1].location = fields[0].location;
4655 backend_string_type = gogo->backend()->struct_type(fields);
4657 return backend_string_type;
4660 // The type descriptor for the string type.
4662 Expression*
4663 String_type::do_type_descriptor(Gogo* gogo, Named_type* name)
4665 if (name != NULL)
4666 return this->plain_type_descriptor(gogo, RUNTIME_TYPE_KIND_STRING, name);
4667 else
4669 Named_object* no = gogo->lookup_global("string");
4670 go_assert(no != NULL);
4671 return Type::type_descriptor(gogo, no->type_value());
4675 // We should not be asked for the reflection string of a basic type.
4677 void
4678 String_type::do_reflection(Gogo*, std::string* ret) const
4680 ret->append("string");
4683 // Make a string type.
4685 Type*
4686 Type::make_string_type()
4688 static String_type string_type;
4689 return &string_type;
4692 // The named type "string".
4694 static Named_type* named_string_type;
4696 // Get the named type "string".
4698 Named_type*
4699 Type::lookup_string_type()
4701 return named_string_type;
4704 // Make the named type string.
4706 Named_type*
4707 Type::make_named_string_type()
4709 Type* string_type = Type::make_string_type();
4710 Named_object* named_object =
4711 Named_object::make_type("string", NULL, string_type,
4712 Linemap::predeclared_location());
4713 Named_type* named_type = named_object->type_value();
4714 named_string_type = named_type;
4715 return named_type;
4718 // The sink type. This is the type of the blank identifier _. Any
4719 // type may be assigned to it.
4721 class Sink_type : public Type
4723 public:
4724 Sink_type()
4725 : Type(TYPE_SINK)
4728 protected:
4729 void
4730 do_message_name(std::string* ret) const
4731 { ret->append("<SINK>"); }
4733 bool
4734 do_compare_is_identity(Gogo*)
4735 { return false; }
4737 Btype*
4738 do_get_backend(Gogo* gogo)
4740 go_assert(saw_errors());
4741 return gogo->backend()->error_type();
4744 Expression*
4745 do_type_descriptor(Gogo*, Named_type*)
4746 { go_unreachable(); }
4748 void
4749 do_reflection(Gogo*, std::string*) const
4750 { go_unreachable(); }
4752 void
4753 do_mangled_name(Gogo*, std::string*, bool*) const
4754 { go_unreachable(); }
4757 // Make the sink type.
4759 Type*
4760 Type::make_sink_type()
4762 static Sink_type sink_type;
4763 return &sink_type;
4766 // Class Function_type.
4768 // Message name.
4770 void
4771 Function_type::do_message_name(std::string* ret) const
4773 ret->append("func");
4774 if (this->receiver_ != NULL)
4776 ret->append(" (receiver ");
4777 this->append_message_name(this->receiver_->type(), ret);
4778 ret->append(") ");
4780 this->append_signature(ret);
4783 // Append just the signature to RET.
4785 void
4786 Function_type::append_signature(std::string* ret) const
4788 ret->push_back('(');
4789 if (this->parameters_ != NULL)
4791 bool first = true;
4792 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
4793 p != this->parameters_->end();
4794 ++p)
4796 if (first)
4797 first = false;
4798 else
4799 ret->append(", ");
4800 this->append_message_name(p->type(), ret);
4803 ret->push_back(')');
4805 if (this->results_ != NULL)
4807 if (this->results_->size() == 1)
4809 ret->push_back(' ');
4810 this->append_message_name(this->results_->front().type(), ret);
4812 else
4814 ret->append(" (");
4815 bool first = true;
4816 for (Typed_identifier_list::const_iterator p =
4817 this->results_->begin();
4818 p != this->results_->end();
4819 ++p)
4821 if (first)
4822 first = false;
4823 else
4824 ret->append(", ");
4825 this->append_message_name(p->type(), ret);
4827 ret->push_back(')');
4832 // Traversal.
4835 Function_type::do_traverse(Traverse* traverse)
4837 if (this->receiver_ != NULL
4838 && Type::traverse(this->receiver_->type(), traverse) == TRAVERSE_EXIT)
4839 return TRAVERSE_EXIT;
4840 if (this->parameters_ != NULL
4841 && this->parameters_->traverse(traverse) == TRAVERSE_EXIT)
4842 return TRAVERSE_EXIT;
4843 if (this->results_ != NULL
4844 && this->results_->traverse(traverse) == TRAVERSE_EXIT)
4845 return TRAVERSE_EXIT;
4846 return TRAVERSE_CONTINUE;
4849 // Returns whether T is a valid redeclaration of this type. If this
4850 // returns false, and REASON is not NULL, *REASON may be set to a
4851 // brief explanation of why it returned false.
4853 bool
4854 Function_type::is_valid_redeclaration(const Function_type* t,
4855 std::string* reason) const
4857 if (!this->is_identical(t, false, COMPARE_TAGS, reason))
4858 return false;
4860 // A redeclaration of a function is required to use the same names
4861 // for the receiver and parameters.
4862 if (this->receiver() != NULL
4863 && this->receiver()->name() != t->receiver()->name())
4865 if (reason != NULL)
4866 *reason = "receiver name changed";
4867 return false;
4870 const Typed_identifier_list* parms1 = this->parameters();
4871 const Typed_identifier_list* parms2 = t->parameters();
4872 if (parms1 != NULL)
4874 Typed_identifier_list::const_iterator p1 = parms1->begin();
4875 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4876 p2 != parms2->end();
4877 ++p2, ++p1)
4879 if (p1->name() != p2->name())
4881 if (reason != NULL)
4882 *reason = "parameter name changed";
4883 return false;
4886 // This is called at parse time, so we may have unknown
4887 // types.
4888 Type* t1 = p1->type()->forwarded();
4889 Type* t2 = p2->type()->forwarded();
4890 if (t1 != t2
4891 && t1->forward_declaration_type() != NULL
4892 && (t2->forward_declaration_type() == NULL
4893 || (t1->forward_declaration_type()->named_object()
4894 != t2->forward_declaration_type()->named_object())))
4895 return false;
4899 const Typed_identifier_list* results1 = this->results();
4900 const Typed_identifier_list* results2 = t->results();
4901 if (results1 != NULL)
4903 Typed_identifier_list::const_iterator res1 = results1->begin();
4904 for (Typed_identifier_list::const_iterator res2 = results2->begin();
4905 res2 != results2->end();
4906 ++res2, ++res1)
4908 if (res1->name() != res2->name())
4910 if (reason != NULL)
4911 *reason = "result name changed";
4912 return false;
4915 // This is called at parse time, so we may have unknown
4916 // types.
4917 Type* t1 = res1->type()->forwarded();
4918 Type* t2 = res2->type()->forwarded();
4919 if (t1 != t2
4920 && t1->forward_declaration_type() != NULL
4921 && (t2->forward_declaration_type() == NULL
4922 || (t1->forward_declaration_type()->named_object()
4923 != t2->forward_declaration_type()->named_object())))
4924 return false;
4928 return true;
4931 // Check whether T is the same as this type.
4933 bool
4934 Function_type::is_identical(const Function_type* t, bool ignore_receiver,
4935 int flags, std::string* reason) const
4937 if (this->is_backend_function_type() != t->is_backend_function_type())
4938 return false;
4940 if (!ignore_receiver)
4942 const Typed_identifier* r1 = this->receiver();
4943 const Typed_identifier* r2 = t->receiver();
4944 if ((r1 != NULL) != (r2 != NULL))
4946 if (reason != NULL)
4947 *reason = _("different receiver types");
4948 return false;
4950 if (r1 != NULL)
4952 if (!Type::are_identical(r1->type(), r2->type(), flags, reason))
4954 if (reason != NULL && !reason->empty())
4955 *reason = "receiver: " + *reason;
4956 return false;
4961 const Typed_identifier_list* parms1 = this->parameters();
4962 if (parms1 != NULL && parms1->empty())
4963 parms1 = NULL;
4964 const Typed_identifier_list* parms2 = t->parameters();
4965 if (parms2 != NULL && parms2->empty())
4966 parms2 = NULL;
4967 if ((parms1 != NULL) != (parms2 != NULL))
4969 if (reason != NULL)
4970 *reason = _("different number of parameters");
4971 return false;
4973 if (parms1 != NULL)
4975 Typed_identifier_list::const_iterator p1 = parms1->begin();
4976 for (Typed_identifier_list::const_iterator p2 = parms2->begin();
4977 p2 != parms2->end();
4978 ++p2, ++p1)
4980 if (p1 == parms1->end())
4982 if (reason != NULL)
4983 *reason = _("different number of parameters");
4984 return false;
4987 if (!Type::are_identical(p1->type(), p2->type(), flags, NULL))
4989 if (reason != NULL)
4990 *reason = _("different parameter types");
4991 return false;
4994 if (p1 != parms1->end())
4996 if (reason != NULL)
4997 *reason = _("different number of parameters");
4998 return false;
5002 if (this->is_varargs() != t->is_varargs())
5004 if (reason != NULL)
5005 *reason = _("different varargs");
5006 return false;
5009 const Typed_identifier_list* results1 = this->results();
5010 if (results1 != NULL && results1->empty())
5011 results1 = NULL;
5012 const Typed_identifier_list* results2 = t->results();
5013 if (results2 != NULL && results2->empty())
5014 results2 = NULL;
5015 if ((results1 != NULL) != (results2 != NULL))
5017 if (reason != NULL)
5018 *reason = _("different number of results");
5019 return false;
5021 if (results1 != NULL)
5023 Typed_identifier_list::const_iterator res1 = results1->begin();
5024 for (Typed_identifier_list::const_iterator res2 = results2->begin();
5025 res2 != results2->end();
5026 ++res2, ++res1)
5028 if (res1 == results1->end())
5030 if (reason != NULL)
5031 *reason = _("different number of results");
5032 return false;
5035 if (!Type::are_identical(res1->type(), res2->type(), flags, NULL))
5037 if (reason != NULL)
5038 *reason = _("different result types");
5039 return false;
5042 if (res1 != results1->end())
5044 if (reason != NULL)
5045 *reason = _("different number of results");
5046 return false;
5050 return true;
5053 // Hash code.
5055 unsigned int
5056 Function_type::do_hash_for_method(Gogo* gogo, int flags) const
5058 unsigned int ret = 0;
5059 // We ignore the receiver type for hash codes, because we need to
5060 // get the same hash code for a method in an interface and a method
5061 // declared for a type. The former will not have a receiver.
5062 if (this->parameters_ != NULL)
5064 int shift = 1;
5065 for (Typed_identifier_list::const_iterator p = this->parameters_->begin();
5066 p != this->parameters_->end();
5067 ++p, ++shift)
5068 ret += p->type()->hash_for_method(gogo, flags) << shift;
5070 if (this->results_ != NULL)
5072 int shift = 2;
5073 for (Typed_identifier_list::const_iterator p = this->results_->begin();
5074 p != this->results_->end();
5075 ++p, ++shift)
5076 ret += p->type()->hash_for_method(gogo, flags) << shift;
5078 if (this->is_varargs_)
5079 ret += 1;
5080 ret <<= 4;
5081 return ret;
5084 // Hash result parameters.
5086 unsigned int
5087 Function_type::Results_hash::operator()(const Typed_identifier_list* t) const
5089 unsigned int hash = 0;
5090 for (Typed_identifier_list::const_iterator p = t->begin();
5091 p != t->end();
5092 ++p)
5094 hash <<= 2;
5095 hash = Gogo::hash_string(p->name(), hash);
5096 hash += p->type()->hash_for_method(NULL, Type::COMPARE_TAGS);
5098 return hash;
5101 // Compare result parameters so that can map identical result
5102 // parameters to a single struct type.
5104 bool
5105 Function_type::Results_equal::operator()(const Typed_identifier_list* a,
5106 const Typed_identifier_list* b) const
5108 if (a->size() != b->size())
5109 return false;
5110 Typed_identifier_list::const_iterator pa = a->begin();
5111 for (Typed_identifier_list::const_iterator pb = b->begin();
5112 pb != b->end();
5113 ++pa, ++pb)
5115 if (pa->name() != pb->name()
5116 || !Type::are_identical(pa->type(), pb->type(), Type::COMPARE_TAGS,
5117 NULL))
5118 return false;
5120 return true;
5123 // Hash from results to a backend struct type.
5125 Function_type::Results_structs Function_type::results_structs;
5127 // Get the backend representation for a function type.
5129 Btype*
5130 Function_type::get_backend_fntype(Gogo* gogo)
5132 if (this->fnbtype_ == NULL)
5134 Backend::Btyped_identifier breceiver;
5135 if (this->receiver_ != NULL)
5137 breceiver.name = Gogo::unpack_hidden_name(this->receiver_->name());
5139 // We always pass the address of the receiver parameter, in
5140 // order to make interface calls work with unknown types,
5141 // except for direct interface types where the interface call
5142 // actually passes the underlying pointer of the value.
5143 Type* rtype = this->receiver_->type();
5144 if (rtype->points_to() == NULL)
5146 if (rtype->is_direct_iface_type())
5147 rtype = Type::make_pointer_type(Type::make_void_type());
5148 else
5149 rtype = Type::make_pointer_type(rtype);
5151 breceiver.btype = rtype->get_backend(gogo);
5152 breceiver.location = this->receiver_->location();
5155 std::vector<Backend::Btyped_identifier> bparameters;
5156 if (this->parameters_ != NULL)
5158 bparameters.resize(this->parameters_->size());
5159 size_t i = 0;
5160 for (Typed_identifier_list::const_iterator p =
5161 this->parameters_->begin(); p != this->parameters_->end();
5162 ++p, ++i)
5164 bparameters[i].name = Gogo::unpack_hidden_name(p->name());
5165 bparameters[i].btype = p->type()->get_backend(gogo);
5166 bparameters[i].location = p->location();
5168 go_assert(i == bparameters.size());
5171 std::vector<Backend::Btyped_identifier> bresults;
5172 Btype* bresult_struct = NULL;
5173 if (this->results_ != NULL)
5175 bresults.resize(this->results_->size());
5176 size_t i = 0;
5177 for (Typed_identifier_list::const_iterator p =
5178 this->results_->begin();
5179 p != this->results_->end();
5180 ++p, ++i)
5182 bresults[i].name = Gogo::unpack_hidden_name(p->name());
5183 bresults[i].btype = p->type()->get_backend(gogo);
5184 bresults[i].location = p->location();
5186 go_assert(i == bresults.size());
5188 if (this->results_->size() > 1)
5190 // Use the same results struct for all functions that
5191 // return the same set of results. This is useful to
5192 // unify calls to interface methods with other calls.
5193 std::pair<Typed_identifier_list*, Btype*> val;
5194 val.first = this->results_;
5195 val.second = NULL;
5196 std::pair<Results_structs::iterator, bool> ins =
5197 Function_type::results_structs.insert(val);
5198 if (ins.second)
5200 // Build a new struct type.
5201 Struct_field_list* sfl = new Struct_field_list;
5202 for (Typed_identifier_list::const_iterator p =
5203 this->results_->begin();
5204 p != this->results_->end();
5205 ++p)
5207 Typed_identifier tid = *p;
5208 if (tid.name().empty())
5209 tid = Typed_identifier("UNNAMED", tid.type(),
5210 tid.location());
5211 sfl->push_back(Struct_field(tid));
5213 Struct_type* st = Type::make_struct_type(sfl,
5214 this->location());
5215 st->set_is_struct_incomparable();
5216 st->set_is_results_struct();
5217 ins.first->second = st->get_backend(gogo);
5219 bresult_struct = ins.first->second;
5223 this->fnbtype_ = gogo->backend()->function_type(breceiver, bparameters,
5224 bresults, bresult_struct,
5225 this->location());
5229 return this->fnbtype_;
5232 // Get the backend representation for a Go function type.
5234 Btype*
5235 Function_type::do_get_backend(Gogo* gogo)
5237 // When we do anything with a function value other than call it, it
5238 // is represented as a pointer to a struct whose first field is the
5239 // actual function. So that is what we return as the type of a Go
5240 // function.
5242 Location loc = this->location();
5243 Btype* struct_type =
5244 gogo->backend()->placeholder_struct_type("__go_descriptor", loc);
5245 Btype* ptr_struct_type = gogo->backend()->pointer_type(struct_type);
5247 std::vector<Backend::Btyped_identifier> fields(1);
5248 fields[0].name = "code";
5249 fields[0].btype = this->get_backend_fntype(gogo);
5250 fields[0].location = loc;
5251 if (!gogo->backend()->set_placeholder_struct_type(struct_type, fields))
5252 return gogo->backend()->error_type();
5253 return ptr_struct_type;
5256 // The type of a function type descriptor.
5258 Type*
5259 Function_type::make_function_type_descriptor_type()
5261 static Type* ret;
5262 if (ret == NULL)
5264 Type* tdt = Type::make_type_descriptor_type();
5265 Type* ptdt = Type::make_type_descriptor_ptr_type();
5267 Type* bool_type = Type::lookup_bool_type();
5269 Type* slice_type = Type::make_array_type(ptdt, NULL);
5271 Struct_type* s = Type::make_builtin_struct_type(4,
5272 "", tdt,
5273 "dotdotdot", bool_type,
5274 "in", slice_type,
5275 "out", slice_type);
5277 ret = Type::make_builtin_named_type("FuncType", s);
5280 return ret;
5283 // The type descriptor for a function type.
5285 Expression*
5286 Function_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5288 Location bloc = Linemap::predeclared_location();
5290 Type* ftdt = Function_type::make_function_type_descriptor_type();
5292 const Struct_field_list* fields = ftdt->struct_type()->fields();
5294 Expression_list* vals = new Expression_list();
5295 vals->reserve(4);
5297 Struct_field_list::const_iterator p = fields->begin();
5298 go_assert(p->is_field_name("_type"));
5299 vals->push_back(this->type_descriptor_constructor(gogo,
5300 RUNTIME_TYPE_KIND_FUNC,
5301 name, NULL, true));
5303 ++p;
5304 go_assert(p->is_field_name("dotdotdot"));
5305 vals->push_back(Expression::make_boolean(this->is_varargs(), bloc));
5307 ++p;
5308 go_assert(p->is_field_name("in"));
5309 vals->push_back(this->type_descriptor_params(p->type(), this->receiver(),
5310 this->parameters()));
5312 ++p;
5313 go_assert(p->is_field_name("out"));
5314 vals->push_back(this->type_descriptor_params(p->type(), NULL,
5315 this->results()));
5317 ++p;
5318 go_assert(p == fields->end());
5320 return Expression::make_struct_composite_literal(ftdt, vals, bloc);
5323 // Return a composite literal for the parameters or results of a type
5324 // descriptor.
5326 Expression*
5327 Function_type::type_descriptor_params(Type* params_type,
5328 const Typed_identifier* receiver,
5329 const Typed_identifier_list* params)
5331 Location bloc = Linemap::predeclared_location();
5333 if (receiver == NULL && params == NULL)
5334 return Expression::make_slice_composite_literal(params_type, NULL, bloc);
5336 Expression_list* vals = new Expression_list();
5337 vals->reserve((params == NULL ? 0 : params->size())
5338 + (receiver != NULL ? 1 : 0));
5340 if (receiver != NULL)
5341 vals->push_back(Expression::make_type_descriptor(receiver->type(), bloc));
5343 if (params != NULL)
5345 for (Typed_identifier_list::const_iterator p = params->begin();
5346 p != params->end();
5347 ++p)
5348 vals->push_back(Expression::make_type_descriptor(p->type(), bloc));
5351 return Expression::make_slice_composite_literal(params_type, vals, bloc);
5354 // The reflection string.
5356 void
5357 Function_type::do_reflection(Gogo* gogo, std::string* ret) const
5359 // FIXME: Turn this off until we straighten out the type of the
5360 // struct field used in a go statement which calls a method.
5361 // go_assert(this->receiver_ == NULL);
5363 ret->append("func");
5365 if (this->receiver_ != NULL)
5367 ret->push_back('(');
5368 this->append_reflection(this->receiver_->type(), gogo, ret);
5369 ret->push_back(')');
5372 ret->push_back('(');
5373 const Typed_identifier_list* params = this->parameters();
5374 if (params != NULL)
5376 bool is_varargs = this->is_varargs_;
5377 for (Typed_identifier_list::const_iterator p = params->begin();
5378 p != params->end();
5379 ++p)
5381 if (p != params->begin())
5382 ret->append(", ");
5383 if (!is_varargs || p + 1 != params->end())
5384 this->append_reflection(p->type(), gogo, ret);
5385 else
5387 ret->append("...");
5388 this->append_reflection(p->type()->array_type()->element_type(),
5389 gogo, ret);
5393 ret->push_back(')');
5395 const Typed_identifier_list* results = this->results();
5396 if (results != NULL && !results->empty())
5398 if (results->size() == 1)
5399 ret->push_back(' ');
5400 else
5401 ret->append(" (");
5402 for (Typed_identifier_list::const_iterator p = results->begin();
5403 p != results->end();
5404 ++p)
5406 if (p != results->begin())
5407 ret->append(", ");
5408 this->append_reflection(p->type(), gogo, ret);
5410 if (results->size() > 1)
5411 ret->push_back(')');
5415 // Export a function type.
5417 void
5418 Function_type::do_export(Export* exp) const
5420 // We don't write out the receiver. The only function types which
5421 // should have a receiver are the ones associated with explicitly
5422 // defined methods. For those the receiver type is written out by
5423 // Function::export_func.
5425 exp->write_c_string("(");
5426 bool first = true;
5427 if (this->parameters_ != NULL)
5429 bool is_varargs = this->is_varargs_;
5430 for (Typed_identifier_list::const_iterator p =
5431 this->parameters_->begin();
5432 p != this->parameters_->end();
5433 ++p)
5435 if (first)
5436 first = false;
5437 else
5438 exp->write_c_string(", ");
5439 // The hash for a function type ignores parameter names, so
5440 // we don't want to write them out here. If we did write
5441 // them out, we could get spurious changes in export data
5442 // when recompiling a package.
5443 exp->write_name("");
5444 exp->write_c_string(" ");
5445 if (!is_varargs || p + 1 != this->parameters_->end())
5446 exp->write_type(p->type());
5447 else
5449 exp->write_c_string("...");
5450 exp->write_type(p->type()->array_type()->element_type());
5454 exp->write_c_string(")");
5456 const Typed_identifier_list* results = this->results_;
5457 if (results != NULL)
5459 exp->write_c_string(" ");
5460 if (results->size() == 1)
5461 exp->write_type(results->begin()->type());
5462 else
5464 first = true;
5465 exp->write_c_string("(");
5466 for (Typed_identifier_list::const_iterator p = results->begin();
5467 p != results->end();
5468 ++p)
5470 if (first)
5471 first = false;
5472 else
5473 exp->write_c_string(", ");
5474 exp->write_name("");
5475 exp->write_c_string(" ");
5476 exp->write_type(p->type());
5478 exp->write_c_string(")");
5483 // Import a function type.
5485 Function_type*
5486 Function_type::do_import(Import* imp)
5488 imp->require_c_string("(");
5489 Typed_identifier_list* parameters;
5490 bool is_varargs = false;
5491 if (imp->peek_char() == ')')
5492 parameters = NULL;
5493 else
5495 parameters = new Typed_identifier_list();
5496 while (true)
5498 std::string name = imp->read_name();
5499 imp->require_c_string(" ");
5501 if (imp->match_c_string("..."))
5503 imp->advance(3);
5504 is_varargs = true;
5507 Type* ptype = imp->read_type();
5508 if (is_varargs)
5509 ptype = Type::make_array_type(ptype, NULL);
5510 parameters->push_back(Typed_identifier(name, ptype,
5511 imp->location()));
5512 if (imp->peek_char() != ',')
5513 break;
5514 go_assert(!is_varargs);
5515 imp->require_c_string(", ");
5518 imp->require_c_string(")");
5520 Typed_identifier_list* results;
5521 if (imp->peek_char() != ' ')
5522 results = NULL;
5523 else
5525 imp->advance(1);
5526 results = new Typed_identifier_list;
5527 if (imp->peek_char() != '(')
5529 Type* rtype = imp->read_type();
5530 results->push_back(Typed_identifier("", rtype, imp->location()));
5532 else
5534 imp->advance(1);
5535 while (true)
5537 std::string name = imp->read_name();
5538 imp->require_c_string(" ");
5539 Type* rtype = imp->read_type();
5540 results->push_back(Typed_identifier(name, rtype,
5541 imp->location()));
5542 if (imp->peek_char() != ',')
5543 break;
5544 imp->require_c_string(", ");
5546 imp->require_c_string(")");
5550 Function_type* ret = Type::make_function_type(NULL, parameters, results,
5551 imp->location());
5552 if (is_varargs)
5553 ret->set_is_varargs();
5554 return ret;
5557 // Make a copy of a function type without a receiver.
5559 Function_type*
5560 Function_type::copy_without_receiver() const
5562 go_assert(this->is_method());
5563 Function_type *ret = Type::make_function_type(NULL, this->parameters_,
5564 this->results_,
5565 this->location_);
5566 if (this->is_varargs())
5567 ret->set_is_varargs();
5568 if (this->is_builtin())
5569 ret->set_is_builtin();
5570 return ret;
5573 // Make a copy of a function type with a receiver.
5575 Function_type*
5576 Function_type::copy_with_receiver(Type* receiver_type) const
5578 go_assert(!this->is_method());
5579 Typed_identifier* receiver = new Typed_identifier("", receiver_type,
5580 this->location_);
5581 Function_type* ret = Type::make_function_type(receiver, this->parameters_,
5582 this->results_,
5583 this->location_);
5584 if (this->is_varargs_)
5585 ret->set_is_varargs();
5586 return ret;
5589 // Make a copy of a function type with the receiver as the first
5590 // parameter.
5592 Function_type*
5593 Function_type::copy_with_receiver_as_param(bool want_pointer_receiver) const
5595 go_assert(this->is_method());
5596 Typed_identifier_list* new_params = new Typed_identifier_list();
5597 Type* rtype = this->receiver_->type();
5598 if (want_pointer_receiver)
5599 rtype = Type::make_pointer_type(rtype);
5600 Typed_identifier receiver(this->receiver_->name(), rtype,
5601 this->receiver_->location());
5602 new_params->push_back(receiver);
5603 const Typed_identifier_list* orig_params = this->parameters_;
5604 if (orig_params != NULL && !orig_params->empty())
5606 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5607 p != orig_params->end();
5608 ++p)
5609 new_params->push_back(*p);
5611 Function_type* ret = Type::make_function_type(NULL, new_params,
5612 this->results_,
5613 this->location_);
5614 if (this->is_varargs_)
5615 ret->set_is_varargs();
5616 return ret;
5619 // Make a copy of a function type ignoring any receiver and adding a
5620 // closure parameter.
5622 Function_type*
5623 Function_type::copy_with_names() const
5625 Typed_identifier_list* new_params = new Typed_identifier_list();
5626 const Typed_identifier_list* orig_params = this->parameters_;
5627 if (orig_params != NULL && !orig_params->empty())
5629 static int count;
5630 char buf[50];
5631 for (Typed_identifier_list::const_iterator p = orig_params->begin();
5632 p != orig_params->end();
5633 ++p)
5635 snprintf(buf, sizeof buf, "pt.%u", count);
5636 ++count;
5637 new_params->push_back(Typed_identifier(buf, p->type(),
5638 p->location()));
5642 const Typed_identifier_list* orig_results = this->results_;
5643 Typed_identifier_list* new_results;
5644 if (orig_results == NULL || orig_results->empty())
5645 new_results = NULL;
5646 else
5648 new_results = new Typed_identifier_list();
5649 for (Typed_identifier_list::const_iterator p = orig_results->begin();
5650 p != orig_results->end();
5651 ++p)
5652 new_results->push_back(Typed_identifier("", p->type(),
5653 p->location()));
5656 return Type::make_function_type(NULL, new_params, new_results,
5657 this->location());
5660 // Make a function type.
5662 Function_type*
5663 Type::make_function_type(Typed_identifier* receiver,
5664 Typed_identifier_list* parameters,
5665 Typed_identifier_list* results,
5666 Location location)
5668 return new Function_type(receiver, parameters, results, location);
5671 // Make a backend function type.
5673 Backend_function_type*
5674 Type::make_backend_function_type(Typed_identifier* receiver,
5675 Typed_identifier_list* parameters,
5676 Typed_identifier_list* results,
5677 Location location)
5679 return new Backend_function_type(receiver, parameters, results, location);
5682 // Class Pointer_type.
5684 // Message name.
5686 void
5687 Pointer_type::do_message_name(std::string* ret) const
5689 if (this->to_type_->is_void_type())
5690 ret->append("unsafe.Pointer");
5691 else
5693 ret->push_back('*');
5694 this->append_message_name(this->to_type_, ret);
5698 // Traversal.
5701 Pointer_type::do_traverse(Traverse* traverse)
5703 return Type::traverse(this->to_type_, traverse);
5706 // Hash code.
5708 unsigned int
5709 Pointer_type::do_hash_for_method(Gogo* gogo, int flags) const
5711 return this->to_type_->hash_for_method(gogo, flags) << 4;
5714 // Get the backend representation for a pointer type.
5716 Btype*
5717 Pointer_type::do_get_backend(Gogo* gogo)
5719 Btype* to_btype = this->to_type_->get_backend(gogo);
5720 return gogo->backend()->pointer_type(to_btype);
5723 // The type of a pointer type descriptor.
5725 Type*
5726 Pointer_type::make_pointer_type_descriptor_type()
5728 static Type* ret;
5729 if (ret == NULL)
5731 Type* tdt = Type::make_type_descriptor_type();
5732 Type* ptdt = Type::make_type_descriptor_ptr_type();
5734 Struct_type* s = Type::make_builtin_struct_type(2,
5735 "", tdt,
5736 "elem", ptdt);
5738 ret = Type::make_builtin_named_type("PtrType", s);
5741 return ret;
5744 // The type descriptor for a pointer type.
5746 Expression*
5747 Pointer_type::do_type_descriptor(Gogo* gogo, Named_type* name)
5749 if (this->is_unsafe_pointer_type())
5751 go_assert(name != NULL);
5752 return this->plain_type_descriptor(gogo,
5753 RUNTIME_TYPE_KIND_UNSAFE_POINTER,
5754 name);
5756 else
5758 Location bloc = Linemap::predeclared_location();
5760 const Methods* methods;
5761 Type* deref = this->points_to();
5762 if (deref->named_type() != NULL)
5763 methods = deref->named_type()->methods();
5764 else if (deref->struct_type() != NULL)
5765 methods = deref->struct_type()->methods();
5766 else
5767 methods = NULL;
5769 Type* ptr_tdt = Pointer_type::make_pointer_type_descriptor_type();
5771 const Struct_field_list* fields = ptr_tdt->struct_type()->fields();
5773 Expression_list* vals = new Expression_list();
5774 vals->reserve(2);
5776 Struct_field_list::const_iterator p = fields->begin();
5777 go_assert(p->is_field_name("_type"));
5778 vals->push_back(this->type_descriptor_constructor(gogo,
5779 RUNTIME_TYPE_KIND_PTR,
5780 name, methods, false));
5782 ++p;
5783 go_assert(p->is_field_name("elem"));
5784 vals->push_back(Expression::make_type_descriptor(deref, bloc));
5786 return Expression::make_struct_composite_literal(ptr_tdt, vals, bloc);
5790 // Reflection string.
5792 void
5793 Pointer_type::do_reflection(Gogo* gogo, std::string* ret) const
5795 ret->push_back('*');
5796 this->append_reflection(this->to_type_, gogo, ret);
5799 // Export.
5801 void
5802 Pointer_type::do_export(Export* exp) const
5804 exp->write_c_string("*");
5805 if (this->is_unsafe_pointer_type())
5806 exp->write_c_string("any");
5807 else
5808 exp->write_type(this->to_type_);
5811 // Import.
5813 Pointer_type*
5814 Pointer_type::do_import(Import* imp)
5816 imp->require_c_string("*");
5817 if (imp->match_c_string("any"))
5819 imp->advance(3);
5820 return Type::make_pointer_type(Type::make_void_type());
5822 Type* to = imp->read_type();
5823 return Type::make_pointer_type(to);
5826 // Cache of pointer types. Key is "to" type, value is pointer type
5827 // that points to key.
5829 Type::Pointer_type_table Type::pointer_types;
5831 // A list of placeholder pointer types; items on this list will be either be
5832 // Pointer_type or Function_type. We keep this so we can ensure they are
5833 // finalized.
5835 std::vector<Type*> Type::placeholder_pointers;
5837 // Make a pointer type.
5839 Pointer_type*
5840 Type::make_pointer_type(Type* to_type)
5842 Pointer_type_table::const_iterator p = pointer_types.find(to_type);
5843 if (p != pointer_types.end())
5844 return p->second;
5845 Pointer_type* ret = new Pointer_type(to_type);
5846 pointer_types[to_type] = ret;
5847 return ret;
5850 // This helper is invoked immediately after named types have been
5851 // converted, to clean up any unresolved pointer types remaining in
5852 // the pointer type cache.
5854 // The motivation for this routine: occasionally the compiler creates
5855 // some specific pointer type as part of a lowering operation (ex:
5856 // pointer-to-void), then Type::backend_type_size() is invoked on the
5857 // type (which creates a Btype placeholder for it), that placeholder
5858 // passed somewhere along the line to the back end, but since there is
5859 // no reference to the type in user code, there is never a call to
5860 // Type::finish_backend for the type (hence the Btype remains as an
5861 // unresolved placeholder). Calling this routine will clean up such
5862 // instances.
5864 void
5865 Type::finish_pointer_types(Gogo* gogo)
5867 // We don't use begin() and end() because it is possible to add new
5868 // placeholder pointer types as we finalized existing ones.
5869 for (size_t i = 0; i < Type::placeholder_pointers.size(); i++)
5871 Type* typ = Type::placeholder_pointers[i];
5872 Type_btypes::iterator tbti = Type::type_btypes.find(typ);
5873 if (tbti != Type::type_btypes.end() && tbti->second.is_placeholder)
5875 typ->finish_backend(gogo, tbti->second.btype);
5876 tbti->second.is_placeholder = false;
5881 // Class Nil_type.
5883 // Get the backend representation of a nil type. FIXME: Is this ever
5884 // actually called?
5886 Btype*
5887 Nil_type::do_get_backend(Gogo* gogo)
5889 return gogo->backend()->pointer_type(gogo->backend()->void_type());
5892 // Make the nil type.
5894 Type*
5895 Type::make_nil_type()
5897 static Nil_type singleton_nil_type;
5898 return &singleton_nil_type;
5901 // The type of a function call which returns multiple values. This is
5902 // really a struct, but we don't want to confuse a function call which
5903 // returns a struct with a function call which returns multiple
5904 // values.
5906 class Call_multiple_result_type : public Type
5908 public:
5909 Call_multiple_result_type()
5910 : Type(TYPE_CALL_MULTIPLE_RESULT)
5913 protected:
5914 void
5915 do_message_name(std::string* ret) const
5916 { ret->append("<call-multiple-result>"); }
5918 bool
5919 do_has_pointer() const
5920 { return false; }
5922 bool
5923 do_compare_is_identity(Gogo*)
5924 { return false; }
5926 Btype*
5927 do_get_backend(Gogo* gogo)
5929 go_assert(saw_errors());
5930 return gogo->backend()->error_type();
5933 Expression*
5934 do_type_descriptor(Gogo*, Named_type*)
5936 go_assert(saw_errors());
5937 return Expression::make_error(Linemap::unknown_location());
5940 void
5941 do_reflection(Gogo*, std::string*) const
5942 { go_assert(saw_errors()); }
5944 void
5945 do_mangled_name(Gogo*, std::string*, bool*) const
5946 { go_assert(saw_errors()); }
5949 // Make a call result type.
5951 Type*
5952 Type::make_call_multiple_result_type()
5954 return new Call_multiple_result_type;
5957 // Class Struct_field.
5959 // Get the name of a field.
5961 const std::string&
5962 Struct_field::field_name() const
5964 const std::string& name(this->typed_identifier_.name());
5965 if (!name.empty())
5966 return name;
5967 else
5969 // This is called during parsing, before anything is lowered, so
5970 // we have to be pretty careful to avoid dereferencing an
5971 // unknown type name.
5972 Type* t = this->typed_identifier_.type();
5973 Type* dt = t;
5974 if (t->classification() == Type::TYPE_POINTER)
5976 // Very ugly.
5977 Pointer_type* ptype = static_cast<Pointer_type*>(t);
5978 dt = ptype->points_to();
5980 if (dt->forward_declaration_type() != NULL)
5981 return dt->forward_declaration_type()->name();
5982 else if (dt->named_type() != NULL)
5984 // Note that this can be an alias name.
5985 return dt->named_type()->name();
5987 else if (t->is_error_type() || dt->is_error_type())
5989 static const std::string error_string = "*error*";
5990 return error_string;
5992 else
5994 // Avoid crashing in the erroneous case where T is named but
5995 // DT is not.
5996 go_assert(t != dt);
5997 if (t->forward_declaration_type() != NULL)
5998 return t->forward_declaration_type()->name();
5999 else if (t->named_type() != NULL)
6000 return t->named_type()->name();
6001 else
6002 go_unreachable();
6007 // Return whether this field is named NAME.
6009 bool
6010 Struct_field::is_field_name(const std::string& name) const
6012 const std::string& me(this->typed_identifier_.name());
6013 if (!me.empty())
6014 return me == name;
6015 else
6017 Type* t = this->typed_identifier_.type();
6018 if (t->points_to() != NULL)
6019 t = t->points_to();
6020 Named_type* nt = t->named_type();
6021 if (nt != NULL && nt->name() == name)
6022 return true;
6024 // This is a horrible hack caused by the fact that we don't pack
6025 // the names of builtin types. FIXME.
6026 if (!this->is_imported_
6027 && nt != NULL
6028 && nt->is_builtin()
6029 && nt->name() == Gogo::unpack_hidden_name(name))
6030 return true;
6032 return false;
6036 // Return whether this field is an unexported field named NAME.
6038 bool
6039 Struct_field::is_unexported_field_name(Gogo* gogo,
6040 const std::string& name) const
6042 const std::string& field_name(this->field_name());
6043 if (Gogo::is_hidden_name(field_name)
6044 && name == Gogo::unpack_hidden_name(field_name)
6045 && gogo->pack_hidden_name(name, false) != field_name)
6046 return true;
6048 // Check for the name of a builtin type. This is like the test in
6049 // is_field_name, only there we return false if this->is_imported_,
6050 // and here we return true.
6051 if (this->is_imported_ && this->is_anonymous())
6053 Type* t = this->typed_identifier_.type();
6054 if (t->points_to() != NULL)
6055 t = t->points_to();
6056 Named_type* nt = t->named_type();
6057 if (nt != NULL
6058 && nt->is_builtin()
6059 && nt->name() == Gogo::unpack_hidden_name(name))
6060 return true;
6063 return false;
6066 // Return whether this field is an embedded built-in type.
6068 bool
6069 Struct_field::is_embedded_builtin(Gogo* gogo) const
6071 const std::string& name(this->field_name());
6072 // We know that a field is an embedded type if it is anonymous.
6073 // We can decide if it is a built-in type by checking to see if it is
6074 // registered globally under the field's name.
6075 // This allows us to distinguish between embedded built-in types and
6076 // embedded types that are aliases to built-in types.
6077 return (this->is_anonymous()
6078 && !Gogo::is_hidden_name(name)
6079 && gogo->lookup_global(name.c_str()) != NULL);
6082 // Class Struct_type.
6084 // A hash table used to find identical unnamed structs so that they
6085 // share method tables.
6087 Struct_type::Identical_structs Struct_type::identical_structs;
6089 // A hash table used to merge method sets for identical unnamed
6090 // structs.
6092 Struct_type::Struct_method_tables Struct_type::struct_method_tables;
6094 // Message name.
6096 void
6097 Struct_type::do_message_name(std::string* ret) const
6099 if (this->fields_ == NULL || this->fields_->empty())
6101 ret->append("struct{}");
6102 return;
6105 ret->append("struct {");
6107 bool first = true;
6108 for (Struct_field_list::const_iterator p = this->fields_->begin();
6109 p != this->fields_->end();
6110 ++p)
6112 if (first)
6113 first = false;
6114 else
6115 ret->append("; ");
6117 if (!p->is_anonymous())
6119 ret->append(p->field_name());
6120 ret->push_back(' ');
6123 this->append_message_name(p->type(), ret);
6126 ret->append(" }");
6129 // Traversal.
6132 Struct_type::do_traverse(Traverse* traverse)
6134 Struct_field_list* fields = this->fields_;
6135 if (fields != NULL)
6137 for (Struct_field_list::iterator p = fields->begin();
6138 p != fields->end();
6139 ++p)
6141 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
6142 return TRAVERSE_EXIT;
6145 return TRAVERSE_CONTINUE;
6148 // Verify that the struct type is complete and valid.
6150 bool
6151 Struct_type::do_verify(Gogo*)
6153 Struct_field_list* fields = this->fields_;
6154 if (fields == NULL)
6155 return true;
6156 for (Struct_field_list::iterator p = fields->begin();
6157 p != fields->end();
6158 ++p)
6160 Type* t = p->type();
6161 if (p->is_anonymous())
6163 if ((t->named_type() != NULL && t->points_to() != NULL)
6164 || (t->named_type() == NULL && t->points_to() != NULL
6165 && t->points_to()->points_to() != NULL))
6167 go_error_at(p->location(), "embedded type may not be a pointer");
6168 p->set_type(Type::make_error_type());
6169 this->set_is_error();
6171 else if (t->points_to() != NULL
6172 && t->points_to()->interface_type() != NULL)
6174 go_error_at(p->location(),
6175 "embedded type may not be pointer to interface");
6176 p->set_type(Type::make_error_type());
6177 this->set_is_error();
6181 return true;
6184 // Whether this contains a pointer.
6186 bool
6187 Struct_type::do_has_pointer() const
6189 const Struct_field_list* fields = this->fields();
6190 if (fields == NULL)
6191 return false;
6192 for (Struct_field_list::const_iterator p = fields->begin();
6193 p != fields->end();
6194 ++p)
6196 if (p->type()->has_pointer())
6197 return true;
6199 return false;
6202 // Whether this type is identical to T.
6204 bool
6205 Struct_type::is_identical(const Struct_type* t, int flags) const
6207 if (this->is_struct_incomparable_ != t->is_struct_incomparable_)
6208 return false;
6209 const Struct_field_list* fields1 = this->fields();
6210 const Struct_field_list* fields2 = t->fields();
6211 if (fields1 == NULL || fields2 == NULL)
6212 return fields1 == fields2;
6213 Struct_field_list::const_iterator pf2 = fields2->begin();
6214 for (Struct_field_list::const_iterator pf1 = fields1->begin();
6215 pf1 != fields1->end();
6216 ++pf1, ++pf2)
6218 if (pf2 == fields2->end())
6219 return false;
6220 if (pf1->field_name() != pf2->field_name())
6221 return false;
6222 if (pf1->is_anonymous() != pf2->is_anonymous()
6223 || !Type::are_identical(pf1->type(), pf2->type(), flags, NULL))
6224 return false;
6225 if ((flags & Type::COMPARE_TAGS) != 0)
6227 if (!pf1->has_tag())
6229 if (pf2->has_tag())
6230 return false;
6232 else
6234 if (!pf2->has_tag())
6235 return false;
6236 if (pf1->tag() != pf2->tag())
6237 return false;
6241 if (pf2 != fields2->end())
6242 return false;
6243 return true;
6246 // Whether comparisons of this struct type are simple identity
6247 // comparisons.
6249 bool
6250 Struct_type::do_compare_is_identity(Gogo* gogo)
6252 const Struct_field_list* fields = this->fields_;
6253 if (fields == NULL)
6254 return true;
6255 int64_t offset = 0;
6256 for (Struct_field_list::const_iterator pf = fields->begin();
6257 pf != fields->end();
6258 ++pf)
6260 if (Gogo::is_sink_name(pf->field_name()))
6261 return false;
6263 if (!pf->type()->compare_is_identity(gogo))
6264 return false;
6266 int64_t field_align;
6267 if (!pf->type()->backend_type_align(gogo, &field_align))
6268 return false;
6269 if ((offset & (field_align - 1)) != 0)
6271 // This struct has padding. We don't guarantee that that
6272 // padding is zero-initialized for a stack variable, so we
6273 // can't use memcmp to compare struct values.
6274 return false;
6277 int64_t field_size;
6278 if (!pf->type()->backend_type_size(gogo, &field_size))
6279 return false;
6280 offset += field_size;
6283 int64_t struct_size;
6284 if (!this->backend_type_size(gogo, &struct_size))
6285 return false;
6286 if (offset != struct_size)
6288 // Trailing padding may not be zero when on the stack.
6289 return false;
6292 return true;
6295 // Return whether this struct type is reflexive--whether a value of
6296 // this type is always equal to itself.
6298 bool
6299 Struct_type::do_is_reflexive()
6301 const Struct_field_list* fields = this->fields_;
6302 if (fields == NULL)
6303 return true;
6304 for (Struct_field_list::const_iterator pf = fields->begin();
6305 pf != fields->end();
6306 ++pf)
6308 if (!pf->type()->is_reflexive())
6309 return false;
6311 return true;
6314 // Return whether this struct type needs a key update when used as a
6315 // map key.
6317 bool
6318 Struct_type::do_needs_key_update()
6320 const Struct_field_list* fields = this->fields_;
6321 if (fields == NULL)
6322 return false;
6323 for (Struct_field_list::const_iterator pf = fields->begin();
6324 pf != fields->end();
6325 ++pf)
6327 if (pf->type()->needs_key_update())
6328 return true;
6330 return false;
6333 // Return whether computing the hash value of an instance of this
6334 // struct type might panic.
6336 bool
6337 Struct_type::do_hash_might_panic()
6339 const Struct_field_list* fields = this->fields_;
6340 if (fields == NULL)
6341 return false;
6342 for (Struct_field_list::const_iterator pf = fields->begin();
6343 pf != fields->end();
6344 ++pf)
6346 if (pf->type()->hash_might_panic())
6347 return true;
6349 return false;
6352 // Return whether this struct type is permitted to be in the heap.
6354 bool
6355 Struct_type::do_in_heap() const
6357 const Struct_field_list* fields = this->fields_;
6358 if (fields == NULL)
6359 return true;
6360 for (Struct_field_list::const_iterator pf = fields->begin();
6361 pf != fields->end();
6362 ++pf)
6364 if (!pf->type()->in_heap())
6365 return false;
6367 return true;
6370 // Build identity and hash functions for this struct.
6372 // Hash code.
6374 unsigned int
6375 Struct_type::do_hash_for_method(Gogo* gogo, int flags) const
6377 unsigned int ret = 0;
6378 if (this->fields() != NULL)
6380 for (Struct_field_list::const_iterator pf = this->fields()->begin();
6381 pf != this->fields()->end();
6382 ++pf)
6383 ret = (ret << 1) + pf->type()->hash_for_method(gogo, flags);
6385 ret <<= 2;
6386 if (this->is_struct_incomparable_)
6387 ret <<= 1;
6388 return ret;
6391 // Find the local field NAME.
6393 const Struct_field*
6394 Struct_type::find_local_field(const std::string& name,
6395 unsigned int *pindex) const
6397 const Struct_field_list* fields = this->fields_;
6398 if (fields == NULL)
6399 return NULL;
6400 unsigned int i = 0;
6401 for (Struct_field_list::const_iterator pf = fields->begin();
6402 pf != fields->end();
6403 ++pf, ++i)
6405 if (pf->is_field_name(name))
6407 if (pindex != NULL)
6408 *pindex = i;
6409 return &*pf;
6412 return NULL;
6415 // Return an expression for field NAME in STRUCT_EXPR, or NULL.
6417 Field_reference_expression*
6418 Struct_type::field_reference(Expression* struct_expr, const std::string& name,
6419 Location location) const
6421 unsigned int depth;
6422 return this->field_reference_depth(struct_expr, name, location, NULL,
6423 &depth);
6426 // Return an expression for a field, along with the depth at which it
6427 // was found.
6429 Field_reference_expression*
6430 Struct_type::field_reference_depth(Expression* struct_expr,
6431 const std::string& name,
6432 Location location,
6433 Saw_named_type* saw,
6434 unsigned int* depth) const
6436 const Struct_field_list* fields = this->fields_;
6437 if (fields == NULL)
6438 return NULL;
6440 // Look for a field with this name.
6441 unsigned int i = 0;
6442 for (Struct_field_list::const_iterator pf = fields->begin();
6443 pf != fields->end();
6444 ++pf, ++i)
6446 if (pf->is_field_name(name))
6448 *depth = 0;
6449 return Expression::make_field_reference(struct_expr, i, location);
6453 // Look for an anonymous field which contains a field with this
6454 // name.
6455 unsigned int found_depth = 0;
6456 Field_reference_expression* ret = NULL;
6457 i = 0;
6458 for (Struct_field_list::const_iterator pf = fields->begin();
6459 pf != fields->end();
6460 ++pf, ++i)
6462 if (!pf->is_anonymous())
6463 continue;
6465 Struct_type* st = pf->type()->deref()->struct_type();
6466 if (st == NULL)
6467 continue;
6469 Saw_named_type* hold_saw = saw;
6470 Saw_named_type saw_here;
6471 Named_type* nt = pf->type()->named_type();
6472 if (nt == NULL)
6473 nt = pf->type()->deref()->named_type();
6474 if (nt != NULL)
6476 Saw_named_type* q;
6477 for (q = saw; q != NULL; q = q->next)
6479 if (q->nt == nt)
6481 // If this is an error, it will be reported
6482 // elsewhere.
6483 break;
6486 if (q != NULL)
6487 continue;
6488 saw_here.next = saw;
6489 saw_here.nt = nt;
6490 saw = &saw_here;
6493 // Look for a reference using a NULL struct expression. If we
6494 // find one, fill in the struct expression with a reference to
6495 // this field.
6496 unsigned int subdepth;
6497 Field_reference_expression* sub = st->field_reference_depth(NULL, name,
6498 location,
6499 saw,
6500 &subdepth);
6502 saw = hold_saw;
6504 if (sub == NULL)
6505 continue;
6507 if (ret == NULL || subdepth < found_depth)
6509 if (ret != NULL)
6510 delete ret;
6511 ret = sub;
6512 found_depth = subdepth;
6513 Expression* here = Expression::make_field_reference(struct_expr, i,
6514 location);
6515 if (pf->type()->points_to() != NULL)
6516 here = Expression::make_dereference(here,
6517 Expression::NIL_CHECK_DEFAULT,
6518 location);
6519 while (sub->expr() != NULL)
6521 sub = sub->expr()->deref()->field_reference_expression();
6522 go_assert(sub != NULL);
6524 sub->set_struct_expression(here);
6525 sub->set_implicit(true);
6527 else if (subdepth > found_depth)
6528 delete sub;
6529 else
6531 // We do not handle ambiguity here--it should be handled by
6532 // Type::bind_field_or_method.
6533 delete sub;
6534 found_depth = 0;
6535 ret = NULL;
6539 if (ret != NULL)
6540 *depth = found_depth + 1;
6542 return ret;
6545 // Return the total number of fields, including embedded fields.
6547 unsigned int
6548 Struct_type::total_field_count() const
6550 if (this->fields_ == NULL)
6551 return 0;
6552 unsigned int ret = 0;
6553 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6554 pf != this->fields_->end();
6555 ++pf)
6557 if (!pf->is_anonymous() || pf->type()->struct_type() == NULL)
6558 ++ret;
6559 else
6560 ret += pf->type()->struct_type()->total_field_count();
6562 return ret;
6565 // Return whether NAME is an unexported field, for better error reporting.
6567 bool
6568 Struct_type::is_unexported_local_field(Gogo* gogo,
6569 const std::string& name) const
6571 const Struct_field_list* fields = this->fields_;
6572 if (fields != NULL)
6574 for (Struct_field_list::const_iterator pf = fields->begin();
6575 pf != fields->end();
6576 ++pf)
6577 if (pf->is_unexported_field_name(gogo, name))
6578 return true;
6580 return false;
6583 // Finalize the methods of an unnamed struct.
6585 void
6586 Struct_type::finalize_methods(Gogo* gogo)
6588 if (this->all_methods_ != NULL)
6589 return;
6591 // It is possible to have multiple identical structs that have
6592 // methods. We want them to share method tables. Otherwise we will
6593 // emit identical methods more than once, which is bad since they
6594 // will even have the same names.
6595 std::pair<Identical_structs::iterator, bool> ins =
6596 Struct_type::identical_structs.insert(std::make_pair(this, this));
6597 if (!ins.second)
6599 // An identical struct was already entered into the hash table.
6600 // Note that finalize_methods is, fortunately, not recursive.
6601 this->all_methods_ = ins.first->second->all_methods_;
6602 return;
6605 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
6608 // Return the method NAME, or NULL if there isn't one or if it is
6609 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
6610 // ambiguous.
6612 Method*
6613 Struct_type::method_function(const std::string& name, bool* is_ambiguous) const
6615 return Type::method_function(this->all_methods_, name, is_ambiguous);
6618 // Return a pointer to the interface method table for this type for
6619 // the interface INTERFACE. IS_POINTER is true if this is for a
6620 // pointer to THIS.
6622 Expression*
6623 Struct_type::interface_method_table(Interface_type* interface,
6624 bool is_pointer)
6626 std::pair<Struct_type*, Struct_type::Struct_method_table_pair*>
6627 val(this, nullptr);
6628 std::pair<Struct_type::Struct_method_tables::iterator, bool> ins =
6629 Struct_type::struct_method_tables.insert(val);
6631 Struct_method_table_pair* smtp;
6632 if (!ins.second)
6633 smtp = ins.first->second;
6634 else
6636 smtp = new Struct_method_table_pair();
6637 smtp->first = NULL;
6638 smtp->second = NULL;
6639 ins.first->second = smtp;
6642 return Type::interface_method_table(this, interface, is_pointer,
6643 &smtp->first, &smtp->second);
6646 // Convert struct fields to the backend representation. This is not
6647 // declared in types.h so that types.h doesn't have to #include
6648 // backend.h.
6650 static void
6651 get_backend_struct_fields(Gogo* gogo, Struct_type* type, bool use_placeholder,
6652 std::vector<Backend::Btyped_identifier>* bfields)
6654 const Struct_field_list* fields = type->fields();
6655 bfields->resize(fields->size());
6656 size_t i = 0;
6657 int64_t lastsize = 0;
6658 bool saw_nonzero = false;
6659 for (Struct_field_list::const_iterator p = fields->begin();
6660 p != fields->end();
6661 ++p, ++i)
6663 (*bfields)[i].name = Gogo::unpack_hidden_name(p->field_name());
6664 (*bfields)[i].btype = (use_placeholder
6665 ? p->type()->get_backend_placeholder(gogo)
6666 : p->type()->get_backend(gogo));
6667 (*bfields)[i].location = p->location();
6668 int64_t size = gogo->backend()->type_size((*bfields)[i].btype);
6669 if (size != 0)
6670 saw_nonzero = true;
6672 if (size > 0 || !Gogo::is_sink_name(p->field_name()))
6673 lastsize = size;
6674 else
6676 // There is an unreferenceable field of zero size. This
6677 // doesn't affect whether we may need zero padding, so leave
6678 // lastsize unchanged.
6681 go_assert(i == fields->size());
6682 if (saw_nonzero && lastsize == 0 && !type->is_results_struct())
6684 // For nonzero-sized structs which end in a zero-sized thing, we add
6685 // an extra byte of padding to the type. This padding ensures that
6686 // taking the address of the zero-sized thing can't manufacture a
6687 // pointer to the next object in the heap. See issue 9401.
6688 size_t n = fields->size();
6689 bfields->resize(n + 1);
6690 (*bfields)[n].name = "_";
6691 (*bfields)[n].btype = Type::lookup_integer_type("uint8")->get_backend(gogo);
6692 (*bfields)[n].location = (*bfields)[n-1].location;
6693 type->set_has_padding();
6697 // Get the backend representation for a struct type.
6699 Btype*
6700 Struct_type::do_get_backend(Gogo* gogo)
6702 std::vector<Backend::Btyped_identifier> bfields;
6703 get_backend_struct_fields(gogo, this, false, &bfields);
6704 return gogo->backend()->struct_type(bfields);
6707 // Finish the backend representation of the fields of a struct.
6709 void
6710 Struct_type::finish_backend_fields(Gogo* gogo)
6712 const Struct_field_list* fields = this->fields_;
6713 if (fields != NULL)
6715 for (Struct_field_list::const_iterator p = fields->begin();
6716 p != fields->end();
6717 ++p)
6718 p->type()->get_backend(gogo);
6722 // The type of a struct type descriptor.
6724 Type*
6725 Struct_type::make_struct_type_descriptor_type()
6727 static Type* ret;
6728 if (ret == NULL)
6730 Type* tdt = Type::make_type_descriptor_type();
6731 Type* ptdt = Type::make_type_descriptor_ptr_type();
6733 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6734 Type* string_type = Type::lookup_string_type();
6735 Type* pointer_string_type = Type::make_pointer_type(string_type);
6737 Struct_type* sf =
6738 Type::make_builtin_struct_type(5,
6739 "name", pointer_string_type,
6740 "pkgPath", pointer_string_type,
6741 "typ", ptdt,
6742 "tag", pointer_string_type,
6743 "offsetAnon", uintptr_type);
6744 Type* nsf = Type::make_builtin_named_type("structField", sf);
6746 Type* slice_type = Type::make_array_type(nsf, NULL);
6748 Struct_type* s = Type::make_builtin_struct_type(2,
6749 "", tdt,
6750 "fields", slice_type);
6752 ret = Type::make_builtin_named_type("StructType", s);
6755 return ret;
6758 // Build a type descriptor for a struct type.
6760 Expression*
6761 Struct_type::do_type_descriptor(Gogo* gogo, Named_type* name)
6763 Location bloc = Linemap::predeclared_location();
6765 Type* stdt = Struct_type::make_struct_type_descriptor_type();
6767 const Struct_field_list* fields = stdt->struct_type()->fields();
6769 Expression_list* vals = new Expression_list();
6770 vals->reserve(2);
6772 const Methods* methods = this->methods();
6773 // A named struct should not have methods--the methods should attach
6774 // to the named type.
6775 go_assert(methods == NULL || name == NULL);
6777 Struct_field_list::const_iterator ps = fields->begin();
6778 go_assert(ps->is_field_name("_type"));
6779 vals->push_back(this->type_descriptor_constructor(gogo,
6780 RUNTIME_TYPE_KIND_STRUCT,
6781 name, methods, true));
6783 ++ps;
6784 go_assert(ps->is_field_name("fields"));
6786 Expression_list* elements = new Expression_list();
6787 elements->reserve(this->fields_->size());
6788 Type* element_type = ps->type()->array_type()->element_type();
6789 for (Struct_field_list::const_iterator pf = this->fields_->begin();
6790 pf != this->fields_->end();
6791 ++pf)
6793 const Struct_field_list* f = element_type->struct_type()->fields();
6795 Expression_list* fvals = new Expression_list();
6796 fvals->reserve(5);
6798 Struct_field_list::const_iterator q = f->begin();
6799 go_assert(q->is_field_name("name"));
6800 std::string n = Gogo::unpack_hidden_name(pf->field_name());
6801 Expression* s = Expression::make_string(n, bloc);
6802 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6804 ++q;
6805 go_assert(q->is_field_name("pkgPath"));
6806 bool is_embedded_builtin = pf->is_embedded_builtin(gogo);
6807 if (!Gogo::is_hidden_name(pf->field_name()) && !is_embedded_builtin)
6808 fvals->push_back(Expression::make_nil(bloc));
6809 else
6811 if (is_embedded_builtin)
6812 n = gogo->package_name();
6813 else
6814 n = Gogo::hidden_name_pkgpath(pf->field_name());
6815 s = Expression::make_string(n, bloc);
6816 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6819 ++q;
6820 go_assert(q->is_field_name("typ"));
6821 fvals->push_back(Expression::make_type_descriptor(pf->type(), bloc));
6823 ++q;
6824 go_assert(q->is_field_name("tag"));
6825 if (!pf->has_tag())
6826 fvals->push_back(Expression::make_nil(bloc));
6827 else
6829 s = Expression::make_string(pf->tag(), bloc);
6830 fvals->push_back(Expression::make_unary(OPERATOR_AND, s, bloc));
6833 ++q;
6834 go_assert(q->is_field_name("offsetAnon"));
6835 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6836 Expression* o = Expression::make_struct_field_offset(this, &*pf);
6837 Expression* one = Expression::make_integer_ul(1, uintptr_type, bloc);
6838 o = Expression::make_binary(OPERATOR_LSHIFT, o, one, bloc);
6839 int av = pf->is_anonymous() ? 1 : 0;
6840 Expression* anon = Expression::make_integer_ul(av, uintptr_type, bloc);
6841 o = Expression::make_binary(OPERATOR_OR, o, anon, bloc);
6842 fvals->push_back(o);
6844 Expression* v = Expression::make_struct_composite_literal(element_type,
6845 fvals, bloc);
6846 elements->push_back(v);
6849 vals->push_back(Expression::make_slice_composite_literal(ps->type(),
6850 elements, bloc));
6852 return Expression::make_struct_composite_literal(stdt, vals, bloc);
6855 // Write the hash function for a struct which can not use the identity
6856 // function.
6858 void
6859 Struct_type::write_hash_function(Gogo* gogo, Named_object* function,
6860 Function_type* hash_fntype)
6862 Location bloc = Linemap::predeclared_location();
6864 // The pointer to the struct that we are going to hash. This is an
6865 // argument to the hash function we are implementing here.
6866 Named_object* key_arg = gogo->lookup("key", NULL);
6867 go_assert(key_arg != NULL);
6868 Type* key_arg_type = key_arg->var_value()->type();
6870 // The seed argument to the hash function.
6871 Named_object* seed_arg = gogo->lookup("seed", NULL);
6872 go_assert(seed_arg != NULL);
6874 Type* uintptr_type = Type::lookup_integer_type("uintptr");
6876 // Make a temporary to hold the return value, initialized to the seed.
6877 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
6878 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
6879 bloc);
6880 retval->determine_types(gogo);
6881 gogo->add_statement(retval);
6883 // Make a temporary to hold the key as a uintptr.
6884 ref = Expression::make_var_reference(key_arg, bloc);
6885 ref = Expression::make_cast(uintptr_type, ref, bloc);
6886 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
6887 bloc);
6888 key->determine_types(gogo);
6889 gogo->add_statement(key);
6891 // Loop over the struct fields.
6892 const Struct_field_list* fields = this->fields_;
6893 for (Struct_field_list::const_iterator pf = fields->begin();
6894 pf != fields->end();
6895 ++pf)
6897 if (Gogo::is_sink_name(pf->field_name()))
6898 continue;
6900 // Get a pointer to the value of this field.
6901 Expression* offset = Expression::make_struct_field_offset(this, &*pf);
6902 ref = Expression::make_temporary_reference(key, bloc);
6903 Expression* subkey = Expression::make_binary(OPERATOR_PLUS, ref, offset,
6904 bloc);
6905 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
6907 // Get the hash function to use for the type of this field.
6908 Named_object* hash_fn =
6909 pf->type()->unalias()->hash_function(gogo, hash_fntype);
6911 // Call the hash function for the field, passing retval as the seed.
6912 ref = Expression::make_temporary_reference(retval, bloc);
6913 Expression_list* args = new Expression_list();
6914 args->push_back(subkey);
6915 args->push_back(ref);
6916 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
6917 Expression* call = Expression::make_call(func, args, false, bloc);
6919 // Set retval to the result.
6920 Temporary_reference_expression* tref =
6921 Expression::make_temporary_reference(retval, bloc);
6922 tref->set_is_lvalue();
6923 Statement* s = Statement::make_assignment(tref, call, bloc);
6924 s->determine_types(gogo);
6925 gogo->add_statement(s);
6928 // Return retval to the caller of the hash function.
6929 Expression_list* vals = new Expression_list();
6930 ref = Expression::make_temporary_reference(retval, bloc);
6931 vals->push_back(ref);
6932 Statement* s = Statement::make_return_statement(function, vals, bloc);
6933 s->determine_types(gogo);
6934 gogo->add_statement(s);
6937 // Write the equality function for a struct which can not use the
6938 // identity function.
6940 void
6941 Struct_type::write_equal_function(Gogo* gogo, Named_object* function,
6942 Named_type* name)
6944 Location bloc = Linemap::predeclared_location();
6946 // The pointers to the structs we are going to compare.
6947 Named_object* key1_arg = gogo->lookup("key1", NULL);
6948 Named_object* key2_arg = gogo->lookup("key2", NULL);
6949 go_assert(key1_arg != NULL && key2_arg != NULL);
6951 // Build temporaries with the right types.
6952 Type* pt = Type::make_pointer_type(name != NULL
6953 ? static_cast<Type*>(name)
6954 : static_cast<Type*>(this));
6956 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
6957 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6958 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
6959 p1->determine_types(gogo);
6960 gogo->add_statement(p1);
6962 ref = Expression::make_var_reference(key2_arg, bloc);
6963 ref = Expression::make_unsafe_cast(pt, ref, bloc);
6964 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
6965 p2->determine_types(gogo);
6966 gogo->add_statement(p2);
6968 const Struct_field_list* fields = this->fields_;
6969 unsigned int field_index = 0;
6970 for (Struct_field_list::const_iterator pf = fields->begin();
6971 pf != fields->end();
6972 ++pf, ++field_index)
6974 if (Gogo::is_sink_name(pf->field_name()))
6975 continue;
6977 // Compare one field in both P1 and P2.
6978 Expression* f1 = Expression::make_temporary_reference(p1, bloc);
6979 f1 = Expression::make_dereference(f1, Expression::NIL_CHECK_DEFAULT,
6980 bloc);
6981 f1 = Expression::make_field_reference(f1, field_index, bloc);
6983 Expression* f2 = Expression::make_temporary_reference(p2, bloc);
6984 f2 = Expression::make_dereference(f2, Expression::NIL_CHECK_DEFAULT,
6985 bloc);
6986 f2 = Expression::make_field_reference(f2, field_index, bloc);
6988 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, f1, f2, bloc);
6990 // If the values are not equal, return false.
6991 gogo->start_block(bloc);
6992 Expression_list* vals = new Expression_list();
6993 vals->push_back(Expression::make_boolean(false, bloc));
6994 Statement* s = Statement::make_return_statement(function, vals, bloc);
6995 s->determine_types(gogo);
6996 gogo->add_statement(s);
6997 Block* then_block = gogo->finish_block(bloc);
6999 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7000 s->determine_types(gogo);
7001 gogo->add_statement(s);
7004 // All the fields are equal, so return true.
7005 Expression_list* vals = new Expression_list();
7006 vals->push_back(Expression::make_boolean(true, bloc));
7007 Statement* s = Statement::make_return_statement(function, vals, bloc);
7008 s->determine_types(gogo);
7009 gogo->add_statement(s);
7012 // Reflection string.
7014 void
7015 Struct_type::do_reflection(Gogo* gogo, std::string* ret) const
7017 ret->append("struct {");
7019 for (Struct_field_list::const_iterator p = this->fields_->begin();
7020 p != this->fields_->end();
7021 ++p)
7023 if (p != this->fields_->begin())
7024 ret->push_back(';');
7025 ret->push_back(' ');
7026 if (!p->is_anonymous())
7028 ret->append(Gogo::unpack_hidden_name(p->field_name()));
7029 ret->push_back(' ');
7031 if (p->is_anonymous()
7032 && p->type()->named_type() != NULL
7033 && p->type()->named_type()->is_alias())
7034 p->type()->named_type()->append_reflection_type_name(gogo, true, ret);
7035 else
7036 this->append_reflection(p->type(), gogo, ret);
7038 if (p->has_tag())
7040 const std::string& tag(p->tag());
7041 ret->append(" \"");
7042 for (std::string::const_iterator pt = tag.begin();
7043 pt != tag.end();
7044 ++pt)
7046 if (*pt == '\0')
7047 ret->append("\\x00");
7048 else if (*pt == '\n')
7049 ret->append("\\n");
7050 else if (*pt == '\t')
7051 ret->append("\\t");
7052 else if (*pt == '"')
7053 ret->append("\\\"");
7054 else if (*pt == '\\')
7055 ret->append("\\\\");
7056 else
7057 ret->push_back(*pt);
7059 ret->push_back('"');
7063 if (!this->fields_->empty())
7064 ret->push_back(' ');
7066 ret->push_back('}');
7069 // If the offset of field INDEX in the backend implementation can be
7070 // determined, set *POFFSET to the offset in bytes and return true.
7071 // Otherwise, return false.
7073 bool
7074 Struct_type::backend_field_offset(Gogo* gogo, unsigned int index,
7075 int64_t* poffset)
7077 if (!this->is_backend_type_size_known(gogo))
7078 return false;
7079 Btype* bt = this->get_backend_placeholder(gogo);
7080 *poffset = gogo->backend()->type_field_offset(bt, index);
7081 return true;
7084 // Export.
7086 void
7087 Struct_type::do_export(Export* exp) const
7089 exp->write_c_string("struct { ");
7090 const Struct_field_list* fields = this->fields_;
7091 go_assert(fields != NULL);
7092 for (Struct_field_list::const_iterator p = fields->begin();
7093 p != fields->end();
7094 ++p)
7096 if (p->is_anonymous())
7097 exp->write_string("? ");
7098 else
7100 exp->write_string(p->field_name());
7101 exp->write_c_string(" ");
7103 exp->write_type(p->type());
7105 if (p->has_tag())
7107 exp->write_c_string(" ");
7108 Expression* expr =
7109 Expression::make_string(p->tag(), Linemap::predeclared_location());
7111 Export_function_body efb(exp, 0);
7112 expr->export_expression(&efb);
7113 exp->write_string(efb.body());
7115 delete expr;
7118 exp->write_c_string("; ");
7120 exp->write_c_string("}");
7123 // Import.
7125 Struct_type*
7126 Struct_type::do_import(Import* imp)
7128 imp->require_c_string("struct { ");
7129 Struct_field_list* fields = new Struct_field_list;
7130 if (imp->peek_char() != '}')
7132 while (true)
7134 std::string name;
7135 if (imp->match_c_string("? "))
7136 imp->advance(2);
7137 else
7139 name = imp->read_identifier();
7140 imp->require_c_string(" ");
7142 Type* ftype = imp->read_type();
7144 Struct_field sf(Typed_identifier(name, ftype, imp->location()));
7145 sf.set_is_imported();
7147 if (imp->peek_char() == ' ')
7149 imp->advance(1);
7150 Expression* expr = Expression::import_expression(imp,
7151 imp->location());
7152 String_expression* sexpr = expr->string_expression();
7153 go_assert(sexpr != NULL);
7154 sf.set_tag(sexpr->val());
7155 delete sexpr;
7158 imp->require_c_string("; ");
7159 fields->push_back(sf);
7160 if (imp->peek_char() == '}')
7161 break;
7164 imp->require_c_string("}");
7166 return Type::make_struct_type(fields, imp->location());
7169 // Whether we can write this struct type to a C header file.
7170 // We can't if any of the fields are structs defined in a different package.
7172 bool
7173 Struct_type::can_write_to_c_header(
7174 std::vector<const Named_object*>* needs,
7175 std::vector<const Named_object*>* declare) const
7177 const Struct_field_list* fields = this->fields_;
7178 if (fields == NULL || fields->empty())
7179 return false;
7180 int sinks = 0;
7181 for (Struct_field_list::const_iterator p = fields->begin();
7182 p != fields->end();
7183 ++p)
7185 if (!this->can_write_type_to_c_header(p->type(), needs, declare))
7186 return false;
7187 if (Gogo::message_name(p->field_name()) == "_")
7188 sinks++;
7190 if (sinks > 1)
7191 return false;
7192 return true;
7195 // Whether we can write the type T to a C header file.
7197 bool
7198 Struct_type::can_write_type_to_c_header(
7199 const Type* t,
7200 std::vector<const Named_object*>* needs,
7201 std::vector<const Named_object*>* declare) const
7203 t = t->forwarded();
7204 switch (t->classification())
7206 case TYPE_ERROR:
7207 case TYPE_FORWARD:
7208 return false;
7210 case TYPE_VOID:
7211 case TYPE_BOOLEAN:
7212 case TYPE_INTEGER:
7213 case TYPE_FLOAT:
7214 case TYPE_COMPLEX:
7215 case TYPE_STRING:
7216 case TYPE_FUNCTION:
7217 case TYPE_MAP:
7218 case TYPE_CHANNEL:
7219 case TYPE_INTERFACE:
7220 return true;
7222 case TYPE_POINTER:
7223 // Don't try to handle a pointer to an array.
7224 if (t->points_to()->array_type() != NULL
7225 && !t->points_to()->is_slice_type())
7226 return false;
7228 if (t->points_to()->named_type() != NULL
7229 && t->points_to()->struct_type() != NULL)
7230 declare->push_back(t->points_to()->named_type()->named_object());
7231 return true;
7233 case TYPE_STRUCT:
7234 return t->struct_type()->can_write_to_c_header(needs, declare);
7236 case TYPE_ARRAY:
7237 if (t->is_slice_type())
7238 return true;
7239 return this->can_write_type_to_c_header(t->array_type()->element_type(),
7240 needs, declare);
7242 case TYPE_NAMED:
7244 const Named_object* no = t->named_type()->named_object();
7245 if (no->package() != NULL)
7247 if (t->is_unsafe_pointer_type())
7248 return true;
7249 return false;
7251 if (t->struct_type() != NULL)
7253 // We will accept empty struct fields, but not print them.
7254 if (t->struct_type()->total_field_count() == 0)
7255 return true;
7256 needs->push_back(no);
7257 return t->struct_type()->can_write_to_c_header(needs, declare);
7259 return this->can_write_type_to_c_header(t->base(), needs, declare);
7262 case TYPE_CALL_MULTIPLE_RESULT:
7263 case TYPE_NIL:
7264 case TYPE_SINK:
7265 default:
7266 go_unreachable();
7270 // Write this struct to a C header file.
7272 void
7273 Struct_type::write_to_c_header(std::ostream& os) const
7275 const Struct_field_list* fields = this->fields_;
7276 for (Struct_field_list::const_iterator p = fields->begin();
7277 p != fields->end();
7278 ++p)
7280 // Skip fields that are empty struct types. The C code can't
7281 // refer to them anyhow.
7282 if (p->type()->struct_type() != NULL
7283 && p->type()->struct_type()->total_field_count() == 0)
7284 continue;
7286 os << '\t';
7287 this->write_field_to_c_header(os, p->field_name(), p->type());
7288 os << ';' << std::endl;
7292 // Write the type of a struct field to a C header file.
7294 void
7295 Struct_type::write_field_to_c_header(std::ostream& os, const std::string& name,
7296 const Type *t) const
7298 bool print_name = true;
7299 t = t->forwarded();
7300 switch (t->classification())
7302 case TYPE_VOID:
7303 os << "void";
7304 break;
7306 case TYPE_BOOLEAN:
7307 os << "_Bool";
7308 break;
7310 case TYPE_INTEGER:
7312 const Integer_type* it = t->integer_type();
7313 if (it->is_unsigned())
7314 os << 'u';
7315 os << "int" << it->bits() << "_t";
7317 break;
7319 case TYPE_FLOAT:
7320 switch (t->float_type()->bits())
7322 case 32:
7323 os << "float";
7324 break;
7325 case 64:
7326 os << "double";
7327 break;
7328 default:
7329 go_unreachable();
7331 break;
7333 case TYPE_COMPLEX:
7334 switch (t->complex_type()->bits())
7336 case 64:
7337 os << "float _Complex";
7338 break;
7339 case 128:
7340 os << "double _Complex";
7341 break;
7342 default:
7343 go_unreachable();
7345 break;
7347 case TYPE_STRING:
7348 os << "String";
7349 break;
7351 case TYPE_FUNCTION:
7352 os << "FuncVal*";
7353 break;
7355 case TYPE_POINTER:
7357 std::vector<const Named_object*> needs;
7358 std::vector<const Named_object*> declare;
7359 if (!this->can_write_type_to_c_header(t->points_to(), &needs,
7360 &declare))
7361 os << "void*";
7362 else
7364 this->write_field_to_c_header(os, "", t->points_to());
7365 os << '*';
7368 break;
7370 case TYPE_MAP:
7371 os << "Map*";
7372 break;
7374 case TYPE_CHANNEL:
7375 os << "Chan*";
7376 break;
7378 case TYPE_INTERFACE:
7379 if (t->interface_type()->is_empty())
7380 os << "Eface";
7381 else
7382 os << "Iface";
7383 break;
7385 case TYPE_STRUCT:
7386 os << "struct {" << std::endl;
7387 t->struct_type()->write_to_c_header(os);
7388 os << "\t}";
7389 break;
7391 case TYPE_ARRAY:
7392 if (t->is_slice_type())
7393 os << "Slice";
7394 else
7396 const Type *ele = t;
7397 std::vector<const Type*> array_types;
7398 while (ele->array_type() != NULL && !ele->is_slice_type())
7400 array_types.push_back(ele);
7401 ele = ele->array_type()->element_type();
7403 this->write_field_to_c_header(os, "", ele);
7404 os << ' ' << Gogo::message_name(name);
7405 print_name = false;
7406 while (!array_types.empty())
7408 ele = array_types.back();
7409 array_types.pop_back();
7410 os << '[';
7411 Numeric_constant nc;
7412 if (!ele->array_type()->length()->numeric_constant_value(&nc))
7413 go_unreachable();
7414 mpz_t val;
7415 if (!nc.to_int(&val))
7416 go_unreachable();
7417 char* s = mpz_get_str(NULL, 10, val);
7418 os << s;
7419 free(s);
7420 mpz_clear(val);
7421 os << ']';
7424 break;
7426 case TYPE_NAMED:
7428 const Named_object* no = t->named_type()->named_object();
7429 if (t->struct_type() != NULL)
7430 os << "struct " << no->message_name();
7431 else if (t->is_unsafe_pointer_type())
7432 os << "void*";
7433 else if (t == Type::lookup_integer_type("uintptr"))
7434 os << "uintptr_t";
7435 else
7437 this->write_field_to_c_header(os, name, t->base());
7438 print_name = false;
7441 break;
7443 case TYPE_ERROR:
7444 case TYPE_FORWARD:
7445 case TYPE_CALL_MULTIPLE_RESULT:
7446 case TYPE_NIL:
7447 case TYPE_SINK:
7448 default:
7449 go_unreachable();
7452 if (print_name && !name.empty())
7453 os << ' ' << Gogo::message_name(name);
7456 // Make a struct type.
7458 Struct_type*
7459 Type::make_struct_type(Struct_field_list* fields,
7460 Location location)
7462 return new Struct_type(fields, location);
7465 // Class Array_type.
7467 // Store the length of an array as an int64_t into *PLEN. Return
7468 // false if the length can not be determined. This will assert if
7469 // called for a slice.
7471 bool
7472 Array_type::int_length(int64_t* plen) const
7474 go_assert(this->length_ != NULL);
7475 Numeric_constant nc;
7476 if (!this->length_->numeric_constant_value(&nc))
7477 return false;
7478 return nc.to_memory_size(plen);
7481 // Whether two array types are identical.
7483 bool
7484 Array_type::is_identical(const Array_type* t, int flags) const
7486 if (!Type::are_identical(this->element_type(), t->element_type(),
7487 flags, NULL))
7488 return false;
7490 if (this->is_array_incomparable_ != t->is_array_incomparable_)
7491 return false;
7493 Expression* l1 = this->length();
7494 Expression* l2 = t->length();
7496 // Slices of the same element type are identical.
7497 if (l1 == NULL && l2 == NULL)
7498 return true;
7500 // Arrays of the same element type are identical if they have the
7501 // same length.
7502 if (l1 != NULL && l2 != NULL)
7504 if (l1 == l2)
7505 return true;
7507 // Try to determine the lengths. If we can't, assume the arrays
7508 // are not identical.
7509 bool ret = false;
7510 Numeric_constant nc1, nc2;
7511 if (l1->numeric_constant_value(&nc1)
7512 && l2->numeric_constant_value(&nc2))
7514 mpz_t v1;
7515 if (nc1.to_int(&v1))
7517 mpz_t v2;
7518 if (nc2.to_int(&v2))
7520 ret = mpz_cmp(v1, v2) == 0;
7521 mpz_clear(v2);
7523 mpz_clear(v1);
7526 return ret;
7529 // Otherwise the arrays are not identical.
7530 return false;
7533 // Message name.
7535 void
7536 Array_type::do_message_name(std::string* ret) const
7538 ret->push_back('[');
7539 if (!this->is_slice_type())
7541 Numeric_constant nc;
7542 if (!this->length_->numeric_constant_value(&nc))
7543 ret->append("<unknown length>");
7544 else
7546 mpz_t val;
7547 if (!nc.to_int(&val))
7548 ret->append("<unknown length>");
7549 else
7551 char* s = mpz_get_str(NULL, 10, val);
7552 ret->append(s);
7553 free(s);
7554 mpz_clear(val);
7558 ret->push_back(']');
7559 this->append_message_name(this->element_type_, ret);
7562 // Traversal.
7565 Array_type::do_traverse(Traverse* traverse)
7567 if (Type::traverse(this->element_type_, traverse) == TRAVERSE_EXIT)
7568 return TRAVERSE_EXIT;
7569 if (this->length_ != NULL
7570 && Expression::traverse(&this->length_, traverse) == TRAVERSE_EXIT)
7571 return TRAVERSE_EXIT;
7572 return TRAVERSE_CONTINUE;
7575 // Check that the length is valid.
7577 bool
7578 Array_type::verify_length(Gogo* gogo)
7580 if (this->length_ == NULL)
7581 return true;
7583 Type* int_type = Type::lookup_integer_type("int");
7584 Type_context int_context(int_type, false);
7585 this->length_->determine_type(gogo, &int_context);
7587 if (this->length_->is_error_expression()
7588 || this->length_->type()->is_error())
7590 go_assert(saw_errors());
7591 return false;
7594 if (!this->length_->is_constant())
7596 go_error_at(this->length_->location(), "array bound is not constant");
7597 return false;
7600 // For array types, the length expression can be an untyped constant
7601 // representable as an int, but we don't allow explicitly non-integer
7602 // values such as "float64(10)". See issues #13485 and #13486.
7603 if (this->length_->type()->integer_type() == NULL
7604 && !this->length_->type()->is_error_type())
7606 go_error_at(this->length_->location(), "invalid array bound");
7607 return false;
7610 Numeric_constant nc;
7611 if (!this->length_->numeric_constant_value(&nc))
7613 if (this->length_->type()->integer_type() != NULL
7614 || this->length_->type()->float_type() != NULL)
7615 go_error_at(this->length_->location(), "array bound is not constant");
7616 else
7617 go_error_at(this->length_->location(), "array bound is not numeric");
7618 return false;
7621 unsigned int tbits = int_type->integer_type()->bits();
7622 unsigned long val;
7623 switch (nc.to_unsigned_long(&val))
7625 case Numeric_constant::NC_UL_VALID:
7626 if (sizeof(val) >= tbits / 8 && val >> (tbits - 1) != 0)
7628 go_error_at(this->length_->location(), "array bound overflows");
7629 return false;
7631 break;
7632 case Numeric_constant::NC_UL_NOTINT:
7633 go_error_at(this->length_->location(), "array bound truncated to integer");
7634 return false;
7635 case Numeric_constant::NC_UL_NEGATIVE:
7636 go_error_at(this->length_->location(), "negative array bound");
7637 return false;
7638 case Numeric_constant::NC_UL_BIG:
7640 mpz_t mval;
7641 if (!nc.to_int(&mval))
7642 go_unreachable();
7643 unsigned int bits = mpz_sizeinbase(mval, 2);
7644 mpz_clear(mval);
7645 if (bits >= tbits)
7647 go_error_at(this->length_->location(), "array bound overflows");
7648 return false;
7651 break;
7652 default:
7653 go_unreachable();
7656 return true;
7659 // Verify the type.
7661 bool
7662 Array_type::do_verify(Gogo* gogo)
7664 if (this->element_type()->is_error_type())
7666 this->set_is_error();
7667 return false;
7669 if (!this->verify_length(gogo))
7671 this->length_ = Expression::make_error(this->length_->location());
7672 this->set_is_error();
7674 return true;
7677 // Whether the type contains pointers. This is always true for a
7678 // slice. For an array it is true if the element type has pointers
7679 // and the length is greater than zero.
7681 bool
7682 Array_type::do_has_pointer() const
7684 if (this->length_ == NULL)
7685 return true;
7686 if (!this->element_type_->has_pointer())
7687 return false;
7689 Numeric_constant nc;
7690 if (!this->length_->numeric_constant_value(&nc))
7692 // Error reported elsewhere.
7693 return false;
7696 unsigned long val;
7697 switch (nc.to_unsigned_long(&val))
7699 case Numeric_constant::NC_UL_VALID:
7700 return val > 0;
7701 case Numeric_constant::NC_UL_BIG:
7702 return true;
7703 default:
7704 // Error reported elsewhere.
7705 return false;
7709 // Whether we can use memcmp to compare this array.
7711 bool
7712 Array_type::do_compare_is_identity(Gogo* gogo)
7714 if (this->length_ == NULL)
7715 return false;
7717 // Check for [...], which indicates that this is not a real type.
7718 if (this->length_->is_nil_expression())
7719 return false;
7721 if (!this->element_type_->compare_is_identity(gogo))
7722 return false;
7724 // If there is any padding, then we can't use memcmp.
7725 int64_t size;
7726 int64_t align;
7727 if (!this->element_type_->backend_type_size(gogo, &size)
7728 || !this->element_type_->backend_type_align(gogo, &align))
7729 return false;
7730 if ((size & (align - 1)) != 0)
7731 return false;
7733 return true;
7736 // Array type hash code.
7738 unsigned int
7739 Array_type::do_hash_for_method(Gogo* gogo, int flags) const
7741 unsigned int ret;
7743 // There is no very convenient way to get a hash code for the
7744 // length.
7745 ret = this->element_type_->hash_for_method(gogo, flags) + 1;
7746 if (this->is_array_incomparable_)
7747 ret <<= 1;
7748 return ret;
7751 // Write the hash function for an array which can not use the identify
7752 // function.
7754 void
7755 Array_type::write_hash_function(Gogo* gogo, Named_object* function,
7756 Function_type* hash_fntype)
7758 Location bloc = Linemap::predeclared_location();
7760 // The pointer to the array that we are going to hash. This is an
7761 // argument to the hash function we are implementing here.
7762 Named_object* key_arg = gogo->lookup("key", NULL);
7763 go_assert(key_arg != NULL);
7764 Type* key_arg_type = key_arg->var_value()->type();
7766 // The seed argument to the hash function.
7767 Named_object* seed_arg = gogo->lookup("seed", NULL);
7768 go_assert(seed_arg != NULL);
7770 Type* uintptr_type = Type::lookup_integer_type("uintptr");
7772 // Make a temporary to hold the return value, initialized to the seed.
7773 Expression* ref = Expression::make_var_reference(seed_arg, bloc);
7774 Temporary_statement* retval = Statement::make_temporary(uintptr_type, ref,
7775 bloc);
7776 retval->determine_types(gogo);
7777 gogo->add_statement(retval);
7779 // Make a temporary to hold the key as a uintptr.
7780 ref = Expression::make_var_reference(key_arg, bloc);
7781 ref = Expression::make_cast(uintptr_type, ref, bloc);
7782 Temporary_statement* key = Statement::make_temporary(uintptr_type, ref,
7783 bloc);
7784 key->determine_types(gogo);
7785 gogo->add_statement(key);
7787 // Loop over the array elements.
7788 // for i = range a
7789 Type* int_type = Type::lookup_integer_type("int");
7790 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7791 index->determine_types(gogo);
7792 gogo->add_statement(index);
7794 Expression* iref = Expression::make_temporary_reference(index, bloc);
7795 Expression* aref = Expression::make_var_reference(key_arg, bloc);
7796 Type* pt = Type::make_pointer_type(static_cast<Type*>(this));
7797 aref = Expression::make_cast(pt, aref, bloc);
7798 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7799 NULL,
7800 aref,
7801 bloc);
7803 gogo->start_block(bloc);
7805 // Get the hash function for the element type.
7806 Named_object* hash_fn =
7807 this->element_type_->unalias()->hash_function(gogo, hash_fntype);
7809 // Get a pointer to this element in the loop.
7810 Expression* subkey = Expression::make_temporary_reference(key, bloc);
7811 subkey = Expression::make_cast(key_arg_type, subkey, bloc);
7813 // Get the size of each element.
7814 Expression* ele_size = Expression::make_type_info(this->element_type_,
7815 Expression::TYPE_INFO_SIZE);
7817 // Get the hash of this element, passing retval as the seed.
7818 ref = Expression::make_temporary_reference(retval, bloc);
7819 Expression_list* args = new Expression_list();
7820 args->push_back(subkey);
7821 args->push_back(ref);
7822 Expression* func = Expression::make_func_reference(hash_fn, NULL, bloc);
7823 Expression* call = Expression::make_call(func, args, false, bloc);
7825 // Set retval to the result.
7826 Temporary_reference_expression* tref =
7827 Expression::make_temporary_reference(retval, bloc);
7828 tref->set_is_lvalue();
7829 Statement* s = Statement::make_assignment(tref, call, bloc);
7830 s->determine_types(gogo);
7831 gogo->add_statement(s);
7833 // Increase the element pointer.
7834 tref = Expression::make_temporary_reference(key, bloc);
7835 tref->set_is_lvalue();
7836 s = Statement::make_assignment_operation(OPERATOR_PLUSEQ, tref, ele_size,
7837 bloc);
7838 Block* statements = gogo->finish_block(bloc);
7840 for_range->add_statements(statements);
7841 for_range->determine_types(gogo);
7842 gogo->add_statement(for_range);
7844 // Return retval to the caller of the hash function.
7845 Expression_list* vals = new Expression_list();
7846 ref = Expression::make_temporary_reference(retval, bloc);
7847 vals->push_back(ref);
7848 s = Statement::make_return_statement(function, vals, bloc);
7849 s->determine_types(gogo);
7850 gogo->add_statement(s);
7853 // Write the equality function for an array which can not use the
7854 // identity function.
7856 void
7857 Array_type::write_equal_function(Gogo* gogo, Named_object* function,
7858 Named_type* name)
7860 Location bloc = Linemap::predeclared_location();
7862 // The pointers to the arrays we are going to compare.
7863 Named_object* key1_arg = gogo->lookup("key1", NULL);
7864 Named_object* key2_arg = gogo->lookup("key2", NULL);
7865 go_assert(key1_arg != NULL && key2_arg != NULL);
7867 // Build temporaries for the keys with the right types.
7868 Type* pt = Type::make_pointer_type(name != NULL
7869 ? static_cast<Type*>(name)
7870 : static_cast<Type*>(this));
7872 Expression* ref = Expression::make_var_reference(key1_arg, bloc);
7873 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7874 Temporary_statement* p1 = Statement::make_temporary(pt, ref, bloc);
7875 p1->determine_types(gogo);
7876 gogo->add_statement(p1);
7878 ref = Expression::make_var_reference(key2_arg, bloc);
7879 ref = Expression::make_unsafe_cast(pt, ref, bloc);
7880 Temporary_statement* p2 = Statement::make_temporary(pt, ref, bloc);
7881 p2->determine_types(gogo);
7882 gogo->add_statement(p2);
7884 // Loop over the array elements.
7885 // for i = range a
7886 Type* int_type = Type::lookup_integer_type("int");
7887 Temporary_statement* index = Statement::make_temporary(int_type, NULL, bloc);
7888 index->determine_types(gogo);
7889 gogo->add_statement(index);
7891 Expression* iref = Expression::make_temporary_reference(index, bloc);
7892 Expression* aref = Expression::make_temporary_reference(p1, bloc);
7893 For_range_statement* for_range = Statement::make_for_range_statement(iref,
7894 NULL,
7895 aref,
7896 bloc);
7898 gogo->start_block(bloc);
7900 // Compare element in P1 and P2.
7901 Expression* e1 = Expression::make_temporary_reference(p1, bloc);
7902 e1 = Expression::make_dereference(e1, Expression::NIL_CHECK_DEFAULT, bloc);
7903 ref = Expression::make_temporary_reference(index, bloc);
7904 e1 = Expression::make_array_index(e1, ref, NULL, NULL, bloc);
7906 Expression* e2 = Expression::make_temporary_reference(p2, bloc);
7907 e2 = Expression::make_dereference(e2, Expression::NIL_CHECK_DEFAULT, bloc);
7908 ref = Expression::make_temporary_reference(index, bloc);
7909 e2 = Expression::make_array_index(e2, ref, NULL, NULL, bloc);
7911 Expression* cond = Expression::make_binary(OPERATOR_NOTEQ, e1, e2, bloc);
7913 // If the elements are not equal, return false.
7914 gogo->start_block(bloc);
7915 Expression_list* vals = new Expression_list();
7916 vals->push_back(Expression::make_boolean(false, bloc));
7917 Statement* s = Statement::make_return_statement(function, vals, bloc);
7918 s->determine_types(gogo);
7919 gogo->add_statement(s);
7920 Block* then_block = gogo->finish_block(bloc);
7922 s = Statement::make_if_statement(cond, then_block, NULL, bloc);
7923 s->determine_types(gogo);
7924 gogo->add_statement(s);
7926 Block* statements = gogo->finish_block(bloc);
7928 for_range->add_statements(statements);
7929 for_range->determine_types(gogo);
7930 gogo->add_statement(for_range);
7932 // All the elements are equal, so return true.
7933 vals = new Expression_list();
7934 vals->push_back(Expression::make_boolean(true, bloc));
7935 s = Statement::make_return_statement(function, vals, bloc);
7936 s->determine_types(gogo);
7937 gogo->add_statement(s);
7940 // Get the backend representation of the fields of a slice. This is
7941 // not declared in types.h so that types.h doesn't have to #include
7942 // backend.h.
7944 // We use int for the count and capacity fields. This matches 6g.
7945 // The language more or less assumes that we can't allocate space of a
7946 // size which does not fit in int.
7948 static void
7949 get_backend_slice_fields(Gogo* gogo, Array_type* type, bool use_placeholder,
7950 std::vector<Backend::Btyped_identifier>* bfields)
7952 bfields->resize(3);
7954 Type* pet = Type::make_pointer_type(type->element_type());
7955 Btype* pbet = (use_placeholder
7956 ? pet->get_backend_placeholder(gogo)
7957 : pet->get_backend(gogo));
7958 Location ploc = Linemap::predeclared_location();
7960 Backend::Btyped_identifier* p = &(*bfields)[0];
7961 p->name = "__values";
7962 p->btype = pbet;
7963 p->location = ploc;
7965 Type* int_type = Type::lookup_integer_type("int");
7967 p = &(*bfields)[1];
7968 p->name = "__count";
7969 p->btype = int_type->get_backend(gogo);
7970 p->location = ploc;
7972 p = &(*bfields)[2];
7973 p->name = "__capacity";
7974 p->btype = int_type->get_backend(gogo);
7975 p->location = ploc;
7978 // Get the backend representation for the type of this array. A fixed array is
7979 // simply represented as ARRAY_TYPE with the appropriate index--i.e., it is
7980 // just like an array in C. An open array is a struct with three
7981 // fields: a data pointer, the length, and the capacity.
7983 Btype*
7984 Array_type::do_get_backend(Gogo* gogo)
7986 if (this->length_ == NULL)
7988 std::vector<Backend::Btyped_identifier> bfields;
7989 get_backend_slice_fields(gogo, this, false, &bfields);
7990 return gogo->backend()->struct_type(bfields);
7992 else
7994 Btype* element = this->get_backend_element(gogo, false);
7995 Bexpression* len = this->get_backend_length(gogo);
7996 return gogo->backend()->array_type(element, len);
8000 // Return the backend representation of the element type.
8002 Btype*
8003 Array_type::get_backend_element(Gogo* gogo, bool use_placeholder)
8005 if (use_placeholder)
8006 return this->element_type_->get_backend_placeholder(gogo);
8007 else
8008 return this->element_type_->get_backend(gogo);
8011 // Return the backend representation of the length. The length may be
8012 // computed using a function call, so we must only evaluate it once.
8014 Bexpression*
8015 Array_type::get_backend_length(Gogo* gogo)
8017 go_assert(this->length_ != NULL);
8018 if (this->blength_ == NULL)
8020 if (this->length_->is_error_expression())
8022 this->blength_ = gogo->backend()->error_expression();
8023 return this->blength_;
8025 Numeric_constant nc;
8026 mpz_t val;
8027 if (this->length_->numeric_constant_value(&nc) && nc.to_int(&val))
8029 if (mpz_sgn(val) < 0)
8031 this->blength_ = gogo->backend()->error_expression();
8032 return this->blength_;
8034 Type* t = nc.type();
8035 if (t == NULL)
8036 t = Type::lookup_integer_type("int");
8037 else if (t->is_abstract())
8038 t = t->make_non_abstract_type();
8039 Btype* btype = t->get_backend(gogo);
8040 this->blength_ =
8041 gogo->backend()->integer_constant_expression(btype, val);
8042 mpz_clear(val);
8044 else
8046 // Make up a translation context for the array length
8047 // expression. FIXME: This won't work in general.
8048 Translate_context context(gogo, NULL, NULL, NULL);
8049 this->blength_ = this->length_->get_backend(&context);
8051 Btype* ibtype = Type::lookup_integer_type("int")->get_backend(gogo);
8052 this->blength_ =
8053 gogo->backend()->convert_expression(ibtype, this->blength_,
8054 this->length_->location());
8057 return this->blength_;
8060 // Finish backend representation of the array.
8062 void
8063 Array_type::finish_backend_element(Gogo* gogo)
8065 Type* et = this->array_type()->element_type();
8066 et->get_backend(gogo);
8067 if (this->is_slice_type())
8069 // This relies on the fact that we always use the same
8070 // structure for a pointer to any given type.
8071 Type* pet = Type::make_pointer_type(et);
8072 pet->get_backend(gogo);
8076 // Return an expression for a pointer to the values in ARRAY.
8078 Expression*
8079 Array_type::get_value_pointer(Gogo*, Expression* array) const
8081 if (this->length() != NULL)
8083 // Fixed array.
8084 go_assert(array->type()->array_type() != NULL);
8085 Type* etype = array->type()->array_type()->element_type();
8086 array = Expression::make_unary(OPERATOR_AND, array, array->location());
8087 return Expression::make_cast(Type::make_pointer_type(etype), array,
8088 array->location());
8091 // Slice.
8092 return Expression::make_slice_info(array,
8093 Expression::SLICE_INFO_VALUE_POINTER,
8094 array->location());
8097 // Return an expression for the length of the array ARRAY which has this
8098 // type.
8100 Expression*
8101 Array_type::get_length(Gogo*, Expression* array) const
8103 if (this->length_ != NULL)
8104 return this->length_;
8106 // This is a slice. We need to read the length field.
8107 return Expression::make_slice_info(array, Expression::SLICE_INFO_LENGTH,
8108 array->location());
8111 // Return an expression for the capacity of the array ARRAY which has this
8112 // type.
8114 Expression*
8115 Array_type::get_capacity(Gogo*, Expression* array) const
8117 if (this->length_ != NULL)
8118 return this->length_;
8120 // This is a slice. We need to read the capacity field.
8121 return Expression::make_slice_info(array, Expression::SLICE_INFO_CAPACITY,
8122 array->location());
8125 // Export.
8127 void
8128 Array_type::do_export(Export* exp) const
8130 exp->write_c_string("[");
8131 if (this->length_ != NULL)
8133 Numeric_constant nc;
8134 mpz_t val;
8135 if (!this->length_->numeric_constant_value(&nc) || !nc.to_int(&val))
8137 go_assert(saw_errors());
8138 return;
8140 char* s = mpz_get_str(NULL, 10, val);
8141 exp->write_string(s);
8142 free(s);
8143 exp->write_string(" ");
8144 mpz_clear(val);
8146 exp->write_c_string("] ");
8147 exp->write_type(this->element_type_);
8150 // Import.
8152 Array_type*
8153 Array_type::do_import(Import* imp)
8155 imp->require_c_string("[");
8156 Expression* length;
8157 if (imp->peek_char() == ']')
8158 length = NULL;
8159 else
8160 length = Expression::import_expression(imp, imp->location());
8161 imp->require_c_string("] ");
8162 Type* element_type = imp->read_type();
8163 return Type::make_array_type(element_type, length);
8166 // The type of an array type descriptor.
8168 Type*
8169 Array_type::make_array_type_descriptor_type()
8171 static Type* ret;
8172 if (ret == NULL)
8174 Type* tdt = Type::make_type_descriptor_type();
8175 Type* ptdt = Type::make_type_descriptor_ptr_type();
8177 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8179 Struct_type* sf =
8180 Type::make_builtin_struct_type(4,
8181 "", tdt,
8182 "elem", ptdt,
8183 "slice", ptdt,
8184 "len", uintptr_type);
8186 ret = Type::make_builtin_named_type("ArrayType", sf);
8189 return ret;
8192 // The type of an slice type descriptor.
8194 Type*
8195 Array_type::make_slice_type_descriptor_type()
8197 static Type* ret;
8198 if (ret == NULL)
8200 Type* tdt = Type::make_type_descriptor_type();
8201 Type* ptdt = Type::make_type_descriptor_ptr_type();
8203 Struct_type* sf =
8204 Type::make_builtin_struct_type(2,
8205 "", tdt,
8206 "elem", ptdt);
8208 ret = Type::make_builtin_named_type("SliceType", sf);
8211 return ret;
8214 // Build a type descriptor for an array/slice type.
8216 Expression*
8217 Array_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8219 if (this->length_ != NULL)
8220 return this->array_type_descriptor(gogo, name);
8221 else
8222 return this->slice_type_descriptor(gogo, name);
8225 // Build a type descriptor for an array type.
8227 Expression*
8228 Array_type::array_type_descriptor(Gogo* gogo, Named_type* name)
8230 Location bloc = Linemap::predeclared_location();
8232 Type* atdt = Array_type::make_array_type_descriptor_type();
8234 const Struct_field_list* fields = atdt->struct_type()->fields();
8236 Expression_list* vals = new Expression_list();
8237 vals->reserve(3);
8239 Struct_field_list::const_iterator p = fields->begin();
8240 go_assert(p->is_field_name("_type"));
8241 vals->push_back(this->type_descriptor_constructor(gogo,
8242 RUNTIME_TYPE_KIND_ARRAY,
8243 name, NULL, true));
8245 ++p;
8246 go_assert(p->is_field_name("elem"));
8247 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8249 ++p;
8250 go_assert(p->is_field_name("slice"));
8251 Type* slice_type = Type::make_array_type(this->element_type_, NULL);
8252 vals->push_back(Expression::make_type_descriptor(slice_type, bloc));
8254 ++p;
8255 go_assert(p->is_field_name("len"));
8256 vals->push_back(Expression::make_cast(p->type(), this->length_, bloc));
8258 ++p;
8259 go_assert(p == fields->end());
8261 return Expression::make_struct_composite_literal(atdt, vals, bloc);
8264 // Build a type descriptor for a slice type.
8266 Expression*
8267 Array_type::slice_type_descriptor(Gogo* gogo, Named_type* name)
8269 Location bloc = Linemap::predeclared_location();
8271 Type* stdt = Array_type::make_slice_type_descriptor_type();
8273 const Struct_field_list* fields = stdt->struct_type()->fields();
8275 Expression_list* vals = new Expression_list();
8276 vals->reserve(2);
8278 Struct_field_list::const_iterator p = fields->begin();
8279 go_assert(p->is_field_name("_type"));
8280 vals->push_back(this->type_descriptor_constructor(gogo,
8281 RUNTIME_TYPE_KIND_SLICE,
8282 name, NULL, true));
8284 ++p;
8285 go_assert(p->is_field_name("elem"));
8286 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
8288 ++p;
8289 go_assert(p == fields->end());
8291 return Expression::make_struct_composite_literal(stdt, vals, bloc);
8294 // Reflection string.
8296 void
8297 Array_type::do_reflection(Gogo* gogo, std::string* ret) const
8299 ret->push_back('[');
8300 if (this->length_ != NULL)
8302 Numeric_constant nc;
8303 if (!this->length_->numeric_constant_value(&nc))
8305 go_assert(saw_errors());
8306 return;
8308 mpz_t val;
8309 if (!nc.to_int(&val))
8311 go_assert(saw_errors());
8312 return;
8314 char* s = mpz_get_str(NULL, 10, val);
8315 ret->append(s);
8316 free(s);
8317 mpz_clear(val);
8319 ret->push_back(']');
8321 this->append_reflection(this->element_type_, gogo, ret);
8324 // Make an array type.
8326 Array_type*
8327 Type::make_array_type(Type* element_type, Expression* length)
8329 return new Array_type(element_type, length);
8332 // Class Map_type.
8334 Named_object* Map_type::zero_value;
8335 int64_t Map_type::zero_value_size;
8336 int64_t Map_type::zero_value_align;
8338 // If this map requires the "fat" functions, return the pointer to
8339 // pass as the zero value to those functions. Otherwise, in the
8340 // normal case, return NULL. The map requires the "fat" functions if
8341 // the value size is larger than max_zero_size bytes. max_zero_size
8342 // must match maxZero in libgo/go/runtime/map.go.
8344 Expression*
8345 Map_type::fat_zero_value(Gogo* gogo)
8347 int64_t valsize;
8348 if (!this->val_type_->backend_type_size(gogo, &valsize))
8350 go_assert(saw_errors());
8351 return NULL;
8353 if (valsize <= Map_type::max_zero_size)
8354 return NULL;
8356 if (Map_type::zero_value_size < valsize)
8357 Map_type::zero_value_size = valsize;
8359 int64_t valalign;
8360 if (!this->val_type_->backend_type_align(gogo, &valalign))
8362 go_assert(saw_errors());
8363 return NULL;
8366 if (Map_type::zero_value_align < valalign)
8367 Map_type::zero_value_align = valalign;
8369 Location bloc = Linemap::predeclared_location();
8371 if (Map_type::zero_value == NULL)
8373 // The final type will be set in backend_zero_value.
8374 Type* uint8_type = Type::lookup_integer_type("uint8");
8375 Expression* size = Expression::make_integer_ul(0, NULL, bloc);
8376 Array_type* array_type = Type::make_array_type(uint8_type, size);
8377 array_type->set_is_array_incomparable();
8378 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
8379 std::string name = gogo->map_zero_value_name();
8380 Map_type::zero_value = Named_object::make_variable(name, NULL, var);
8383 Expression* z = Expression::make_var_reference(Map_type::zero_value, bloc);
8384 z = Expression::make_unary(OPERATOR_AND, z, bloc);
8385 Type* unsafe_ptr_type = Type::make_pointer_type(Type::make_void_type());
8386 z = Expression::make_cast(unsafe_ptr_type, z, bloc);
8387 return z;
8390 // Map algorithm to use for this map type.
8392 Map_type::Map_alg
8393 Map_type::algorithm(Gogo* gogo)
8395 int64_t size;
8396 bool ok = this->val_type_->backend_type_size(gogo, &size);
8397 if (!ok || size > Map_type::max_val_size)
8398 return MAP_ALG_SLOW;
8400 Type* key_type = this->key_type_;
8401 if (key_type->is_string_type())
8402 return MAP_ALG_FASTSTR;
8403 if (!key_type->compare_is_identity(gogo))
8404 return MAP_ALG_SLOW;
8406 ok = key_type->backend_type_size(gogo, &size);
8407 if (!ok)
8408 return MAP_ALG_SLOW;
8409 if (size == 4)
8410 return (key_type->has_pointer()
8411 ? MAP_ALG_FAST32PTR
8412 : MAP_ALG_FAST32);
8413 if (size == 8)
8415 if (!key_type->has_pointer())
8416 return MAP_ALG_FAST64;
8417 Type* ptr_type = Type::make_pointer_type(Type::make_void_type());
8418 ok = ptr_type->backend_type_size(gogo, &size);
8419 if (ok && size == 8)
8420 return MAP_ALG_FAST64PTR;
8421 // Key contains pointer but is not a single pointer.
8422 // Use slow version.
8424 return MAP_ALG_SLOW;
8427 // Return whether VAR is the map zero value.
8429 bool
8430 Map_type::is_zero_value(Variable* var)
8432 return (Map_type::zero_value != NULL
8433 && Map_type::zero_value->var_value() == var);
8436 // Return the backend representation for the zero value.
8438 Bvariable*
8439 Map_type::backend_zero_value(Gogo* gogo)
8441 Location bloc = Linemap::predeclared_location();
8443 go_assert(Map_type::zero_value != NULL);
8445 Type* uint8_type = Type::lookup_integer_type("uint8");
8446 Btype* buint8_type = uint8_type->get_backend(gogo);
8448 Type* int_type = Type::lookup_integer_type("int");
8450 Expression* e = Expression::make_integer_int64(Map_type::zero_value_size,
8451 int_type, bloc);
8452 Translate_context context(gogo, NULL, NULL, NULL);
8453 Bexpression* blength = e->get_backend(&context);
8455 Btype* barray_type = gogo->backend()->array_type(buint8_type, blength);
8457 std::string zname = Map_type::zero_value->name();
8458 unsigned int flags = Backend::variable_is_common;
8459 Bvariable* zvar =
8460 gogo->backend()->implicit_variable(zname, "", barray_type, flags,
8461 Map_type::zero_value_align);
8462 gogo->backend()->implicit_variable_set_init(zvar, zname, barray_type,
8463 flags, NULL);
8464 return zvar;
8467 // Message name.
8469 void
8470 Map_type::do_message_name(std::string* ret) const
8472 ret->append("map[");
8473 this->append_message_name(this->key_type_, ret);
8474 ret->push_back(']');
8475 this->append_message_name(this->val_type_, ret);
8478 // Traversal.
8481 Map_type::do_traverse(Traverse* traverse)
8483 if (Type::traverse(this->key_type_, traverse) == TRAVERSE_EXIT
8484 || Type::traverse(this->val_type_, traverse) == TRAVERSE_EXIT)
8485 return TRAVERSE_EXIT;
8486 return TRAVERSE_CONTINUE;
8489 // Check that the map type is OK.
8491 bool
8492 Map_type::do_verify(Gogo*)
8494 // The runtime support uses "map[void]void".
8495 if (!this->key_type_->is_comparable() && !this->key_type_->is_void_type())
8497 go_error_at(this->location_, "invalid map key type");
8498 this->set_is_error();
8500 if (!this->key_type_->in_heap())
8502 go_error_at(this->location_, "go:notinheap map key not allowed");
8503 this->set_is_error();
8505 if (!this->val_type_->in_heap())
8507 go_error_at(this->location_, "go:notinheap map value not allowed");
8508 this->set_is_error();
8510 return true;
8513 // Whether two map types are identical.
8515 bool
8516 Map_type::is_identical(const Map_type* t, int flags) const
8518 return (Type::are_identical(this->key_type(), t->key_type(), flags, NULL)
8519 && Type::are_identical(this->val_type(), t->val_type(), flags,
8520 NULL));
8523 // Hash code.
8525 unsigned int
8526 Map_type::do_hash_for_method(Gogo* gogo, int flags) const
8528 return (this->key_type_->hash_for_method(gogo, flags)
8529 + this->val_type_->hash_for_method(gogo, flags)
8530 + 2);
8533 // Get the backend representation for a map type. A map type is
8534 // represented as a pointer to a struct. The struct is hmap in
8535 // runtime/map.go.
8537 Btype*
8538 Map_type::do_get_backend(Gogo* gogo)
8540 static Btype* backend_map_type;
8541 if (backend_map_type == NULL)
8543 std::vector<Backend::Btyped_identifier> bfields(9);
8545 Location bloc = Linemap::predeclared_location();
8547 Type* int_type = Type::lookup_integer_type("int");
8548 bfields[0].name = "count";
8549 bfields[0].btype = int_type->get_backend(gogo);
8550 bfields[0].location = bloc;
8552 Type* uint8_type = Type::lookup_integer_type("uint8");
8553 bfields[1].name = "flags";
8554 bfields[1].btype = uint8_type->get_backend(gogo);
8555 bfields[1].location = bloc;
8557 bfields[2].name = "B";
8558 bfields[2].btype = bfields[1].btype;
8559 bfields[2].location = bloc;
8561 Type* uint16_type = Type::lookup_integer_type("uint16");
8562 bfields[3].name = "noverflow";
8563 bfields[3].btype = uint16_type->get_backend(gogo);
8564 bfields[3].location = bloc;
8566 Type* uint32_type = Type::lookup_integer_type("uint32");
8567 bfields[4].name = "hash0";
8568 bfields[4].btype = uint32_type->get_backend(gogo);
8569 bfields[4].location = bloc;
8571 Btype* bvt = gogo->backend()->void_type();
8572 Btype* bpvt = gogo->backend()->pointer_type(bvt);
8573 bfields[5].name = "buckets";
8574 bfields[5].btype = bpvt;
8575 bfields[5].location = bloc;
8577 bfields[6].name = "oldbuckets";
8578 bfields[6].btype = bpvt;
8579 bfields[6].location = bloc;
8581 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8582 bfields[7].name = "nevacuate";
8583 bfields[7].btype = uintptr_type->get_backend(gogo);
8584 bfields[7].location = bloc;
8586 bfields[8].name = "extra";
8587 bfields[8].btype = bpvt;
8588 bfields[8].location = bloc;
8590 Btype *bt = gogo->backend()->struct_type(bfields);
8591 bt = gogo->backend()->named_type("runtime.hmap", bt, bloc);
8592 backend_map_type = gogo->backend()->pointer_type(bt);
8594 return backend_map_type;
8597 // The type of a map type descriptor.
8599 Type*
8600 Map_type::make_map_type_descriptor_type()
8602 static Type* ret;
8603 if (ret == NULL)
8605 Type* tdt = Type::make_type_descriptor_type();
8606 Type* ptdt = Type::make_type_descriptor_ptr_type();
8607 Type* uint8_type = Type::lookup_integer_type("uint8");
8608 Type* uint16_type = Type::lookup_integer_type("uint16");
8609 Type* uint32_type = Type::lookup_integer_type("uint32");
8610 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8611 Type* void_type = Type::make_void_type();
8612 Type* unsafe_pointer_type = Type::make_pointer_type(void_type);
8614 Location bloc = Linemap::predeclared_location();
8615 Typed_identifier_list *params = new Typed_identifier_list();
8616 params->push_back(Typed_identifier("key", unsafe_pointer_type, bloc));
8617 params->push_back(Typed_identifier("seed", uintptr_type, bloc));
8619 Typed_identifier_list* results = new Typed_identifier_list();
8620 results->push_back(Typed_identifier("", uintptr_type, bloc));
8622 Type* hasher_fntype = Type::make_function_type(NULL, params, results,
8623 bloc);
8625 Struct_type* sf =
8626 Type::make_builtin_struct_type(9,
8627 "", tdt,
8628 "key", ptdt,
8629 "elem", ptdt,
8630 "bucket", ptdt,
8631 "hasher", hasher_fntype,
8632 "keysize", uint8_type,
8633 "valuesize", uint8_type,
8634 "bucketsize", uint16_type,
8635 "flags", uint32_type);
8637 ret = Type::make_builtin_named_type("MapType", sf);
8640 return ret;
8643 // Build a type descriptor for a map type.
8645 Expression*
8646 Map_type::do_type_descriptor(Gogo* gogo, Named_type* name)
8648 Location bloc = Linemap::predeclared_location();
8650 Type* mtdt = Map_type::make_map_type_descriptor_type();
8651 Type* uint8_type = Type::lookup_integer_type("uint8");
8652 Type* uint16_type = Type::lookup_integer_type("uint16");
8653 Type* uint32_type = Type::lookup_integer_type("uint32");
8655 int64_t keysize;
8656 if (!this->key_type_->backend_type_size(gogo, &keysize))
8658 go_error_at(this->location_, "error determining map key type size");
8659 return Expression::make_error(this->location_);
8662 int64_t valsize;
8663 if (!this->val_type_->backend_type_size(gogo, &valsize))
8665 go_error_at(this->location_, "error determining map value type size");
8666 return Expression::make_error(this->location_);
8669 int64_t ptrsize;
8670 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptrsize))
8672 go_assert(saw_errors());
8673 return Expression::make_error(this->location_);
8676 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8677 if (bucket_type == NULL)
8679 go_assert(saw_errors());
8680 return Expression::make_error(this->location_);
8683 int64_t bucketsize;
8684 if (!bucket_type->backend_type_size(gogo, &bucketsize))
8686 go_assert(saw_errors());
8687 return Expression::make_error(this->location_);
8690 const Struct_field_list* fields = mtdt->struct_type()->fields();
8692 Expression_list* vals = new Expression_list();
8693 vals->reserve(12);
8695 Struct_field_list::const_iterator p = fields->begin();
8696 go_assert(p->is_field_name("_type"));
8697 vals->push_back(this->type_descriptor_constructor(gogo,
8698 RUNTIME_TYPE_KIND_MAP,
8699 name, NULL, true));
8701 ++p;
8702 go_assert(p->is_field_name("key"));
8703 vals->push_back(Expression::make_type_descriptor(this->key_type_, bloc));
8705 ++p;
8706 go_assert(p->is_field_name("elem"));
8707 vals->push_back(Expression::make_type_descriptor(this->val_type_, bloc));
8709 ++p;
8710 go_assert(p->is_field_name("bucket"));
8711 vals->push_back(Expression::make_type_descriptor(bucket_type, bloc));
8713 ++p;
8714 go_assert(p->is_field_name("hasher"));
8715 Function_type* hasher_fntype = p->type()->function_type();
8716 Named_object* hasher_fn =
8717 this->key_type_->unalias()->hash_function(gogo, hasher_fntype);
8718 if (hasher_fn == NULL)
8719 vals->push_back(Expression::make_cast(hasher_fntype,
8720 Expression::make_nil(bloc),
8721 bloc));
8722 else
8723 vals->push_back(Expression::make_func_reference(hasher_fn, NULL, bloc));
8725 ++p;
8726 go_assert(p->is_field_name("keysize"));
8727 if (keysize > Map_type::max_key_size)
8728 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8729 else
8730 vals->push_back(Expression::make_integer_int64(keysize, uint8_type, bloc));
8732 ++p;
8733 go_assert(p->is_field_name("valuesize"));
8734 if (valsize > Map_type::max_val_size)
8735 vals->push_back(Expression::make_integer_int64(ptrsize, uint8_type, bloc));
8736 else
8737 vals->push_back(Expression::make_integer_int64(valsize, uint8_type, bloc));
8739 ++p;
8740 go_assert(p->is_field_name("bucketsize"));
8741 vals->push_back(Expression::make_integer_int64(bucketsize, uint16_type,
8742 bloc));
8744 ++p;
8745 go_assert(p->is_field_name("flags"));
8746 // As with the other fields, the flag bits must match the reflect
8747 // and runtime packages.
8748 unsigned long flags = 0;
8749 if (keysize > Map_type::max_key_size)
8750 flags |= 1;
8751 if (valsize > Map_type::max_val_size)
8752 flags |= 2;
8753 if (this->key_type_->is_reflexive())
8754 flags |= 4;
8755 if (this->key_type_->needs_key_update())
8756 flags |= 8;
8757 if (this->key_type_->hash_might_panic())
8758 flags |= 16;
8759 vals->push_back(Expression::make_integer_ul(flags, uint32_type, bloc));
8761 ++p;
8762 go_assert(p == fields->end());
8764 return Expression::make_struct_composite_literal(mtdt, vals, bloc);
8767 // Return the bucket type to use for a map type. This must correspond
8768 // to libgo/go/runtime/map.go.
8770 Type*
8771 Map_type::bucket_type(Gogo* gogo, int64_t keysize, int64_t valsize)
8773 if (this->bucket_type_ != NULL)
8774 return this->bucket_type_;
8776 Type* key_type = this->key_type_;
8777 if (keysize > Map_type::max_key_size)
8778 key_type = Type::make_pointer_type(key_type);
8780 Type* val_type = this->val_type_;
8781 if (valsize > Map_type::max_val_size)
8782 val_type = Type::make_pointer_type(val_type);
8784 Expression* bucket_size = Expression::make_integer_ul(Map_type::bucket_size,
8785 NULL, this->location_);
8787 Type* uint8_type = Type::lookup_integer_type("uint8");
8788 Array_type* topbits_type = Type::make_array_type(uint8_type, bucket_size);
8789 topbits_type->set_is_array_incomparable();
8790 Array_type* keys_type = Type::make_array_type(key_type, bucket_size);
8791 keys_type->set_is_array_incomparable();
8792 Array_type* values_type = Type::make_array_type(val_type, bucket_size);
8793 values_type->set_is_array_incomparable();
8795 // If keys and values have no pointers, the map implementation can
8796 // keep a list of overflow pointers on the side so that buckets can
8797 // be marked as having no pointers. Arrange for the bucket to have
8798 // no pointers by changing the type of the overflow field to uintptr
8799 // in this case. See comment on the hmap.overflow field in
8800 // libgo/go/runtime/map.go.
8801 Type* overflow_type;
8802 if (!key_type->has_pointer() && !val_type->has_pointer())
8803 overflow_type = Type::lookup_integer_type("uintptr");
8804 else
8806 // This should really be a pointer to the bucket type itself,
8807 // but that would require us to construct a Named_type for it to
8808 // give it a way to refer to itself. Since nothing really cares
8809 // (except perhaps for someone using a debugger) just use an
8810 // unsafe pointer.
8811 overflow_type = Type::make_pointer_type(Type::make_void_type());
8814 // Make sure the overflow pointer is the last memory in the struct,
8815 // because the runtime assumes it can use size-ptrSize as the offset
8816 // of the overflow pointer. We double-check that property below
8817 // once the offsets and size are computed.
8819 int64_t topbits_field_size, topbits_field_align;
8820 int64_t keys_field_size, keys_field_align;
8821 int64_t values_field_size, values_field_align;
8822 int64_t overflow_field_size, overflow_field_align;
8823 if (!topbits_type->backend_type_size(gogo, &topbits_field_size)
8824 || !topbits_type->backend_type_field_align(gogo, &topbits_field_align)
8825 || !keys_type->backend_type_size(gogo, &keys_field_size)
8826 || !keys_type->backend_type_field_align(gogo, &keys_field_align)
8827 || !values_type->backend_type_size(gogo, &values_field_size)
8828 || !values_type->backend_type_field_align(gogo, &values_field_align)
8829 || !overflow_type->backend_type_size(gogo, &overflow_field_size)
8830 || !overflow_type->backend_type_field_align(gogo, &overflow_field_align))
8832 go_assert(saw_errors());
8833 return NULL;
8836 Struct_type* ret;
8837 int64_t max_align = std::max(std::max(topbits_field_align, keys_field_align),
8838 values_field_align);
8839 if (max_align <= overflow_field_align)
8840 ret = make_builtin_struct_type(4,
8841 "topbits", topbits_type,
8842 "keys", keys_type,
8843 "values", values_type,
8844 "overflow", overflow_type);
8845 else
8847 size_t off = topbits_field_size;
8848 off = ((off + keys_field_align - 1)
8849 &~ static_cast<size_t>(keys_field_align - 1));
8850 off += keys_field_size;
8851 off = ((off + values_field_align - 1)
8852 &~ static_cast<size_t>(values_field_align - 1));
8853 off += values_field_size;
8855 int64_t padded_overflow_field_size =
8856 ((overflow_field_size + max_align - 1)
8857 &~ static_cast<size_t>(max_align - 1));
8859 size_t ovoff = off;
8860 ovoff = ((ovoff + max_align - 1)
8861 &~ static_cast<size_t>(max_align - 1));
8862 size_t pad = (ovoff - off
8863 + padded_overflow_field_size - overflow_field_size);
8865 Expression* pad_expr = Expression::make_integer_ul(pad, NULL,
8866 this->location_);
8867 Array_type* pad_type = Type::make_array_type(uint8_type, pad_expr);
8868 pad_type->set_is_array_incomparable();
8870 ret = make_builtin_struct_type(5,
8871 "topbits", topbits_type,
8872 "keys", keys_type,
8873 "values", values_type,
8874 "pad", pad_type,
8875 "overflow", overflow_type);
8878 // Verify that the overflow field is just before the end of the
8879 // bucket type.
8881 Btype* btype = ret->get_backend(gogo);
8882 int64_t offset = gogo->backend()->type_field_offset(btype,
8883 ret->field_count() - 1);
8884 int64_t size;
8885 if (!ret->backend_type_size(gogo, &size))
8887 go_assert(saw_errors());
8888 return NULL;
8891 int64_t ptr_size;
8892 if (!Type::make_pointer_type(uint8_type)->backend_type_size(gogo, &ptr_size))
8894 go_assert(saw_errors());
8895 return NULL;
8898 go_assert(offset + ptr_size == size);
8900 ret->set_is_struct_incomparable();
8902 this->bucket_type_ = ret;
8903 return ret;
8906 // Return the hashmap type for a map type.
8908 Type*
8909 Map_type::hmap_type(Type* bucket_type)
8911 if (this->hmap_type_ != NULL)
8912 return this->hmap_type_;
8914 Type* int_type = Type::lookup_integer_type("int");
8915 Type* uint8_type = Type::lookup_integer_type("uint8");
8916 Type* uint16_type = Type::lookup_integer_type("uint16");
8917 Type* uint32_type = Type::lookup_integer_type("uint32");
8918 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8919 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8921 Type* ptr_bucket_type = Type::make_pointer_type(bucket_type);
8923 Struct_type* ret = make_builtin_struct_type(9,
8924 "count", int_type,
8925 "flags", uint8_type,
8926 "B", uint8_type,
8927 "noverflow", uint16_type,
8928 "hash0", uint32_type,
8929 "buckets", ptr_bucket_type,
8930 "oldbuckets", ptr_bucket_type,
8931 "nevacuate", uintptr_type,
8932 "extra", void_ptr_type);
8933 ret->set_is_struct_incomparable();
8934 this->hmap_type_ = ret;
8935 return ret;
8938 // Return the iterator type for a map type. This is the type of the
8939 // value used when doing a range over a map.
8941 Type*
8942 Map_type::hiter_type(Gogo* gogo)
8944 if (this->hiter_type_ != NULL)
8945 return this->hiter_type_;
8947 int64_t keysize, valsize;
8948 if (!this->key_type_->backend_type_size(gogo, &keysize)
8949 || !this->val_type_->backend_type_size(gogo, &valsize))
8951 go_assert(saw_errors());
8952 return NULL;
8955 Type* key_ptr_type = Type::make_pointer_type(this->key_type_);
8956 Type* val_ptr_type = Type::make_pointer_type(this->val_type_);
8957 Type* uint8_type = Type::lookup_integer_type("uint8");
8958 Type* uint8_ptr_type = Type::make_pointer_type(uint8_type);
8959 Type* uintptr_type = Type::lookup_integer_type("uintptr");
8960 Type* bucket_type = this->bucket_type(gogo, keysize, valsize);
8961 Type* bucket_ptr_type = Type::make_pointer_type(bucket_type);
8962 Type* hmap_type = this->hmap_type(bucket_type);
8963 Type* hmap_ptr_type = Type::make_pointer_type(hmap_type);
8964 Type* void_ptr_type = Type::make_pointer_type(Type::make_void_type());
8965 Type* bool_type = Type::lookup_bool_type();
8967 Struct_type* ret = make_builtin_struct_type(15,
8968 "key", key_ptr_type,
8969 "val", val_ptr_type,
8970 "t", uint8_ptr_type,
8971 "h", hmap_ptr_type,
8972 "buckets", bucket_ptr_type,
8973 "bptr", bucket_ptr_type,
8974 "overflow", void_ptr_type,
8975 "oldoverflow", void_ptr_type,
8976 "startBucket", uintptr_type,
8977 "offset", uint8_type,
8978 "wrapped", bool_type,
8979 "B", uint8_type,
8980 "i", uint8_type,
8981 "bucket", uintptr_type,
8982 "checkBucket", uintptr_type);
8983 ret->set_is_struct_incomparable();
8984 this->hiter_type_ = ret;
8985 return ret;
8988 // Reflection string for a map.
8990 void
8991 Map_type::do_reflection(Gogo* gogo, std::string* ret) const
8993 ret->append("map[");
8994 this->append_reflection(this->key_type_, gogo, ret);
8995 ret->append("]");
8996 this->append_reflection(this->val_type_, gogo, ret);
8999 // Export a map type.
9001 void
9002 Map_type::do_export(Export* exp) const
9004 exp->write_c_string("map [");
9005 exp->write_type(this->key_type_);
9006 exp->write_c_string("] ");
9007 exp->write_type(this->val_type_);
9010 // Import a map type.
9012 Map_type*
9013 Map_type::do_import(Import* imp)
9015 imp->require_c_string("map [");
9016 Type* key_type = imp->read_type();
9017 imp->require_c_string("] ");
9018 Type* val_type = imp->read_type();
9019 return Type::make_map_type(key_type, val_type, imp->location());
9022 // Make a map type.
9024 Map_type*
9025 Type::make_map_type(Type* key_type, Type* val_type, Location location)
9027 return new Map_type(key_type, val_type, location);
9030 // Class Channel_type.
9032 // Message name.
9034 void
9035 Channel_type::do_message_name(std::string* ret) const
9037 if (!this->may_send_)
9038 ret->append("<-");
9039 ret->append("chan");
9040 if (!this->may_receive_)
9041 ret->append("<-");
9042 ret->push_back(' ');
9043 this->append_message_name(this->element_type_, ret);
9046 // Verify.
9048 bool
9049 Channel_type::do_verify(Gogo*)
9051 // We have no location for this error, but this is not something the
9052 // ordinary user will see.
9053 if (!this->element_type_->in_heap())
9055 go_error_at(Linemap::unknown_location(),
9056 "chan of go:notinheap type not allowed");
9057 this->set_is_error();
9059 return true;
9062 // Hash code.
9064 unsigned int
9065 Channel_type::do_hash_for_method(Gogo* gogo, int flags) const
9067 unsigned int ret = 0;
9068 if (this->may_send_)
9069 ret += 1;
9070 if (this->may_receive_)
9071 ret += 2;
9072 if (this->element_type_ != NULL)
9073 ret += this->element_type_->hash_for_method(gogo, flags) << 2;
9074 return ret << 3;
9077 // Whether this type is the same as T.
9079 bool
9080 Channel_type::is_identical(const Channel_type* t, int flags) const
9082 if (!Type::are_identical(this->element_type(), t->element_type(), flags,
9083 NULL))
9084 return false;
9085 return (this->may_send_ == t->may_send_
9086 && this->may_receive_ == t->may_receive_);
9089 // Return the backend representation for a channel type. A channel is a pointer
9090 // to a __go_channel struct. The __go_channel struct is defined in
9091 // libgo/runtime/channel.h.
9093 Btype*
9094 Channel_type::do_get_backend(Gogo* gogo)
9096 static Btype* backend_channel_type;
9097 if (backend_channel_type == NULL)
9099 std::vector<Backend::Btyped_identifier> bfields;
9100 Btype* bt = gogo->backend()->struct_type(bfields);
9101 bt = gogo->backend()->named_type("__go_channel", bt,
9102 Linemap::predeclared_location());
9103 backend_channel_type = gogo->backend()->pointer_type(bt);
9105 return backend_channel_type;
9108 // Build a type descriptor for a channel type.
9110 Type*
9111 Channel_type::make_chan_type_descriptor_type()
9113 static Type* ret;
9114 if (ret == NULL)
9116 Type* tdt = Type::make_type_descriptor_type();
9117 Type* ptdt = Type::make_type_descriptor_ptr_type();
9119 Type* uintptr_type = Type::lookup_integer_type("uintptr");
9121 Struct_type* sf =
9122 Type::make_builtin_struct_type(3,
9123 "", tdt,
9124 "elem", ptdt,
9125 "dir", uintptr_type);
9127 ret = Type::make_builtin_named_type("ChanType", sf);
9130 return ret;
9133 // Build a type descriptor for a map type.
9135 Expression*
9136 Channel_type::do_type_descriptor(Gogo* gogo, Named_type* name)
9138 Location bloc = Linemap::predeclared_location();
9140 Type* ctdt = Channel_type::make_chan_type_descriptor_type();
9142 const Struct_field_list* fields = ctdt->struct_type()->fields();
9144 Expression_list* vals = new Expression_list();
9145 vals->reserve(3);
9147 Struct_field_list::const_iterator p = fields->begin();
9148 go_assert(p->is_field_name("_type"));
9149 vals->push_back(this->type_descriptor_constructor(gogo,
9150 RUNTIME_TYPE_KIND_CHAN,
9151 name, NULL, true));
9153 ++p;
9154 go_assert(p->is_field_name("elem"));
9155 vals->push_back(Expression::make_type_descriptor(this->element_type_, bloc));
9157 ++p;
9158 go_assert(p->is_field_name("dir"));
9159 // These bits must match the ones in libgo/runtime/go-type.h.
9160 int val = 0;
9161 if (this->may_receive_)
9162 val |= 1;
9163 if (this->may_send_)
9164 val |= 2;
9165 vals->push_back(Expression::make_integer_ul(val, p->type(), bloc));
9167 ++p;
9168 go_assert(p == fields->end());
9170 return Expression::make_struct_composite_literal(ctdt, vals, bloc);
9173 // Reflection string.
9175 void
9176 Channel_type::do_reflection(Gogo* gogo, std::string* ret) const
9178 if (!this->may_send_)
9179 ret->append("<-");
9180 ret->append("chan");
9181 if (!this->may_receive_)
9182 ret->append("<-");
9183 ret->push_back(' ');
9185 bool need_paren = false;
9186 if (this->may_send_
9187 && this->may_receive_
9188 && this->element_type_->channel_type() != NULL
9189 && this->element_type_->unalias()->named_type() == NULL
9190 && !this->element_type_->channel_type()->may_send())
9192 ret->push_back('(');
9193 need_paren = true;
9196 this->append_reflection(this->element_type_, gogo, ret);
9198 if (need_paren)
9199 ret->push_back(')');
9202 // Export.
9204 void
9205 Channel_type::do_export(Export* exp) const
9207 exp->write_c_string("chan ");
9208 if (this->may_send_ && !this->may_receive_)
9209 exp->write_c_string("-< ");
9210 else if (this->may_receive_ && !this->may_send_)
9211 exp->write_c_string("<- ");
9212 exp->write_type(this->element_type_);
9215 // Import.
9217 Channel_type*
9218 Channel_type::do_import(Import* imp)
9220 imp->require_c_string("chan ");
9222 bool may_send;
9223 bool may_receive;
9224 if (imp->match_c_string("-< "))
9226 imp->advance(3);
9227 may_send = true;
9228 may_receive = false;
9230 else if (imp->match_c_string("<- "))
9232 imp->advance(3);
9233 may_receive = true;
9234 may_send = false;
9236 else
9238 may_send = true;
9239 may_receive = true;
9242 Type* element_type = imp->read_type();
9244 return Type::make_channel_type(may_send, may_receive, element_type);
9247 // Return the type that the runtime package uses for one case of a
9248 // select statement. An array of values of this type is allocated on
9249 // the stack. This must match scase in libgo/go/runtime/select.go.
9251 Type*
9252 Channel_type::select_case_type()
9254 static Struct_type* scase_type;
9255 if (scase_type == NULL)
9257 Type* unsafe_pointer_type =
9258 Type::make_pointer_type(Type::make_void_type());
9259 scase_type =
9260 Type::make_builtin_struct_type(2,
9261 "c", unsafe_pointer_type,
9262 "elem", unsafe_pointer_type);
9263 scase_type->set_is_struct_incomparable();
9265 return scase_type;
9268 // Make a new channel type.
9270 Channel_type*
9271 Type::make_channel_type(bool send, bool receive, Type* element_type)
9273 return new Channel_type(send, receive, element_type);
9276 // Class Interface_type.
9278 // Return the list of methods.
9280 const Typed_identifier_list*
9281 Interface_type::methods() const
9283 go_assert(this->methods_are_finalized_ || saw_errors());
9284 return this->all_methods_;
9287 // Return the number of methods.
9289 size_t
9290 Interface_type::method_count() const
9292 go_assert(this->methods_are_finalized_ || saw_errors());
9293 return this->all_methods_ == NULL ? 0 : this->all_methods_->size();
9296 // Message name.
9298 void
9299 Interface_type::do_message_name(std::string* ret) const
9301 const Typed_identifier_list* methods = (this->methods_are_finalized_
9302 ? this->all_methods_
9303 : this->parse_methods_);
9304 if (methods == NULL || methods->empty())
9306 ret->append("interface{}");
9307 return;
9310 ret->append("interface {");
9312 bool first = true;
9313 for (Typed_identifier_list::const_iterator p = methods->begin();
9314 p != methods->end();
9315 ++p)
9317 if (first)
9318 first = false;
9319 else
9320 ret->append("; ");
9322 if (!p->name().empty())
9323 ret->append(p->name());
9325 Function_type* ft = p->type()->function_type();
9326 if (ft == NULL)
9327 this->append_message_name(p->type(), ret);
9328 else
9329 ft->append_signature(ret);
9332 ret->append(" }");
9335 // Traversal.
9338 Interface_type::do_traverse(Traverse* traverse)
9340 Typed_identifier_list* methods = (this->methods_are_finalized_
9341 ? this->all_methods_
9342 : this->parse_methods_);
9343 if (methods == NULL)
9344 return TRAVERSE_CONTINUE;
9345 return methods->traverse(traverse);
9348 // Finalize the methods. This handles interface inheritance.
9350 void
9351 Interface_type::finalize_methods()
9353 if (this->methods_are_finalized_)
9354 return;
9355 this->methods_are_finalized_ = true;
9356 if (this->parse_methods_ == NULL)
9357 return;
9359 // The exporter uses parse_methods_.
9360 this->parse_methods_->sort_by_name();
9362 this->all_methods_ = new Typed_identifier_list();
9363 this->all_methods_->reserve(this->parse_methods_->size());
9364 Typed_identifier_list inherit;
9365 for (Typed_identifier_list::const_iterator pm =
9366 this->parse_methods_->begin();
9367 pm != this->parse_methods_->end();
9368 ++pm)
9370 const Typed_identifier* p = &*pm;
9371 if (p->name().empty())
9372 inherit.push_back(*p);
9373 else if (this->find_method(p->name()) == NULL)
9374 this->all_methods_->push_back(*p);
9375 else
9377 go_error_at(p->location(), "duplicate method %qs",
9378 Gogo::message_name(p->name()).c_str());
9379 this->set_is_error();
9383 std::vector<Named_type*> seen;
9384 seen.reserve(inherit.size());
9385 bool issued_recursive_error = false;
9386 while (!inherit.empty())
9388 Type* t = inherit.back().type();
9389 Location tl = inherit.back().location();
9390 inherit.pop_back();
9392 Interface_type* it = t->interface_type();
9393 if (it == NULL)
9395 if (!t->is_error())
9397 go_error_at(tl, "interface contains embedded non-interface");
9398 this->set_is_error();
9400 continue;
9402 if (it == this)
9404 if (!issued_recursive_error)
9406 go_error_at(tl, "invalid recursive interface");
9407 this->set_is_error();
9408 issued_recursive_error = true;
9410 continue;
9413 const Typed_identifier_list* imethods = it->parse_methods_;
9414 if (imethods == NULL)
9415 continue;
9417 Named_type* nt = t->named_type();
9418 if (nt != NULL)
9420 std::vector<Named_type*>::const_iterator q;
9421 for (q = seen.begin(); q != seen.end(); ++q)
9423 if (*q == nt)
9425 go_error_at(tl, "inherited interface loop");
9426 this->set_is_error();
9427 break;
9430 if (q != seen.end())
9431 continue;
9432 seen.push_back(nt);
9435 for (Typed_identifier_list::const_iterator q = imethods->begin();
9436 q != imethods->end();
9437 ++q)
9439 if (q->name().empty())
9440 inherit.push_back(*q);
9441 else
9443 const Typed_identifier* oldm = this->find_method(q->name());
9444 if (oldm == NULL)
9445 this->all_methods_->push_back(Typed_identifier(q->name(),
9446 q->type(), tl));
9447 else if (!Type::are_identical(q->type(), oldm->type(),
9448 Type::COMPARE_TAGS, NULL))
9450 go_error_at(tl, "duplicate method %qs",
9451 Gogo::message_name(q->name()).c_str());
9452 this->set_is_error();
9457 seen.pop_back();
9460 if (!this->all_methods_->empty())
9461 this->all_methods_->sort_by_name();
9462 else
9464 delete this->all_methods_;
9465 this->all_methods_ = NULL;
9469 // Return the method NAME, or NULL.
9471 const Typed_identifier*
9472 Interface_type::find_method(const std::string& name) const
9474 go_assert(this->methods_are_finalized_);
9475 if (this->all_methods_ == NULL)
9476 return NULL;
9477 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9478 p != this->all_methods_->end();
9479 ++p)
9480 if (p->name() == name)
9481 return &*p;
9482 return NULL;
9485 // Return the method index.
9487 size_t
9488 Interface_type::method_index(const std::string& name) const
9490 go_assert(this->methods_are_finalized_ && this->all_methods_ != NULL);
9491 size_t ret = 0;
9492 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9493 p != this->all_methods_->end();
9494 ++p, ++ret)
9495 if (p->name() == name)
9496 return ret;
9497 go_unreachable();
9500 // Return whether NAME is an unexported method, for better error
9501 // reporting.
9503 bool
9504 Interface_type::is_unexported_method(Gogo* gogo, const std::string& name) const
9506 go_assert(this->methods_are_finalized_);
9507 if (this->all_methods_ == NULL)
9508 return false;
9509 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9510 p != this->all_methods_->end();
9511 ++p)
9513 const std::string& method_name(p->name());
9514 if (Gogo::is_hidden_name(method_name)
9515 && name == Gogo::unpack_hidden_name(method_name)
9516 && gogo->pack_hidden_name(name, false) != method_name)
9517 return true;
9519 return false;
9522 // Whether this type is identical with T.
9524 bool
9525 Interface_type::is_identical(const Interface_type* t, int flags) const
9527 // If methods have not been finalized, then we are asking whether
9528 // func redeclarations are the same. This is an error, so for
9529 // simplicity we say they are never the same.
9530 if (!this->methods_are_finalized_ || !t->methods_are_finalized_)
9531 return false;
9533 // Consult a flag to see whether we need to compare based on
9534 // parse methods or all methods.
9535 Typed_identifier_list* methods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9536 ? this->parse_methods_
9537 : this->all_methods_);
9538 Typed_identifier_list* tmethods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9539 ? t->parse_methods_
9540 : t->all_methods_);
9542 // We require the same methods with the same types. The methods
9543 // have already been sorted.
9544 if (methods == NULL || tmethods == NULL)
9545 return methods == tmethods;
9547 if (this->assume_identical(this, t) || t->assume_identical(t, this))
9548 return true;
9550 Assume_identical* hold_ai = this->assume_identical_;
9551 Assume_identical ai;
9552 ai.t1 = this;
9553 ai.t2 = t;
9554 ai.next = hold_ai;
9555 this->assume_identical_ = &ai;
9557 Typed_identifier_list::const_iterator p1 = methods->begin();
9558 Typed_identifier_list::const_iterator p2;
9559 for (p2 = tmethods->begin(); p2 != tmethods->end(); ++p1, ++p2)
9561 if (p1 == methods->end())
9562 break;
9563 if (p1->name() != p2->name()
9564 || !Type::are_identical(p1->type(), p2->type(), flags, NULL))
9565 break;
9568 this->assume_identical_ = hold_ai;
9570 return p1 == methods->end() && p2 == tmethods->end();
9573 // Return true if T1 and T2 are assumed to be identical during a type
9574 // comparison.
9576 bool
9577 Interface_type::assume_identical(const Interface_type* t1,
9578 const Interface_type* t2) const
9580 for (Assume_identical* p = this->assume_identical_;
9581 p != NULL;
9582 p = p->next)
9583 if ((p->t1 == t1 && p->t2 == t2) || (p->t1 == t2 && p->t2 == t1))
9584 return true;
9585 return false;
9588 // Whether we can assign the interface type T to this type. The types
9589 // are known to not be identical. An interface assignment is only
9590 // permitted if T is known to implement all methods in THIS.
9591 // Otherwise a type guard is required.
9593 bool
9594 Interface_type::is_compatible_for_assign(const Interface_type* t,
9595 std::string* reason) const
9597 go_assert(this->methods_are_finalized_ && t->methods_are_finalized_);
9598 if (this->all_methods_ == NULL)
9599 return true;
9600 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9601 p != this->all_methods_->end();
9602 ++p)
9604 const Typed_identifier* m = t->find_method(p->name());
9605 if (m == NULL)
9607 if (reason != NULL)
9609 char buf[200];
9610 snprintf(buf, sizeof buf,
9611 _("need explicit conversion; missing method %s%s%s"),
9612 go_open_quote(), Gogo::message_name(p->name()).c_str(),
9613 go_close_quote());
9614 reason->assign(buf);
9616 return false;
9619 std::string subreason;
9620 if (!Type::are_identical(p->type(), m->type(), Type::COMPARE_TAGS,
9621 &subreason))
9623 if (reason != NULL)
9625 std::string n = Gogo::message_name(p->name());
9626 size_t len = 100 + n.length() + subreason.length();
9627 char* buf = new char[len];
9628 if (subreason.empty())
9629 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9630 go_open_quote(), n.c_str(), go_close_quote());
9631 else
9632 snprintf(buf, len,
9633 _("incompatible type for method %s%s%s (%s)"),
9634 go_open_quote(), n.c_str(), go_close_quote(),
9635 subreason.c_str());
9636 reason->assign(buf);
9637 delete[] buf;
9639 return false;
9643 return true;
9646 // Hash code.
9648 unsigned int
9649 Interface_type::do_hash_for_method(Gogo*, int flags) const
9651 go_assert(this->methods_are_finalized_);
9652 Typed_identifier_list* methods = (((flags & COMPARE_EMBEDDED_INTERFACES) != 0)
9653 ? this->parse_methods_
9654 : this->all_methods_);
9655 unsigned int ret = 0;
9656 if (methods != NULL)
9658 for (Typed_identifier_list::const_iterator p = methods->begin();
9659 p != methods->end();
9660 ++p)
9662 ret = Gogo::hash_string(p->name(), ret);
9663 // We don't use the method type in the hash, to avoid
9664 // infinite recursion if an interface method uses a type
9665 // which is an interface which inherits from the interface
9666 // itself.
9667 // type T interface { F() interface {T}}
9668 ret <<= 1;
9671 return ret;
9674 // Return true if T implements the interface. If it does not, and
9675 // REASON is not NULL, set *REASON to a useful error message.
9677 bool
9678 Interface_type::implements_interface(const Type* t, std::string* reason) const
9680 go_assert(this->methods_are_finalized_);
9681 if (this->all_methods_ == NULL)
9682 return true;
9684 t = t->unalias();
9685 bool is_pointer = false;
9686 const Named_type* nt = t->named_type();
9687 const Struct_type* st = t->struct_type();
9688 // If we start with a named type, we don't dereference it to find
9689 // methods.
9690 if (nt == NULL)
9692 const Type* pt = t->points_to();
9693 if (pt != NULL)
9695 // If T is a pointer to a named type, then we need to look at
9696 // the type to which it points.
9697 pt = pt->unalias();
9698 is_pointer = true;
9699 nt = pt->named_type();
9700 st = pt->struct_type();
9704 // If we have a named type, get the methods from it rather than from
9705 // any struct type.
9706 if (nt != NULL)
9707 st = NULL;
9709 // Only named and struct types have methods.
9710 if (nt == NULL && st == NULL)
9712 if (reason != NULL)
9714 if (t->points_to() != NULL
9715 && t->points_to()->interface_type() != NULL)
9716 reason->assign(_("pointer to interface type has no methods"));
9717 else
9718 reason->assign(_("type has no methods"));
9720 return false;
9723 if (nt != NULL ? !nt->has_any_methods() : !st->has_any_methods())
9725 if (reason != NULL)
9727 if (t->points_to() != NULL
9728 && t->points_to()->interface_type() != NULL)
9729 reason->assign(_("pointer to interface type has no methods"));
9730 else
9731 reason->assign(_("type has no methods"));
9733 return false;
9736 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9737 p != this->all_methods_->end();
9738 ++p)
9740 bool is_ambiguous = false;
9741 Method* m = (nt != NULL
9742 ? nt->method_function(p->name(), &is_ambiguous)
9743 : st->method_function(p->name(), &is_ambiguous));
9744 if (m == NULL)
9746 if (reason != NULL)
9748 std::string n = Gogo::message_name(p->name());
9749 size_t len = n.length() + 100;
9750 char* buf = new char[len];
9751 if (is_ambiguous)
9752 snprintf(buf, len, _("ambiguous method %s%s%s"),
9753 go_open_quote(), n.c_str(), go_close_quote());
9754 else
9755 snprintf(buf, len, _("missing method %s%s%s"),
9756 go_open_quote(), n.c_str(), go_close_quote());
9757 reason->assign(buf);
9758 delete[] buf;
9760 return false;
9763 Function_type *p_fn_type = p->type()->function_type();
9764 Function_type* m_fn_type = m->type()->function_type();
9765 go_assert(p_fn_type != NULL && m_fn_type != NULL);
9766 std::string subreason;
9767 if (!p_fn_type->is_identical(m_fn_type, true, Type::COMPARE_TAGS,
9768 &subreason))
9770 if (reason != NULL)
9772 std::string n = Gogo::message_name(p->name());
9773 size_t len = 100 + n.length() + subreason.length();
9774 char* buf = new char[len];
9775 if (subreason.empty())
9776 snprintf(buf, len, _("incompatible type for method %s%s%s"),
9777 go_open_quote(), n.c_str(), go_close_quote());
9778 else
9779 snprintf(buf, len,
9780 _("incompatible type for method %s%s%s (%s)"),
9781 go_open_quote(), n.c_str(), go_close_quote(),
9782 subreason.c_str());
9783 reason->assign(buf);
9784 delete[] buf;
9786 return false;
9789 if (!is_pointer && !m->is_value_method())
9791 if (reason != NULL)
9793 std::string n = Gogo::message_name(p->name());
9794 size_t len = 100 + n.length();
9795 char* buf = new char[len];
9796 snprintf(buf, len,
9797 _("method %s%s%s requires a pointer receiver"),
9798 go_open_quote(), n.c_str(), go_close_quote());
9799 reason->assign(buf);
9800 delete[] buf;
9802 return false;
9805 // If the magic //go:nointerface comment was used, the method
9806 // may not be used to implement interfaces.
9807 if (m->nointerface())
9809 if (reason != NULL)
9811 std::string n = Gogo::message_name(p->name());
9812 size_t len = 100 + n.length();
9813 char* buf = new char[len];
9814 snprintf(buf, len,
9815 _("method %s%s%s is marked go:nointerface"),
9816 go_open_quote(), n.c_str(), go_close_quote());
9817 reason->assign(buf);
9818 delete[] buf;
9820 return false;
9824 return true;
9827 // Return the backend representation of the empty interface type. We
9828 // use the same struct for all empty interfaces.
9830 Btype*
9831 Interface_type::get_backend_empty_interface_type(Gogo* gogo)
9833 static Btype* empty_interface_type;
9834 if (empty_interface_type == NULL)
9836 std::vector<Backend::Btyped_identifier> bfields(2);
9838 Location bloc = Linemap::predeclared_location();
9840 Type* pdt = Type::make_type_descriptor_ptr_type();
9841 bfields[0].name = "__type_descriptor";
9842 bfields[0].btype = pdt->get_backend(gogo);
9843 bfields[0].location = bloc;
9845 Type* vt = Type::make_pointer_type(Type::make_void_type());
9846 bfields[1].name = "__object";
9847 bfields[1].btype = vt->get_backend(gogo);
9848 bfields[1].location = bloc;
9850 empty_interface_type = gogo->backend()->struct_type(bfields);
9852 return empty_interface_type;
9855 Interface_type::Bmethods_map Interface_type::bmethods_map;
9857 // Return a pointer to the backend representation of the method table.
9859 Btype*
9860 Interface_type::get_backend_methods(Gogo* gogo)
9862 if (this->bmethods_ != NULL && !this->bmethods_is_placeholder_)
9863 return this->bmethods_;
9865 std::pair<Interface_type*, Bmethods_map_entry> val;
9866 val.first = this;
9867 val.second.btype = NULL;
9868 val.second.is_placeholder = false;
9869 std::pair<Bmethods_map::iterator, bool> ins =
9870 Interface_type::bmethods_map.insert(val);
9871 if (!ins.second
9872 && ins.first->second.btype != NULL
9873 && !ins.first->second.is_placeholder)
9875 this->bmethods_ = ins.first->second.btype;
9876 this->bmethods_is_placeholder_ = false;
9877 return this->bmethods_;
9880 Location loc = this->location();
9882 std::vector<Backend::Btyped_identifier>
9883 mfields(this->all_methods_->size() + 1);
9885 Type* pdt = Type::make_type_descriptor_ptr_type();
9886 mfields[0].name = "__type_descriptor";
9887 mfields[0].btype = pdt->get_backend(gogo);
9888 mfields[0].location = loc;
9890 std::string last_name = "";
9891 size_t i = 1;
9892 for (Typed_identifier_list::const_iterator p = this->all_methods_->begin();
9893 p != this->all_methods_->end();
9894 ++p, ++i)
9896 // The type of the method in Go only includes the parameters.
9897 // The actual method also has a receiver, which is always a
9898 // pointer. We need to add that pointer type here in order to
9899 // generate the correct type for the backend.
9900 Function_type* ft = p->type()->function_type();
9901 go_assert(ft->receiver() == NULL);
9903 const Typed_identifier_list* params = ft->parameters();
9904 Typed_identifier_list* mparams = new Typed_identifier_list();
9905 if (params != NULL)
9906 mparams->reserve(params->size() + 1);
9907 Type* vt = Type::make_pointer_type(Type::make_void_type());
9908 mparams->push_back(Typed_identifier("", vt, ft->location()));
9909 if (params != NULL)
9911 for (Typed_identifier_list::const_iterator pp = params->begin();
9912 pp != params->end();
9913 ++pp)
9914 mparams->push_back(*pp);
9917 Typed_identifier_list* mresults = (ft->results() == NULL
9918 ? NULL
9919 : ft->results()->copy());
9920 Function_type* mft = Type::make_function_type(NULL, mparams, mresults,
9921 ft->location());
9923 mfields[i].name = Gogo::unpack_hidden_name(p->name());
9924 mfields[i].btype = mft->get_backend_fntype(gogo);
9925 mfields[i].location = loc;
9927 // Sanity check: the names should be sorted.
9928 go_assert(Gogo::unpack_hidden_name(p->name())
9929 > Gogo::unpack_hidden_name(last_name));
9930 last_name = p->name();
9933 Btype* st = gogo->backend()->struct_type(mfields);
9934 Btype* ret = gogo->backend()->pointer_type(st);
9936 if (ins.first->second.btype != NULL
9937 && ins.first->second.is_placeholder)
9938 gogo->backend()->set_placeholder_pointer_type(ins.first->second.btype,
9939 ret);
9940 this->bmethods_ = ret;
9941 ins.first->second.btype = ret;
9942 this->bmethods_is_placeholder_ = false;
9943 ins.first->second.is_placeholder = false;
9944 return ret;
9947 // Return a placeholder for the pointer to the backend methods table.
9949 Btype*
9950 Interface_type::get_backend_methods_placeholder(Gogo* gogo)
9952 if (this->bmethods_ == NULL)
9954 std::pair<Interface_type*, Bmethods_map_entry> val;
9955 val.first = this;
9956 val.second.btype = NULL;
9957 val.second.is_placeholder = false;
9958 std::pair<Bmethods_map::iterator, bool> ins =
9959 Interface_type::bmethods_map.insert(val);
9960 if (!ins.second && ins.first->second.btype != NULL)
9962 this->bmethods_ = ins.first->second.btype;
9963 this->bmethods_is_placeholder_ = ins.first->second.is_placeholder;
9964 return this->bmethods_;
9967 Location loc = this->location();
9968 Btype* bt = gogo->backend()->placeholder_pointer_type("", loc, false);
9969 this->bmethods_ = bt;
9970 ins.first->second.btype = bt;
9971 this->bmethods_is_placeholder_ = true;
9972 ins.first->second.is_placeholder = true;
9974 return this->bmethods_;
9977 // Return the fields of a non-empty interface type. This is not
9978 // declared in types.h so that types.h doesn't have to #include
9979 // backend.h.
9981 static void
9982 get_backend_interface_fields(Gogo* gogo, Interface_type* type,
9983 bool use_placeholder,
9984 std::vector<Backend::Btyped_identifier>* bfields)
9986 Location loc = type->location();
9988 bfields->resize(2);
9990 (*bfields)[0].name = "__methods";
9991 (*bfields)[0].btype = (use_placeholder
9992 ? type->get_backend_methods_placeholder(gogo)
9993 : type->get_backend_methods(gogo));
9994 (*bfields)[0].location = loc;
9996 Type* vt = Type::make_pointer_type(Type::make_void_type());
9997 (*bfields)[1].name = "__object";
9998 (*bfields)[1].btype = vt->get_backend(gogo);
9999 (*bfields)[1].location = Linemap::predeclared_location();
10002 // Return the backend representation for an interface type. An interface is a
10003 // pointer to a struct. The struct has three fields. The first field is a
10004 // pointer to the type descriptor for the dynamic type of the object.
10005 // The second field is a pointer to a table of methods for the
10006 // interface to be used with the object. The third field is the value
10007 // of the object itself.
10009 Btype*
10010 Interface_type::do_get_backend(Gogo* gogo)
10012 if (this->is_empty())
10013 return Interface_type::get_backend_empty_interface_type(gogo);
10014 else
10016 if (this->interface_btype_ != NULL)
10017 return this->interface_btype_;
10018 this->interface_btype_ =
10019 gogo->backend()->placeholder_struct_type("", this->location_);
10020 std::vector<Backend::Btyped_identifier> bfields;
10021 get_backend_interface_fields(gogo, this, false, &bfields);
10022 if (!gogo->backend()->set_placeholder_struct_type(this->interface_btype_,
10023 bfields))
10024 this->interface_btype_ = gogo->backend()->error_type();
10025 return this->interface_btype_;
10029 // Finish the backend representation of the methods.
10031 void
10032 Interface_type::finish_backend_methods(Gogo* gogo)
10034 if (!this->is_empty())
10036 const Typed_identifier_list* methods = this->methods();
10037 if (methods != NULL)
10039 for (Typed_identifier_list::const_iterator p = methods->begin();
10040 p != methods->end();
10041 ++p)
10042 p->type()->get_backend(gogo);
10045 // Getting the backend methods now will set the placeholder
10046 // pointer.
10047 this->get_backend_methods(gogo);
10051 // The type of an interface type descriptor.
10053 Type*
10054 Interface_type::make_interface_type_descriptor_type()
10056 static Type* ret;
10057 if (ret == NULL)
10059 Type* tdt = Type::make_type_descriptor_type();
10060 Type* ptdt = Type::make_type_descriptor_ptr_type();
10062 Type* string_type = Type::lookup_string_type();
10063 Type* pointer_string_type = Type::make_pointer_type(string_type);
10065 Struct_type* sm =
10066 Type::make_builtin_struct_type(3,
10067 "name", pointer_string_type,
10068 "pkgPath", pointer_string_type,
10069 "typ", ptdt);
10071 Type* nsm = Type::make_builtin_named_type("imethod", sm);
10073 Type* slice_nsm = Type::make_array_type(nsm, NULL);
10075 Struct_type* s = Type::make_builtin_struct_type(2,
10076 "", tdt,
10077 "methods", slice_nsm);
10079 ret = Type::make_builtin_named_type("InterfaceType", s);
10082 return ret;
10085 // Build a type descriptor for an interface type.
10087 Expression*
10088 Interface_type::do_type_descriptor(Gogo* gogo, Named_type* name)
10090 Location bloc = Linemap::predeclared_location();
10092 Type* itdt = Interface_type::make_interface_type_descriptor_type();
10094 const Struct_field_list* ifields = itdt->struct_type()->fields();
10096 Expression_list* ivals = new Expression_list();
10097 ivals->reserve(2);
10099 Struct_field_list::const_iterator pif = ifields->begin();
10100 go_assert(pif->is_field_name("_type"));
10101 const int rt = RUNTIME_TYPE_KIND_INTERFACE;
10102 ivals->push_back(this->type_descriptor_constructor(gogo, rt, name, NULL,
10103 true));
10105 ++pif;
10106 go_assert(pif->is_field_name("methods"));
10108 Expression_list* methods = new Expression_list();
10109 if (this->all_methods_ != NULL)
10111 Type* elemtype = pif->type()->array_type()->element_type();
10113 methods->reserve(this->all_methods_->size());
10114 for (Typed_identifier_list::const_iterator pm =
10115 this->all_methods_->begin();
10116 pm != this->all_methods_->end();
10117 ++pm)
10119 const Struct_field_list* mfields = elemtype->struct_type()->fields();
10121 Expression_list* mvals = new Expression_list();
10122 mvals->reserve(3);
10124 Struct_field_list::const_iterator pmf = mfields->begin();
10125 go_assert(pmf->is_field_name("name"));
10126 std::string s = Gogo::unpack_hidden_name(pm->name());
10127 Expression* e = Expression::make_string(s, bloc);
10128 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
10130 ++pmf;
10131 go_assert(pmf->is_field_name("pkgPath"));
10132 if (!Gogo::is_hidden_name(pm->name()))
10133 mvals->push_back(Expression::make_nil(bloc));
10134 else
10136 s = Gogo::hidden_name_pkgpath(pm->name());
10137 e = Expression::make_string(s, bloc);
10138 mvals->push_back(Expression::make_unary(OPERATOR_AND, e, bloc));
10141 ++pmf;
10142 go_assert(pmf->is_field_name("typ"));
10143 mvals->push_back(Expression::make_type_descriptor(pm->type(), bloc));
10145 ++pmf;
10146 go_assert(pmf == mfields->end());
10148 e = Expression::make_struct_composite_literal(elemtype, mvals,
10149 bloc);
10150 methods->push_back(e);
10154 ivals->push_back(Expression::make_slice_composite_literal(pif->type(),
10155 methods, bloc));
10157 ++pif;
10158 go_assert(pif == ifields->end());
10160 return Expression::make_struct_composite_literal(itdt, ivals, bloc);
10163 // Reflection string.
10165 void
10166 Interface_type::do_reflection(Gogo* gogo, std::string* ret) const
10168 ret->append("interface {");
10169 const Typed_identifier_list* methods = this->parse_methods_;
10170 if (methods != NULL)
10172 ret->push_back(' ');
10173 for (Typed_identifier_list::const_iterator p = methods->begin();
10174 p != methods->end();
10175 ++p)
10177 if (p != methods->begin())
10178 ret->append("; ");
10179 if (p->name().empty())
10180 this->append_reflection(p->type(), gogo, ret);
10181 else
10183 if (!Gogo::is_hidden_name(p->name()))
10184 ret->append(p->name());
10185 else if (gogo->pkgpath_from_option())
10186 ret->append(p->name().substr(1));
10187 else
10189 // If no -fgo-pkgpath option, backward compatibility
10190 // for how this used to work before -fgo-pkgpath was
10191 // introduced.
10192 std::string pkgpath = Gogo::hidden_name_pkgpath(p->name());
10193 ret->append(pkgpath.substr(pkgpath.find('.') + 1));
10194 ret->push_back('.');
10195 ret->append(Gogo::unpack_hidden_name(p->name()));
10197 std::string sub = p->type()->reflection(gogo);
10198 go_assert(sub.compare(0, 4, "func") == 0);
10199 sub = sub.substr(4);
10200 ret->append(sub);
10203 ret->push_back(' ');
10205 ret->append("}");
10208 // Export.
10210 void
10211 Interface_type::do_export(Export* exp) const
10213 exp->write_c_string("interface { ");
10215 const Typed_identifier_list* methods = this->parse_methods_;
10216 if (methods != NULL)
10218 for (Typed_identifier_list::const_iterator pm = methods->begin();
10219 pm != methods->end();
10220 ++pm)
10222 if (pm->name().empty())
10224 exp->write_c_string("? ");
10225 exp->write_type(pm->type());
10227 else
10229 exp->write_string(pm->name());
10230 exp->write_c_string(" (");
10232 const Function_type* fntype = pm->type()->function_type();
10234 bool first = true;
10235 const Typed_identifier_list* parameters = fntype->parameters();
10236 if (parameters != NULL)
10238 bool is_varargs = fntype->is_varargs();
10239 for (Typed_identifier_list::const_iterator pp =
10240 parameters->begin();
10241 pp != parameters->end();
10242 ++pp)
10244 if (first)
10245 first = false;
10246 else
10247 exp->write_c_string(", ");
10248 exp->write_name(pp->name());
10249 exp->write_c_string(" ");
10250 if (!is_varargs || pp + 1 != parameters->end())
10251 exp->write_type(pp->type());
10252 else
10254 exp->write_c_string("...");
10255 Type *pptype = pp->type();
10256 exp->write_type(pptype->array_type()->element_type());
10261 exp->write_c_string(")");
10263 const Typed_identifier_list* results = fntype->results();
10264 if (results != NULL)
10266 exp->write_c_string(" ");
10267 if (results->size() == 1 && results->begin()->name().empty())
10268 exp->write_type(results->begin()->type());
10269 else
10271 first = true;
10272 exp->write_c_string("(");
10273 for (Typed_identifier_list::const_iterator p =
10274 results->begin();
10275 p != results->end();
10276 ++p)
10278 if (first)
10279 first = false;
10280 else
10281 exp->write_c_string(", ");
10282 exp->write_name(p->name());
10283 exp->write_c_string(" ");
10284 exp->write_type(p->type());
10286 exp->write_c_string(")");
10291 exp->write_c_string("; ");
10295 exp->write_c_string("}");
10298 // Import an interface type.
10300 Interface_type*
10301 Interface_type::do_import(Import* imp)
10303 imp->require_c_string("interface { ");
10305 Typed_identifier_list* methods = new Typed_identifier_list;
10306 while (imp->peek_char() != '}')
10308 std::string name = imp->read_identifier();
10310 if (name == "?")
10312 imp->require_c_string(" ");
10313 Type* t = imp->read_type();
10314 methods->push_back(Typed_identifier("", t, imp->location()));
10315 imp->require_c_string("; ");
10316 continue;
10319 imp->require_c_string(" (");
10321 Typed_identifier_list* parameters;
10322 bool is_varargs = false;
10323 if (imp->peek_char() == ')')
10324 parameters = NULL;
10325 else
10327 parameters = new Typed_identifier_list;
10328 while (true)
10330 std::string pname = imp->read_name();
10331 imp->require_c_string(" ");
10333 if (imp->match_c_string("..."))
10335 imp->advance(3);
10336 is_varargs = true;
10339 Type* ptype = imp->read_type();
10340 if (is_varargs)
10341 ptype = Type::make_array_type(ptype, NULL);
10342 parameters->push_back(Typed_identifier(pname, ptype,
10343 imp->location()));
10344 if (imp->peek_char() != ',')
10345 break;
10346 go_assert(!is_varargs);
10347 imp->require_c_string(", ");
10350 imp->require_c_string(")");
10352 Typed_identifier_list* results;
10353 if (imp->peek_char() != ' ')
10354 results = NULL;
10355 else
10357 results = new Typed_identifier_list;
10358 imp->advance(1);
10359 if (imp->peek_char() != '(')
10361 Type* rtype = imp->read_type();
10362 results->push_back(Typed_identifier("", rtype, imp->location()));
10364 else
10366 imp->advance(1);
10367 while (true)
10369 std::string rname = imp->read_name();
10370 imp->require_c_string(" ");
10371 Type* rtype = imp->read_type();
10372 results->push_back(Typed_identifier(rname, rtype,
10373 imp->location()));
10374 if (imp->peek_char() != ',')
10375 break;
10376 imp->require_c_string(", ");
10378 imp->require_c_string(")");
10382 Function_type* fntype = Type::make_function_type(NULL, parameters,
10383 results,
10384 imp->location());
10385 if (is_varargs)
10386 fntype->set_is_varargs();
10387 methods->push_back(Typed_identifier(name, fntype, imp->location()));
10389 imp->require_c_string("; ");
10392 imp->require_c_string("}");
10394 if (methods->empty())
10396 delete methods;
10397 methods = NULL;
10400 Interface_type* ret = Type::make_interface_type(methods, imp->location());
10401 ret->package_ = imp->package();
10402 return ret;
10405 // Make an interface type.
10407 Interface_type*
10408 Type::make_interface_type(Typed_identifier_list* methods,
10409 Location location)
10411 return new Interface_type(methods, location);
10414 // Make an empty interface type.
10416 Interface_type*
10417 Type::make_empty_interface_type(Location location)
10419 Interface_type* ret = new Interface_type(NULL, location);
10420 ret->finalize_methods();
10421 return ret;
10424 // Class Method.
10426 // Bind a method to an object.
10428 Expression*
10429 Method::bind_method(Expression* expr, Location location) const
10431 if (this->stub_ == NULL)
10433 // When there is no stub object, the binding is determined by
10434 // the child class.
10435 return this->do_bind_method(expr, location);
10437 return Expression::make_bound_method(expr, this, this->stub_, location);
10440 // Return the named object associated with a method. This may only be
10441 // called after methods are finalized.
10443 Named_object*
10444 Method::named_object() const
10446 if (this->stub_ != NULL)
10447 return this->stub_;
10448 return this->do_named_object();
10451 // Class Named_method.
10453 // The type of the method.
10455 Function_type*
10456 Named_method::do_type() const
10458 if (this->named_object_->is_function())
10459 return this->named_object_->func_value()->type();
10460 else if (this->named_object_->is_function_declaration())
10461 return this->named_object_->func_declaration_value()->type();
10462 else
10463 go_unreachable();
10466 // Return the location of the method receiver.
10468 Location
10469 Named_method::do_receiver_location() const
10471 return this->do_type()->receiver()->location();
10474 // Bind a method to an object.
10476 Expression*
10477 Named_method::do_bind_method(Expression* expr, Location location) const
10479 Named_object* no = this->named_object_;
10480 Bound_method_expression* bme = Expression::make_bound_method(expr, this,
10481 no, location);
10482 // If this is not a local method, and it does not use a stub, then
10483 // the real method expects a different type. We need to cast the
10484 // first argument.
10485 if (this->depth() > 0 && !this->needs_stub_method())
10487 Function_type* ftype = this->do_type();
10488 go_assert(ftype->is_method());
10489 Type* frtype = ftype->receiver()->type();
10490 bme->set_first_argument_type(frtype);
10492 return bme;
10495 // Return whether this method should not participate in interfaces.
10497 bool
10498 Named_method::do_nointerface() const
10500 Named_object* no = this->named_object_;
10501 if (no->is_function())
10502 return no->func_value()->nointerface();
10503 else if (no->is_function_declaration())
10504 return no->func_declaration_value()->nointerface();
10505 else
10506 go_unreachable();
10509 // Class Interface_method.
10511 // Bind a method to an object.
10513 Expression*
10514 Interface_method::do_bind_method(Expression* expr,
10515 Location location) const
10517 return Expression::make_interface_field_reference(expr, this->name_,
10518 location);
10521 // Class Methods.
10523 // Insert a new method. Return true if it was inserted, false
10524 // otherwise.
10526 bool
10527 Methods::insert(const std::string& name, Method* m)
10529 std::pair<Method_map::iterator, bool> ins =
10530 this->methods_.insert(std::make_pair(name, m));
10531 if (ins.second)
10532 return true;
10533 else
10535 Method* old_method = ins.first->second;
10536 if (m->depth() < old_method->depth())
10538 delete old_method;
10539 ins.first->second = m;
10540 return true;
10542 else
10544 if (m->depth() == old_method->depth())
10545 old_method->set_is_ambiguous();
10546 return false;
10551 // Return the number of unambiguous methods.
10553 size_t
10554 Methods::count() const
10556 size_t ret = 0;
10557 for (Method_map::const_iterator p = this->methods_.begin();
10558 p != this->methods_.end();
10559 ++p)
10560 if (!p->second->is_ambiguous())
10561 ++ret;
10562 return ret;
10565 // Class Named_type.
10567 // Return the name of the type.
10569 const std::string&
10570 Named_type::name() const
10572 return this->named_object_->name();
10575 // Return the name of the type to use in an error message.
10577 void
10578 Named_type::do_message_name(std::string* ret) const
10580 ret->append(this->named_object_->message_name());
10583 // Return the base type for this type. We have to be careful about
10584 // circular type definitions, which are invalid but may be seen here.
10586 Type*
10587 Named_type::named_base()
10589 if (this->seen_)
10590 return this;
10591 this->seen_ = true;
10592 Type* ret = this->type_->base();
10593 this->seen_ = false;
10594 return ret;
10597 const Type*
10598 Named_type::named_base() const
10600 if (this->seen_)
10601 return this;
10602 this->seen_ = true;
10603 const Type* ret = this->type_->base();
10604 this->seen_ = false;
10605 return ret;
10608 // Return whether this is an error type. We have to be careful about
10609 // circular type definitions, which are invalid but may be seen here.
10611 bool
10612 Named_type::is_named_error_type() const
10614 if (this->seen_)
10615 return false;
10616 this->seen_ = true;
10617 bool ret = this->type_->is_error_type();
10618 this->seen_ = false;
10619 return ret;
10622 // Whether this type is comparable. We have to be careful about
10623 // circular type definitions.
10625 bool
10626 Named_type::named_type_is_comparable(std::string* reason) const
10628 if (this->seen_)
10629 return false;
10630 this->seen_ = true;
10631 bool ret = Type::are_compatible_for_comparison(true, this->type_,
10632 this->type_, reason);
10633 this->seen_ = false;
10634 return ret;
10637 // Add a method to this type.
10639 Named_object*
10640 Named_type::add_method(const std::string& name, Function* function)
10642 go_assert(!this->is_alias_);
10643 if (this->local_methods_ == NULL)
10644 this->local_methods_ = new Bindings(NULL);
10645 return this->local_methods_->add_function(name,
10646 this->named_object_->package(),
10647 function);
10650 // Add a method declaration to this type.
10652 Named_object*
10653 Named_type::add_method_declaration(const std::string& name, Package* package,
10654 Function_type* type,
10655 Location location)
10657 go_assert(!this->is_alias_);
10658 if (this->local_methods_ == NULL)
10659 this->local_methods_ = new Bindings(NULL);
10660 return this->local_methods_->add_function_declaration(name, package, type,
10661 location);
10664 // Add an existing method to this type.
10666 void
10667 Named_type::add_existing_method(Named_object* no)
10669 go_assert(!this->is_alias_);
10670 if (this->local_methods_ == NULL)
10671 this->local_methods_ = new Bindings(NULL);
10672 this->local_methods_->add_named_object(no);
10675 // Look for a local method NAME, and returns its named object, or NULL
10676 // if not there.
10678 Named_object*
10679 Named_type::find_local_method(const std::string& name) const
10681 if (this->is_error_)
10682 return NULL;
10683 if (this->is_alias_)
10685 Named_type* nt = this->type_->named_type();
10686 if (nt != NULL)
10688 if (this->seen_alias_)
10689 return NULL;
10690 this->seen_alias_ = true;
10691 Named_object* ret = nt->find_local_method(name);
10692 this->seen_alias_ = false;
10693 return ret;
10695 return NULL;
10697 if (this->local_methods_ == NULL)
10698 return NULL;
10699 return this->local_methods_->lookup(name);
10702 // Return the list of local methods.
10704 const Bindings*
10705 Named_type::local_methods() const
10707 if (this->is_error_)
10708 return NULL;
10709 if (this->is_alias_)
10711 Named_type* nt = this->type_->named_type();
10712 if (nt != NULL)
10714 if (this->seen_alias_)
10715 return NULL;
10716 this->seen_alias_ = true;
10717 const Bindings* ret = nt->local_methods();
10718 this->seen_alias_ = false;
10719 return ret;
10721 return NULL;
10723 return this->local_methods_;
10726 // Return whether NAME is an unexported field or method, for better
10727 // error reporting.
10729 bool
10730 Named_type::is_unexported_local_method(Gogo* gogo,
10731 const std::string& name) const
10733 if (this->is_error_)
10734 return false;
10735 if (this->is_alias_)
10737 Named_type* nt = this->type_->named_type();
10738 if (nt != NULL)
10740 if (this->seen_alias_)
10741 return false;
10742 this->seen_alias_ = true;
10743 bool ret = nt->is_unexported_local_method(gogo, name);
10744 this->seen_alias_ = false;
10745 return ret;
10747 return false;
10749 Bindings* methods = this->local_methods_;
10750 if (methods != NULL)
10752 for (Bindings::const_declarations_iterator p =
10753 methods->begin_declarations();
10754 p != methods->end_declarations();
10755 ++p)
10757 if (Gogo::is_hidden_name(p->first)
10758 && name == Gogo::unpack_hidden_name(p->first)
10759 && gogo->pack_hidden_name(name, false) != p->first)
10760 return true;
10763 return false;
10766 // Build the complete list of methods for this type, which means
10767 // recursively including all methods for anonymous fields. Create all
10768 // stub methods.
10770 void
10771 Named_type::finalize_methods(Gogo* gogo)
10773 if (this->is_alias_)
10774 return;
10775 if (this->all_methods_ != NULL)
10776 return;
10778 if (this->local_methods_ != NULL
10779 && (this->points_to() != NULL || this->interface_type() != NULL))
10781 const Bindings* lm = this->local_methods_;
10782 for (Bindings::const_declarations_iterator p = lm->begin_declarations();
10783 p != lm->end_declarations();
10784 ++p)
10785 go_error_at(p->second->location(),
10786 "invalid pointer or interface receiver type");
10787 delete this->local_methods_;
10788 this->local_methods_ = NULL;
10789 return;
10792 // Remove any aliases in the local method receiver types.
10793 Bindings* methods = this->local_methods_;
10794 if (methods != NULL)
10796 for (Bindings::const_declarations_iterator p =
10797 methods->begin_declarations();
10798 p != methods->end_declarations();
10799 ++p)
10801 Named_object* no = p->second;
10802 Function_type* fntype;
10803 if (no->is_function())
10804 fntype = no->func_value()->type();
10805 else if (no->is_function_declaration())
10806 fntype = no->func_declaration_value()->type();
10807 else
10809 go_assert(saw_errors());
10810 continue;
10813 Type* rtype = fntype->receiver()->type();
10814 bool is_pointer = false;
10815 Type* pt = rtype->points_to();
10816 if (pt != NULL)
10818 rtype = pt;
10819 is_pointer = true;
10821 if (rtype->named_type() != this)
10823 if (rtype->unalias() != this)
10825 go_assert(saw_errors());
10826 continue;
10829 rtype = this;
10830 if (is_pointer)
10831 rtype = Type::make_pointer_type(rtype);
10833 if (no->is_function())
10834 no->func_value()->set_receiver_type(rtype);
10835 else if (no->is_function_declaration())
10836 no->func_declaration_value()->set_receiver_type(rtype);
10837 else
10838 go_unreachable();
10843 Type::finalize_methods(gogo, this, this->location_, &this->all_methods_);
10846 // Return whether this type has any methods.
10848 bool
10849 Named_type::has_any_methods() const
10851 if (this->is_error_)
10852 return false;
10853 if (this->is_alias_)
10855 if (this->type_->named_type() != NULL)
10857 if (this->seen_alias_)
10858 return false;
10859 this->seen_alias_ = true;
10860 bool ret = this->type_->named_type()->has_any_methods();
10861 this->seen_alias_ = false;
10862 return ret;
10864 if (this->type_->struct_type() != NULL)
10865 return this->type_->struct_type()->has_any_methods();
10866 return false;
10868 return this->all_methods_ != NULL;
10871 // Return the methods for this type.
10873 const Methods*
10874 Named_type::methods() const
10876 if (this->is_error_)
10877 return NULL;
10878 if (this->is_alias_)
10880 if (this->type_->named_type() != NULL)
10882 if (this->seen_alias_)
10883 return NULL;
10884 this->seen_alias_ = true;
10885 const Methods* ret = this->type_->named_type()->methods();
10886 this->seen_alias_ = false;
10887 return ret;
10889 if (this->type_->struct_type() != NULL)
10890 return this->type_->struct_type()->methods();
10891 return NULL;
10893 return this->all_methods_;
10896 // Return the method NAME, or NULL if there isn't one or if it is
10897 // ambiguous. Set *IS_AMBIGUOUS if the method exists but is
10898 // ambiguous.
10900 Method*
10901 Named_type::method_function(const std::string& name, bool* is_ambiguous) const
10903 if (this->is_error_)
10904 return NULL;
10905 if (this->is_alias_)
10907 if (is_ambiguous != NULL)
10908 *is_ambiguous = false;
10909 if (this->type_->named_type() != NULL)
10911 if (this->seen_alias_)
10912 return NULL;
10913 this->seen_alias_ = true;
10914 Named_type* nt = this->type_->named_type();
10915 Method* ret = nt->method_function(name, is_ambiguous);
10916 this->seen_alias_ = false;
10917 return ret;
10919 if (this->type_->struct_type() != NULL)
10920 return this->type_->struct_type()->method_function(name, is_ambiguous);
10921 return NULL;
10923 return Type::method_function(this->all_methods_, name, is_ambiguous);
10926 // Return a pointer to the interface method table for this type for
10927 // the interface INTERFACE. IS_POINTER is true if this is for a
10928 // pointer to THIS.
10930 Expression*
10931 Named_type::interface_method_table(Interface_type* interface, bool is_pointer)
10933 if (this->is_error_)
10934 return Expression::make_error(this->location_);
10935 if (this->is_alias_)
10937 Type* t = this->type_;
10938 if (!is_pointer && t->points_to() != NULL)
10940 t = t->points_to();
10941 is_pointer = true;
10943 if (t->named_type() != NULL)
10945 if (this->seen_alias_)
10946 return Expression::make_error(this->location_);
10947 this->seen_alias_ = true;
10948 Named_type* nt = t->named_type();
10949 Expression* ret = nt->interface_method_table(interface, is_pointer);
10950 this->seen_alias_ = false;
10951 return ret;
10953 if (t->struct_type() != NULL)
10954 return t->struct_type()->interface_method_table(interface, is_pointer);
10955 go_unreachable();
10957 return Type::interface_method_table(this, interface, is_pointer,
10958 &this->interface_method_tables_,
10959 &this->pointer_interface_method_tables_);
10962 // Look for a use of a complete type within another type. This is
10963 // used to check that we don't try to use a type within itself.
10965 class Find_type_use : public Traverse
10967 public:
10968 Find_type_use(Named_type* find_type)
10969 : Traverse(traverse_types),
10970 find_type_(find_type), found_(false)
10973 // Whether we found the type.
10974 bool
10975 found() const
10976 { return this->found_; }
10978 protected:
10980 type(Type*);
10982 private:
10983 // The type we are looking for.
10984 Named_type* find_type_;
10985 // Whether we found the type.
10986 bool found_;
10989 // Check for FIND_TYPE in TYPE.
10992 Find_type_use::type(Type* type)
10994 if (type->named_type() != NULL && this->find_type_ == type->named_type())
10996 this->found_ = true;
10997 return TRAVERSE_EXIT;
11000 // It's OK if we see a reference to the type in any type which is
11001 // essentially a pointer: a pointer, a slice, a function, a map, or
11002 // a channel.
11003 if (type->points_to() != NULL
11004 || type->is_slice_type()
11005 || type->function_type() != NULL
11006 || type->map_type() != NULL
11007 || type->channel_type() != NULL)
11008 return TRAVERSE_SKIP_COMPONENTS;
11010 // For an interface, a reference to the type in a method type should
11011 // be ignored, but we have to consider direct inheritance. When
11012 // this is called, there may be cases of direct inheritance
11013 // represented as a method with no name.
11014 if (type->interface_type() != NULL)
11016 const Typed_identifier_list* methods = type->interface_type()->methods();
11017 if (methods != NULL)
11019 for (Typed_identifier_list::const_iterator p = methods->begin();
11020 p != methods->end();
11021 ++p)
11023 if (p->name().empty())
11025 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
11026 return TRAVERSE_EXIT;
11030 return TRAVERSE_SKIP_COMPONENTS;
11033 // Otherwise, FIND_TYPE_ depends on TYPE, in the sense that we need
11034 // to convert TYPE to the backend representation before we convert
11035 // FIND_TYPE_.
11036 if (type->named_type() != NULL)
11038 switch (type->base()->classification())
11040 case Type::TYPE_ERROR:
11041 case Type::TYPE_BOOLEAN:
11042 case Type::TYPE_INTEGER:
11043 case Type::TYPE_FLOAT:
11044 case Type::TYPE_COMPLEX:
11045 case Type::TYPE_STRING:
11046 case Type::TYPE_NIL:
11047 break;
11049 case Type::TYPE_ARRAY:
11050 case Type::TYPE_STRUCT:
11051 this->find_type_->add_dependency(type->named_type());
11052 break;
11054 case Type::TYPE_NAMED:
11055 if (type->named_type() == type->base()->named_type())
11057 this->found_ = true;
11058 return TRAVERSE_EXIT;
11060 else
11061 go_assert(saw_errors());
11062 break;
11064 case Type::TYPE_FORWARD:
11065 go_assert(saw_errors());
11066 break;
11068 case Type::TYPE_VOID:
11069 case Type::TYPE_SINK:
11070 case Type::TYPE_FUNCTION:
11071 case Type::TYPE_POINTER:
11072 case Type::TYPE_CALL_MULTIPLE_RESULT:
11073 case Type::TYPE_MAP:
11074 case Type::TYPE_CHANNEL:
11075 case Type::TYPE_INTERFACE:
11076 default:
11077 go_unreachable();
11081 return TRAVERSE_CONTINUE;
11084 // Look for a circular reference of an alias.
11086 class Find_alias : public Traverse
11088 public:
11089 Find_alias(Named_type* find_type)
11090 : Traverse(traverse_types),
11091 find_type_(find_type), found_(false)
11094 // Whether we found the type.
11095 bool
11096 found() const
11097 { return this->found_; }
11099 protected:
11101 type(Type*);
11103 private:
11104 // The type we are looking for.
11105 Named_type* find_type_;
11106 // Whether we found the type.
11107 bool found_;
11111 Find_alias::type(Type* type)
11113 Named_type* nt = type->named_type();
11114 if (nt != NULL)
11116 if (nt == this->find_type_)
11118 this->found_ = true;
11119 return TRAVERSE_EXIT;
11122 // We started from `type T1 = T2`, where T1 is find_type_ and T2
11123 // is, perhaps indirectly, the parameter TYPE. If TYPE is not
11124 // an alias itself, it's OK if whatever T2 is defined as refers
11125 // to T1.
11126 if (!nt->is_alias())
11127 return TRAVERSE_SKIP_COMPONENTS;
11130 // Check if there are recursive inherited interface aliases.
11131 Interface_type* ift = type->interface_type();
11132 if (ift != NULL)
11134 const Typed_identifier_list* methods = ift->local_methods();
11135 if (methods == NULL)
11136 return TRAVERSE_CONTINUE;
11137 for (Typed_identifier_list::const_iterator p = methods->begin();
11138 p != methods->end();
11139 ++p)
11140 if (p->name().empty() && p->type()->named_type() == this->find_type_)
11142 this->found_ = true;
11143 return TRAVERSE_EXIT;
11147 return TRAVERSE_CONTINUE;
11150 // Verify that a named type does not refer to itself.
11152 bool
11153 Named_type::do_verify(Gogo*)
11155 if (this->is_verified_)
11156 return true;
11157 this->is_verified_ = true;
11159 if (this->is_error_)
11160 return false;
11162 if (this->is_alias_)
11164 Find_alias find(this);
11165 Type::traverse(this->type_, &find);
11166 if (find.found())
11168 go_error_at(this->location_, "invalid recursive alias %qs",
11169 this->message_name().c_str());
11170 this->is_error_ = true;
11171 return false;
11175 Find_type_use find(this);
11176 Type::traverse(this->type_, &find);
11177 if (find.found())
11179 go_error_at(this->location_, "invalid recursive type %qs",
11180 this->message_name().c_str());
11181 this->is_error_ = true;
11182 return false;
11185 // Check whether any of the local methods overloads an existing
11186 // struct field or interface method. We don't need to check the
11187 // list of methods against itself: that is handled by the Bindings
11188 // code.
11189 if (this->local_methods_ != NULL)
11191 Struct_type* st = this->type_->struct_type();
11192 if (st != NULL)
11194 for (Bindings::const_declarations_iterator p =
11195 this->local_methods_->begin_declarations();
11196 p != this->local_methods_->end_declarations();
11197 ++p)
11199 const std::string& name(p->first);
11200 if (st != NULL && st->find_local_field(name, NULL) != NULL)
11202 go_error_at(p->second->location(),
11203 "method %qs redeclares struct field name",
11204 Gogo::message_name(name).c_str());
11210 return true;
11213 // Return whether this type is or contains a pointer.
11215 bool
11216 Named_type::do_has_pointer() const
11218 // A type that is not in the heap has no pointers that we care about.
11219 if (!this->in_heap_)
11220 return false;
11222 if (this->seen_)
11223 return false;
11224 this->seen_ = true;
11225 bool ret = this->type_->has_pointer();
11226 this->seen_ = false;
11227 return ret;
11230 // Return whether comparisons for this type can use the identity
11231 // function.
11233 bool
11234 Named_type::do_compare_is_identity(Gogo* gogo)
11236 // We don't use this->seen_ here because compare_is_identity may
11237 // call base() later, and that will mess up if seen_ is set here.
11238 if (this->seen_in_compare_is_identity_)
11239 return false;
11240 this->seen_in_compare_is_identity_ = true;
11241 bool ret = this->type_->compare_is_identity(gogo);
11242 this->seen_in_compare_is_identity_ = false;
11243 return ret;
11246 // Return whether this type is reflexive--whether it is always equal
11247 // to itself.
11249 bool
11250 Named_type::do_is_reflexive()
11252 if (this->seen_in_compare_is_identity_)
11253 return false;
11254 this->seen_in_compare_is_identity_ = true;
11255 bool ret = this->type_->is_reflexive();
11256 this->seen_in_compare_is_identity_ = false;
11257 return ret;
11260 // Return whether this type needs a key update when used as a map key.
11262 bool
11263 Named_type::do_needs_key_update()
11265 if (this->seen_in_compare_is_identity_)
11266 return true;
11267 this->seen_in_compare_is_identity_ = true;
11268 bool ret = this->type_->needs_key_update();
11269 this->seen_in_compare_is_identity_ = false;
11270 return ret;
11273 // Return whether this type is permitted in the heap.
11274 bool
11275 Named_type::do_in_heap() const
11277 if (!this->in_heap_)
11278 return false;
11279 if (this->seen_)
11280 return true;
11281 this->seen_ = true;
11282 bool ret = this->type_->in_heap();
11283 this->seen_ = false;
11284 return ret;
11287 // Return a hash code. This is used for method lookup. We simply
11288 // hash on the name itself.
11290 unsigned int
11291 Named_type::do_hash_for_method(Gogo* gogo, int) const
11293 if (this->is_error_)
11294 return 0;
11296 // Aliases are handled in Type::hash_for_method.
11297 go_assert(!this->is_alias_);
11299 const std::string& name(this->named_object()->name());
11300 unsigned int ret = Gogo::hash_string(name, 0);
11302 // GOGO will be NULL here when called from Type_hash_identical.
11303 // That is OK because that is only used for internal hash tables
11304 // where we are going to be comparing named types for equality. In
11305 // other cases, which are cases where the runtime is going to
11306 // compare hash codes to see if the types are the same, we need to
11307 // include the pkgpath in the hash.
11308 if (gogo != NULL && !Gogo::is_hidden_name(name) && !this->is_builtin())
11310 const Package* package = this->named_object()->package();
11311 if (package == NULL)
11312 ret = Gogo::hash_string(gogo->pkgpath(), ret);
11313 else
11314 ret = Gogo::hash_string(package->pkgpath(), ret);
11317 return ret;
11320 // Convert a named type to the backend representation. In order to
11321 // get dependencies right, we fill in a dummy structure for this type,
11322 // then convert all the dependencies, then complete this type. When
11323 // this function is complete, the size of the type is known.
11325 void
11326 Named_type::convert(Gogo* gogo)
11328 if (this->is_error_ || this->is_converted_)
11329 return;
11331 this->create_placeholder(gogo);
11333 // If we are called to turn unsafe.Sizeof into a constant, we may
11334 // not have verified the type yet. We have to make sure it is
11335 // verified, since that sets the list of dependencies.
11336 this->verify(gogo);
11338 // Convert all the dependencies. If they refer indirectly back to
11339 // this type, they will pick up the intermediate representation we just
11340 // created.
11341 for (std::vector<Named_type*>::const_iterator p = this->dependencies_.begin();
11342 p != this->dependencies_.end();
11343 ++p)
11344 (*p)->convert(gogo);
11346 // Complete this type.
11347 Btype* bt = this->named_btype_;
11348 Type* base = this->type_->base();
11349 switch (base->classification())
11351 case TYPE_VOID:
11352 case TYPE_BOOLEAN:
11353 case TYPE_INTEGER:
11354 case TYPE_FLOAT:
11355 case TYPE_COMPLEX:
11356 case TYPE_STRING:
11357 case TYPE_NIL:
11358 break;
11360 case TYPE_MAP:
11361 case TYPE_CHANNEL:
11362 break;
11364 case TYPE_FUNCTION:
11365 case TYPE_POINTER:
11366 // The size of these types is already correct. We don't worry
11367 // about filling them in until later, when we also track
11368 // circular references.
11369 break;
11371 case TYPE_STRUCT:
11373 std::vector<Backend::Btyped_identifier> bfields;
11374 get_backend_struct_fields(gogo, base->struct_type(), true, &bfields);
11375 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
11376 bt = gogo->backend()->error_type();
11378 break;
11380 case TYPE_ARRAY:
11381 // Slice types were completed in create_placeholder.
11382 if (!base->is_slice_type())
11384 Btype* bet = base->array_type()->get_backend_element(gogo, true);
11385 Bexpression* blen = base->array_type()->get_backend_length(gogo);
11386 if (!gogo->backend()->set_placeholder_array_type(bt, bet, blen))
11387 bt = gogo->backend()->error_type();
11389 break;
11391 case TYPE_INTERFACE:
11392 // Interface types were completed in create_placeholder.
11393 break;
11395 case TYPE_ERROR:
11396 return;
11398 default:
11399 case TYPE_SINK:
11400 case TYPE_CALL_MULTIPLE_RESULT:
11401 case TYPE_NAMED:
11402 case TYPE_FORWARD:
11403 go_unreachable();
11406 this->named_btype_ = bt;
11407 this->is_converted_ = true;
11408 this->is_placeholder_ = false;
11411 // Create the placeholder for a named type. This is the first step in
11412 // converting to the backend representation.
11414 void
11415 Named_type::create_placeholder(Gogo* gogo)
11417 if (this->is_error_)
11418 this->named_btype_ = gogo->backend()->error_type();
11420 if (this->named_btype_ != NULL)
11421 return;
11423 // Create the structure for this type. Note that because we call
11424 // base() here, we don't attempt to represent a named type defined
11425 // as another named type. Instead both named types will point to
11426 // different base representations.
11427 Type* base = this->type_->base();
11428 Btype* bt;
11429 bool set_name = true;
11430 switch (base->classification())
11432 case TYPE_ERROR:
11433 this->is_error_ = true;
11434 this->named_btype_ = gogo->backend()->error_type();
11435 return;
11437 case TYPE_VOID:
11438 case TYPE_BOOLEAN:
11439 case TYPE_INTEGER:
11440 case TYPE_FLOAT:
11441 case TYPE_COMPLEX:
11442 case TYPE_STRING:
11443 case TYPE_NIL:
11444 // These are simple basic types, we can just create them
11445 // directly.
11446 bt = Type::get_named_base_btype(gogo, base);
11447 break;
11449 case TYPE_MAP:
11450 case TYPE_CHANNEL:
11451 // All maps and channels have the same backend representation.
11452 bt = Type::get_named_base_btype(gogo, base);
11453 break;
11455 case TYPE_FUNCTION:
11456 case TYPE_POINTER:
11458 bool for_function = base->classification() == TYPE_FUNCTION;
11459 bt = gogo->backend()->placeholder_pointer_type(this->name(),
11460 this->location_,
11461 for_function);
11462 set_name = false;
11464 break;
11466 case TYPE_STRUCT:
11467 bt = gogo->backend()->placeholder_struct_type(this->name(),
11468 this->location_);
11469 this->is_placeholder_ = true;
11470 set_name = false;
11471 break;
11473 case TYPE_ARRAY:
11474 if (base->is_slice_type())
11475 bt = gogo->backend()->placeholder_struct_type(this->name(),
11476 this->location_);
11477 else
11479 bt = gogo->backend()->placeholder_array_type(this->name(),
11480 this->location_);
11481 this->is_placeholder_ = true;
11483 set_name = false;
11484 break;
11486 case TYPE_INTERFACE:
11487 if (base->interface_type()->is_empty())
11488 bt = Interface_type::get_backend_empty_interface_type(gogo);
11489 else
11491 bt = gogo->backend()->placeholder_struct_type(this->name(),
11492 this->location_);
11493 set_name = false;
11495 break;
11497 default:
11498 case TYPE_SINK:
11499 case TYPE_CALL_MULTIPLE_RESULT:
11500 case TYPE_NAMED:
11501 case TYPE_FORWARD:
11502 go_unreachable();
11505 if (set_name)
11506 bt = gogo->backend()->named_type(this->name(), bt, this->location_);
11508 this->named_btype_ = bt;
11510 if (base->is_slice_type())
11512 // We do not record slices as dependencies of other types,
11513 // because we can fill them in completely here with the final
11514 // size.
11515 std::vector<Backend::Btyped_identifier> bfields;
11516 get_backend_slice_fields(gogo, base->array_type(), true, &bfields);
11517 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
11518 this->named_btype_ = gogo->backend()->error_type();
11520 else if (base->interface_type() != NULL
11521 && !base->interface_type()->is_empty())
11523 // We do not record interfaces as dependencies of other types,
11524 // because we can fill them in completely here with the final
11525 // size.
11526 std::vector<Backend::Btyped_identifier> bfields;
11527 get_backend_interface_fields(gogo, base->interface_type(), true,
11528 &bfields);
11529 if (!gogo->backend()->set_placeholder_struct_type(bt, bfields))
11530 this->named_btype_ = gogo->backend()->error_type();
11534 // Get the backend representation for a named type.
11536 Btype*
11537 Named_type::do_get_backend(Gogo* gogo)
11539 if (this->is_error_)
11540 return gogo->backend()->error_type();
11542 Btype* bt = this->named_btype_;
11544 if (!gogo->named_types_are_converted())
11546 // We have not completed converting named types. NAMED_BTYPE_
11547 // is a placeholder and we shouldn't do anything further.
11548 if (bt != NULL)
11549 return bt;
11551 // We don't build dependencies for types whose sizes do not
11552 // change or are not relevant, so we may see them here while
11553 // converting types.
11554 this->create_placeholder(gogo);
11555 bt = this->named_btype_;
11556 go_assert(bt != NULL);
11557 return bt;
11560 // We are not converting types. This should only be called if the
11561 // type has already been converted.
11562 if (!this->is_converted_)
11564 go_assert(saw_errors());
11565 return gogo->backend()->error_type();
11568 go_assert(bt != NULL);
11570 // Complete the backend representation.
11571 Type* base = this->type_->base();
11572 Btype* bt1;
11573 switch (base->classification())
11575 case TYPE_ERROR:
11576 return gogo->backend()->error_type();
11578 case TYPE_VOID:
11579 case TYPE_BOOLEAN:
11580 case TYPE_INTEGER:
11581 case TYPE_FLOAT:
11582 case TYPE_COMPLEX:
11583 case TYPE_STRING:
11584 case TYPE_NIL:
11585 case TYPE_MAP:
11586 case TYPE_CHANNEL:
11587 return bt;
11589 case TYPE_STRUCT:
11590 if (!this->seen_in_get_backend_)
11592 this->seen_in_get_backend_ = true;
11593 base->struct_type()->finish_backend_fields(gogo);
11594 this->seen_in_get_backend_ = false;
11596 return bt;
11598 case TYPE_ARRAY:
11599 if (!this->seen_in_get_backend_)
11601 this->seen_in_get_backend_ = true;
11602 base->array_type()->finish_backend_element(gogo);
11603 this->seen_in_get_backend_ = false;
11605 return bt;
11607 case TYPE_INTERFACE:
11608 if (!this->seen_in_get_backend_)
11610 this->seen_in_get_backend_ = true;
11611 base->interface_type()->finish_backend_methods(gogo);
11612 this->seen_in_get_backend_ = false;
11614 return bt;
11616 case TYPE_FUNCTION:
11617 // Don't build a circular data structure. GENERIC can't handle
11618 // it.
11619 if (this->seen_in_get_backend_)
11620 return gogo->backend()->circular_pointer_type(bt, true);
11621 this->seen_in_get_backend_ = true;
11622 bt1 = Type::get_named_base_btype(gogo, base);
11623 this->seen_in_get_backend_ = false;
11624 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11625 bt = gogo->backend()->error_type();
11626 return bt;
11628 case TYPE_POINTER:
11629 // Don't build a circular data structure. GENERIC can't handle
11630 // it.
11631 if (this->seen_in_get_backend_)
11632 return gogo->backend()->circular_pointer_type(bt, false);
11633 this->seen_in_get_backend_ = true;
11634 bt1 = Type::get_named_base_btype(gogo, base);
11635 this->seen_in_get_backend_ = false;
11636 if (!gogo->backend()->set_placeholder_pointer_type(bt, bt1))
11637 bt = gogo->backend()->error_type();
11638 return bt;
11640 default:
11641 case TYPE_SINK:
11642 case TYPE_CALL_MULTIPLE_RESULT:
11643 case TYPE_NAMED:
11644 case TYPE_FORWARD:
11645 go_unreachable();
11648 go_unreachable();
11651 // Build a type descriptor for a named type.
11653 Expression*
11654 Named_type::do_type_descriptor(Gogo* gogo, Named_type* name)
11656 if (this->is_error_)
11657 return Expression::make_error(this->location_);
11659 // We shouldn't see unnamed type aliases here. They should have
11660 // been removed by the call to unalias in Type::type_descriptor_pointer.
11661 // We can see named type aliases via Type::named_type_descriptor.
11662 go_assert(name != NULL || !this->is_alias_);
11664 // If NAME is not NULL, then we don't really want the type
11665 // descriptor for this type; we want the descriptor for the
11666 // underlying type, giving it the name NAME.
11667 return this->named_type_descriptor(gogo, this->type_,
11668 name == NULL ? this : name);
11671 // Add to the reflection string. This is used mostly for the name of
11672 // the type used in a type descriptor, not for actual reflection
11673 // strings.
11675 void
11676 Named_type::do_reflection(Gogo* gogo, std::string* ret) const
11678 this->append_reflection_type_name(gogo, false, ret);
11681 // Add to the reflection string. For an alias we normally use the
11682 // real name, but if USE_ALIAS is true we use the alias name itself.
11684 void
11685 Named_type::append_reflection_type_name(Gogo* gogo, bool use_alias,
11686 std::string* ret) const
11688 if (this->is_error_)
11689 return;
11690 if (this->is_alias_ && !use_alias)
11692 if (this->seen_alias_)
11693 return;
11694 this->seen_alias_ = true;
11695 this->append_reflection(this->type_, gogo, ret);
11696 this->seen_alias_ = false;
11697 return;
11699 if (!this->is_builtin())
11701 // When -fgo-pkgpath or -fgo-prefix is specified, we use it to
11702 // make a unique reflection string, so that the type
11703 // canonicalization in the reflect package will work. In order
11704 // to be compatible with the gc compiler, we put tabs into the
11705 // package path, so that the reflect methods can discard it.
11706 const Package* package = this->named_object_->package();
11707 ret->push_back('\t');
11708 ret->append(package != NULL
11709 ? package->pkgpath_symbol()
11710 : gogo->pkgpath_symbol());
11711 ret->push_back('\t');
11712 ret->append(package != NULL
11713 ? package->package_name()
11714 : gogo->package_name());
11715 ret->push_back('.');
11717 if (this->in_function_ != NULL)
11719 ret->push_back('\t');
11720 const Typed_identifier* rcvr =
11721 this->in_function_->func_value()->type()->receiver();
11722 if (rcvr != NULL)
11724 Named_type* rcvr_type = rcvr->type()->deref()->named_type();
11725 ret->append(Gogo::unpack_hidden_name(rcvr_type->name()));
11726 ret->push_back('.');
11728 ret->append(Gogo::unpack_hidden_name(this->in_function_->name()));
11729 ret->push_back('$');
11730 if (this->in_function_index_ > 0)
11732 char buf[30];
11733 snprintf(buf, sizeof buf, "%u", this->in_function_index_);
11734 ret->append(buf);
11735 ret->push_back('$');
11737 ret->push_back('\t');
11739 ret->append(Gogo::unpack_hidden_name(this->named_object_->name()));
11742 // Import a named type. This is only used for export format versions
11743 // before version 3.
11745 void
11746 Named_type::import_named_type(Import* imp, Named_type** ptype)
11748 imp->require_c_string("type ");
11749 Type *type = imp->read_type();
11750 *ptype = type->named_type();
11751 go_assert(*ptype != NULL);
11752 imp->require_semicolon_if_old_version();
11753 imp->require_c_string("\n");
11756 // Export the type when it is referenced by another type. In this
11757 // case Export::export_type will already have issued the name. The
11758 // output always ends with a newline, since that is convenient if
11759 // there are methods.
11761 void
11762 Named_type::do_export(Export* exp) const
11764 exp->write_type(this->type_);
11765 exp->write_c_string("\n");
11767 // To save space, we only export the methods directly attached to
11768 // this type.
11769 Bindings* methods = this->local_methods_;
11770 if (methods == NULL)
11771 return;
11773 for (Bindings::const_definitions_iterator p = methods->begin_definitions();
11774 p != methods->end_definitions();
11775 ++p)
11777 exp->write_c_string(" ");
11778 (*p)->export_named_object(exp);
11781 for (Bindings::const_declarations_iterator p = methods->begin_declarations();
11782 p != methods->end_declarations();
11783 ++p)
11785 if (p->second->is_function_declaration())
11787 exp->write_c_string(" ");
11788 p->second->export_named_object(exp);
11793 // Make a named type.
11795 Named_type*
11796 Type::make_named_type(Named_object* named_object, Type* type,
11797 Location location)
11799 return new Named_type(named_object, type, location);
11802 // Finalize the methods for TYPE. It will be a named type or a struct
11803 // type. This sets *ALL_METHODS to the list of methods, and builds
11804 // all required stubs.
11806 void
11807 Type::finalize_methods(Gogo* gogo, const Type* type, Location location,
11808 Methods** all_methods)
11810 *all_methods = new Methods();
11811 std::vector<const Named_type*> seen;
11812 Type::add_methods_for_type(type, NULL, 0, false, false, &seen, *all_methods);
11813 if ((*all_methods)->empty())
11815 delete *all_methods;
11816 *all_methods = NULL;
11818 Type::build_stub_methods(gogo, type, *all_methods, location);
11819 if (type->is_direct_iface_type() || !type->in_heap())
11820 Type::build_direct_iface_stub_methods(gogo, type, *all_methods, location);
11823 // Add the methods for TYPE to *METHODS. FIELD_INDEXES is used to
11824 // build up the struct field indexes as we go. DEPTH is the depth of
11825 // the field within TYPE. IS_EMBEDDED_POINTER is true if we are
11826 // adding these methods for an anonymous field with pointer type.
11827 // NEEDS_STUB_METHOD is true if we need to use a stub method which
11828 // calls the real method. TYPES_SEEN is used to avoid infinite
11829 // recursion.
11831 void
11832 Type::add_methods_for_type(const Type* type,
11833 const Method::Field_indexes* field_indexes,
11834 unsigned int depth,
11835 bool is_embedded_pointer,
11836 bool needs_stub_method,
11837 std::vector<const Named_type*>* seen,
11838 Methods* methods)
11840 // Pointer types may not have methods.
11841 if (type->points_to() != NULL)
11842 return;
11844 const Named_type* nt = type->named_type();
11845 if (nt != NULL)
11847 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
11848 p != seen->end();
11849 ++p)
11851 if (*p == nt)
11852 return;
11855 seen->push_back(nt);
11857 Type::add_local_methods_for_type(nt, field_indexes, depth,
11858 is_embedded_pointer, needs_stub_method,
11859 methods);
11862 Type::add_embedded_methods_for_type(type, field_indexes, depth,
11863 is_embedded_pointer, needs_stub_method,
11864 seen, methods);
11866 // If we are called with depth > 0, then we are looking at an
11867 // anonymous field of a struct. If such a field has interface type,
11868 // then we need to add the interface methods. We don't want to add
11869 // them when depth == 0, because we will already handle them
11870 // following the usual rules for an interface type.
11871 if (depth > 0)
11872 Type::add_interface_methods_for_type(type, field_indexes, depth, methods);
11874 if (nt != NULL)
11875 seen->pop_back();
11878 // Add the local methods for the named type NT to *METHODS. The
11879 // parameters are as for add_methods_to_type.
11881 void
11882 Type::add_local_methods_for_type(const Named_type* nt,
11883 const Method::Field_indexes* field_indexes,
11884 unsigned int depth,
11885 bool is_embedded_pointer,
11886 bool needs_stub_method,
11887 Methods* methods)
11889 const Bindings* local_methods = nt->local_methods();
11890 if (local_methods == NULL)
11891 return;
11893 for (Bindings::const_declarations_iterator p =
11894 local_methods->begin_declarations();
11895 p != local_methods->end_declarations();
11896 ++p)
11898 Named_object* no = p->second;
11899 bool is_value_method = (is_embedded_pointer
11900 || !Type::method_expects_pointer(no));
11901 Method* m = new Named_method(no, field_indexes, depth, is_value_method,
11902 (needs_stub_method || depth > 0));
11903 if (!methods->insert(no->name(), m))
11904 delete m;
11908 // Add the embedded methods for TYPE to *METHODS. These are the
11909 // methods attached to anonymous fields. The parameters are as for
11910 // add_methods_to_type.
11912 void
11913 Type::add_embedded_methods_for_type(const Type* type,
11914 const Method::Field_indexes* field_indexes,
11915 unsigned int depth,
11916 bool is_embedded_pointer,
11917 bool needs_stub_method,
11918 std::vector<const Named_type*>* seen,
11919 Methods* methods)
11921 // Look for anonymous fields in TYPE. TYPE has fields if it is a
11922 // struct.
11923 const Struct_type* st = type->struct_type();
11924 if (st == NULL)
11925 return;
11927 const Struct_field_list* fields = st->fields();
11928 if (fields == NULL)
11929 return;
11931 unsigned int i = 0;
11932 for (Struct_field_list::const_iterator pf = fields->begin();
11933 pf != fields->end();
11934 ++pf, ++i)
11936 if (!pf->is_anonymous())
11937 continue;
11939 Type* ftype = pf->type();
11940 bool is_pointer = false;
11941 if (ftype->points_to() != NULL)
11943 ftype = ftype->points_to();
11944 is_pointer = true;
11946 Named_type* fnt = ftype->named_type();
11947 if (fnt == NULL)
11949 // This is an error, but it will be diagnosed elsewhere.
11950 continue;
11953 Method::Field_indexes* sub_field_indexes = new Method::Field_indexes();
11954 sub_field_indexes->next = field_indexes;
11955 sub_field_indexes->field_index = i;
11957 Methods tmp_methods;
11958 Type::add_methods_for_type(fnt, sub_field_indexes, depth + 1,
11959 (is_embedded_pointer || is_pointer),
11960 (needs_stub_method
11961 || is_pointer
11962 || i > 0),
11963 seen,
11964 &tmp_methods);
11965 // Check if there are promoted methods that conflict with field names and
11966 // don't add them to the method map.
11967 for (Methods::const_iterator p = tmp_methods.begin();
11968 p != tmp_methods.end();
11969 ++p)
11971 bool found = false;
11972 for (Struct_field_list::const_iterator fp = fields->begin();
11973 fp != fields->end();
11974 ++fp)
11976 if (fp->field_name() == p->first)
11978 found = true;
11979 break;
11982 if (!found &&
11983 !methods->insert(p->first, p->second))
11984 delete p->second;
11989 // If TYPE is an interface type, then add its method to *METHODS.
11990 // This is for interface methods attached to an anonymous field. The
11991 // parameters are as for add_methods_for_type.
11993 void
11994 Type::add_interface_methods_for_type(const Type* type,
11995 const Method::Field_indexes* field_indexes,
11996 unsigned int depth,
11997 Methods* methods)
11999 const Interface_type* it = type->interface_type();
12000 if (it == NULL)
12001 return;
12003 const Typed_identifier_list* imethods = it->methods();
12004 if (imethods == NULL)
12005 return;
12007 for (Typed_identifier_list::const_iterator pm = imethods->begin();
12008 pm != imethods->end();
12009 ++pm)
12011 Function_type* fntype = pm->type()->function_type();
12012 if (fntype == NULL)
12014 // This is an error, but it should be reported elsewhere
12015 // when we look at the methods for IT.
12016 continue;
12018 go_assert(!fntype->is_method());
12019 fntype = fntype->copy_with_receiver(const_cast<Type*>(type));
12020 Method* m = new Interface_method(pm->name(), pm->location(), fntype,
12021 field_indexes, depth);
12022 if (!methods->insert(pm->name(), m))
12023 delete m;
12027 // Build stub methods for TYPE as needed. METHODS is the set of
12028 // methods for the type. A stub method may be needed when a type
12029 // inherits a method from an anonymous field. When we need the
12030 // address of the method, as in a type descriptor, we need to build a
12031 // little stub which does the required field dereferences and jumps to
12032 // the real method. LOCATION is the location of the type definition.
12034 void
12035 Type::build_stub_methods(Gogo* gogo, const Type* type, const Methods* methods,
12036 Location location)
12038 if (methods == NULL)
12039 return;
12040 for (Methods::const_iterator p = methods->begin();
12041 p != methods->end();
12042 ++p)
12044 Method* m = p->second;
12045 if (m->is_ambiguous() || !m->needs_stub_method())
12046 continue;
12048 const std::string& name(p->first);
12050 // Build a stub method.
12052 const Function_type* fntype = m->type();
12054 static unsigned int counter;
12055 char buf[100];
12056 snprintf(buf, sizeof buf, "$this%u", counter);
12057 ++counter;
12059 Type* receiver_type = const_cast<Type*>(type);
12060 if (!m->is_value_method())
12061 receiver_type = Type::make_pointer_type(receiver_type);
12062 Location receiver_location = m->receiver_location();
12063 Typed_identifier* receiver = new Typed_identifier(buf, receiver_type,
12064 receiver_location);
12066 const Typed_identifier_list* fnparams = fntype->parameters();
12067 Typed_identifier_list* stub_params;
12068 if (fnparams == NULL || fnparams->empty())
12069 stub_params = NULL;
12070 else
12072 // We give each stub parameter a unique name.
12073 stub_params = new Typed_identifier_list();
12074 for (Typed_identifier_list::const_iterator pp = fnparams->begin();
12075 pp != fnparams->end();
12076 ++pp)
12078 char pbuf[100];
12079 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
12080 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
12081 pp->location()));
12082 ++counter;
12086 const Typed_identifier_list* fnresults = fntype->results();
12087 Typed_identifier_list* stub_results;
12088 if (fnresults == NULL || fnresults->empty())
12089 stub_results = NULL;
12090 else
12092 // We create the result parameters without any names, since
12093 // we won't refer to them.
12094 stub_results = new Typed_identifier_list();
12095 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
12096 pr != fnresults->end();
12097 ++pr)
12098 stub_results->push_back(Typed_identifier("", pr->type(),
12099 pr->location()));
12102 Function_type* stub_type = Type::make_function_type(receiver,
12103 stub_params,
12104 stub_results,
12105 fntype->location());
12106 if (fntype->is_varargs())
12107 stub_type->set_is_varargs();
12109 // We only create the function in the package which creates the
12110 // type.
12111 const Package* package;
12112 if (type->named_type() == NULL)
12113 package = NULL;
12114 else
12115 package = type->named_type()->named_object()->package();
12116 std::string stub_name = gogo->stub_method_name(package, name);
12117 Named_object* stub;
12118 if (package != NULL)
12119 stub = Named_object::make_function_declaration(stub_name, package,
12120 stub_type, location);
12121 else
12123 stub = gogo->start_function(stub_name, stub_type, false,
12124 fntype->location());
12125 Type::build_one_stub_method(gogo, m, stub, buf, receiver_type,
12126 stub_params, fntype->is_varargs(),
12127 stub_results, location);
12128 gogo->finish_function(fntype->location());
12130 if (type->named_type() == NULL && stub->is_function())
12131 stub->func_value()->set_is_unnamed_type_stub_method();
12132 if (m->nointerface() && stub->is_function())
12133 stub->func_value()->set_nointerface();
12136 m->set_stub_object(stub);
12140 // Build a stub method which adjusts the receiver as required to call
12141 // METHOD. RECEIVER_NAME is the name we used for the receiver.
12142 // PARAMS is the list of function parameters.
12144 void
12145 Type::build_one_stub_method(Gogo* gogo, Method* method,
12146 Named_object* stub,
12147 const char* receiver_name,
12148 const Type* receiver_type,
12149 const Typed_identifier_list* params,
12150 bool is_varargs,
12151 const Typed_identifier_list* results,
12152 Location location)
12154 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
12155 go_assert(receiver_object != NULL);
12157 Expression* expr = Expression::make_var_reference(receiver_object, location);
12158 const Type* expr_type = receiver_type;
12159 expr = Type::apply_field_indexes(expr, method->field_indexes(), location,
12160 &expr_type);
12161 if (expr_type->points_to() == NULL)
12162 expr = Expression::make_unary(OPERATOR_AND, expr, location);
12164 Expression_list* arguments;
12165 if (params == NULL || params->empty())
12166 arguments = NULL;
12167 else
12169 arguments = new Expression_list();
12170 for (Typed_identifier_list::const_iterator p = params->begin();
12171 p != params->end();
12172 ++p)
12174 Named_object* param = gogo->lookup(p->name(), NULL);
12175 go_assert(param != NULL);
12176 Expression* param_ref = Expression::make_var_reference(param,
12177 location);
12178 arguments->push_back(param_ref);
12182 Expression* func = method->bind_method(expr, location);
12183 go_assert(func != NULL);
12184 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
12185 location);
12186 Type::add_return_from_results(gogo, stub, call, results, location);
12189 // Build direct interface stub methods for TYPE as needed. METHODS
12190 // is the set of methods for the type. LOCATION is the location of
12191 // the type definition.
12193 // This is for an interface holding a pointer to the type and invoking
12194 // a value method. The interface data is the pointer, and is passed
12195 // to the stub, which dereferences it and passes to the actual method.
12197 void
12198 Type::build_direct_iface_stub_methods(Gogo* gogo, const Type* type,
12199 Methods* methods, Location loc)
12201 if (methods == NULL)
12202 return;
12204 bool is_direct_iface = type->is_direct_iface_type();
12205 bool in_heap = type->in_heap();
12206 for (Methods::const_iterator p = methods->begin();
12207 p != methods->end();
12208 ++p)
12210 Method* m = p->second;
12212 // We need a direct-iface stub for a value method for a
12213 // direct-iface type, and for a pointer method for a not-in-heap
12214 // type.
12215 bool need_stub = false;
12216 if (is_direct_iface && m->is_value_method())
12217 need_stub = true;
12218 if (!in_heap && !m->is_value_method())
12219 need_stub = true;
12220 if (!need_stub || m->is_ambiguous())
12221 continue;
12223 Type* receiver_type = const_cast<Type*>(type);
12224 receiver_type = Type::make_pointer_type(receiver_type);
12225 const std::string& name(p->first);
12226 Function_type* fntype = m->type();
12228 static unsigned int counter;
12229 char buf[100];
12230 snprintf(buf, sizeof buf, "$ptr%u", counter);
12231 ++counter;
12232 Typed_identifier* receiver =
12233 new Typed_identifier(buf, receiver_type, m->receiver_location());
12235 const Typed_identifier_list* params = fntype->parameters();
12236 Typed_identifier_list* stub_params;
12237 if (params == NULL || params->empty())
12238 stub_params = NULL;
12239 else
12241 // We give each stub parameter a unique name.
12242 stub_params = new Typed_identifier_list();
12243 for (Typed_identifier_list::const_iterator pp = params->begin();
12244 pp != params->end();
12245 ++pp)
12247 char pbuf[100];
12248 snprintf(pbuf, sizeof pbuf, "$p%u", counter);
12249 stub_params->push_back(Typed_identifier(pbuf, pp->type(),
12250 pp->location()));
12251 ++counter;
12255 const Typed_identifier_list* fnresults = fntype->results();
12256 Typed_identifier_list* stub_results;
12257 if (fnresults == NULL || fnresults->empty())
12258 stub_results = NULL;
12259 else
12261 // We create the result parameters without any names, since
12262 // we won't refer to them.
12263 stub_results = new Typed_identifier_list();
12264 for (Typed_identifier_list::const_iterator pr = fnresults->begin();
12265 pr != fnresults->end();
12266 ++pr)
12267 stub_results->push_back(Typed_identifier("", pr->type(),
12268 pr->location()));
12271 Function_type* stub_type = Type::make_function_type(receiver,
12272 stub_params,
12273 stub_results,
12274 fntype->location());
12275 if (fntype->is_varargs())
12276 stub_type->set_is_varargs();
12278 // We only create the function in the package which creates the
12279 // type.
12280 const Package* package;
12281 if (type->named_type() == NULL)
12282 package = NULL;
12283 else
12284 package = type->named_type()->named_object()->package();
12286 std::string stub_name = gogo->stub_method_name(package, name) + "2";
12287 Named_object* stub;
12288 if (package != NULL)
12289 stub = Named_object::make_function_declaration(stub_name, package,
12290 stub_type, loc);
12291 else
12293 stub = gogo->start_function(stub_name, stub_type, false,
12294 fntype->location());
12295 Type::build_one_iface_stub_method(gogo, m, stub, buf, stub_params,
12296 fntype->is_varargs(), stub_results,
12297 loc);
12298 gogo->finish_function(fntype->location());
12300 if (type->named_type() == NULL && stub->is_function())
12301 stub->func_value()->set_is_unnamed_type_stub_method();
12302 if (m->nointerface() && stub->is_function())
12303 stub->func_value()->set_nointerface();
12306 m->set_iface_stub_object(stub);
12310 // Build a stub method for METHOD of direct interface type T.
12311 // RECEIVER_NAME is the name we used for the receiver.
12312 // PARAMS is the list of function parameters.
12314 // The stub looks like
12316 // func ($ptr *T, PARAMS) {
12317 // (*$ptr).METHOD(PARAMS)
12318 // }
12320 void
12321 Type::build_one_iface_stub_method(Gogo* gogo, Method* method,
12322 Named_object* stub,
12323 const char* receiver_name,
12324 const Typed_identifier_list* params,
12325 bool is_varargs,
12326 const Typed_identifier_list* results,
12327 Location loc)
12329 Named_object* receiver_object = gogo->lookup(receiver_name, NULL);
12330 go_assert(receiver_object != NULL);
12332 Expression* expr = Expression::make_var_reference(receiver_object, loc);
12333 expr = Expression::make_dereference(expr,
12334 Expression::NIL_CHECK_DEFAULT,
12335 loc);
12337 Expression_list* arguments;
12338 if (params == NULL || params->empty())
12339 arguments = NULL;
12340 else
12342 arguments = new Expression_list();
12343 for (Typed_identifier_list::const_iterator p = params->begin();
12344 p != params->end();
12345 ++p)
12347 Named_object* param = gogo->lookup(p->name(), NULL);
12348 go_assert(param != NULL);
12349 Expression* param_ref = Expression::make_var_reference(param,
12350 loc);
12351 arguments->push_back(param_ref);
12355 Expression* func = method->bind_method(expr, loc);
12356 go_assert(func != NULL);
12357 Call_expression* call = Expression::make_call(func, arguments, is_varargs,
12358 loc);
12359 Type::add_return_from_results(gogo, stub, call, results, loc);
12362 // Build and add a return statement from a call expression and a list
12363 // of result parameters. All we need to know is the number of
12364 // results.
12366 void
12367 Type::add_return_from_results(Gogo* gogo, Named_object* stub,
12368 Call_expression* call,
12369 const Typed_identifier_list* results,
12370 Location loc)
12372 Statement* s;
12373 if (results == NULL || results->empty())
12374 s = Statement::make_statement(call, true);
12375 else
12377 Expression_list* vals = new Expression_list();
12378 size_t rc = results->size();
12379 if (rc == 1)
12380 vals->push_back(call);
12381 else
12383 for (size_t i = 0; i < rc; ++i)
12384 vals->push_back(Expression::make_call_result(call, i));
12386 s = Statement::make_return_statement(stub, vals, loc);
12389 s->determine_types(gogo);
12390 gogo->add_statement(s);
12393 // Apply FIELD_INDEXES to EXPR. The field indexes have to be applied
12394 // in reverse order. *PEXPR_TYPE maintains the type of EXPR; we use
12395 // this to avoid calling EXPR->type() before the lowering pass.
12397 Expression*
12398 Type::apply_field_indexes(Expression* expr,
12399 const Method::Field_indexes* field_indexes,
12400 Location location,
12401 const Type** pexpr_type)
12403 if (field_indexes == NULL)
12404 return expr;
12405 expr = Type::apply_field_indexes(expr, field_indexes->next, location,
12406 pexpr_type);
12407 const Type* expr_type = *pexpr_type;
12408 const Struct_type* stype = expr_type->deref()->struct_type();
12409 go_assert(stype != NULL
12410 && field_indexes->field_index < stype->field_count());
12411 if (expr_type->struct_type() == NULL)
12413 go_assert(expr_type->points_to()->struct_type() == stype);
12414 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
12415 location);
12417 *pexpr_type = stype->field(field_indexes->field_index)->type();
12418 return Expression::make_field_reference(expr, field_indexes->field_index,
12419 location);
12422 // Return whether NO is a method for which the receiver is a pointer.
12424 bool
12425 Type::method_expects_pointer(const Named_object* no)
12427 const Function_type *fntype;
12428 if (no->is_function())
12429 fntype = no->func_value()->type();
12430 else if (no->is_function_declaration())
12431 fntype = no->func_declaration_value()->type();
12432 else
12433 go_unreachable();
12434 return fntype->receiver()->type()->points_to() != NULL;
12437 // Given a set of methods for a type, METHODS, return the method NAME,
12438 // or NULL if there isn't one or if it is ambiguous. If IS_AMBIGUOUS
12439 // is not NULL, then set *IS_AMBIGUOUS to true if the method exists
12440 // but is ambiguous (and return NULL).
12442 Method*
12443 Type::method_function(const Methods* methods, const std::string& name,
12444 bool* is_ambiguous)
12446 if (is_ambiguous != NULL)
12447 *is_ambiguous = false;
12448 if (methods == NULL)
12449 return NULL;
12450 Methods::const_iterator p = methods->find(name);
12451 if (p == methods->end())
12452 return NULL;
12453 Method* m = p->second;
12454 if (m->is_ambiguous())
12456 if (is_ambiguous != NULL)
12457 *is_ambiguous = true;
12458 return NULL;
12460 return m;
12463 // Return a pointer to the interface method table for TYPE for the
12464 // interface INTERFACE.
12466 Expression*
12467 Type::interface_method_table(Type* type,
12468 Interface_type *interface,
12469 bool is_pointer,
12470 Interface_method_tables** method_tables,
12471 Interface_method_tables** pointer_tables)
12473 go_assert(!interface->is_empty());
12475 Interface_method_tables** pimt = is_pointer ? method_tables : pointer_tables;
12477 if (*pimt == NULL)
12478 *pimt = new Interface_method_tables(5);
12480 std::pair<Interface_type*, Expression*> val(interface, NULL);
12481 std::pair<Interface_method_tables::iterator, bool> ins = (*pimt)->insert(val);
12483 Location loc = Linemap::predeclared_location();
12484 if (ins.second)
12486 // This is a new entry in the hash table.
12487 go_assert(ins.first->second == NULL);
12488 ins.first->second =
12489 Expression::make_interface_mtable_ref(interface, type, is_pointer, loc);
12491 return Expression::make_unary(OPERATOR_AND, ins.first->second, loc);
12494 // Look for field or method NAME for TYPE. Return an Expression for
12495 // the field or method bound to EXPR. If there is no such field or
12496 // method, give an appropriate error and return an error expression.
12498 Expression*
12499 Type::bind_field_or_method(Gogo* gogo, const Type* type, Expression* expr,
12500 const std::string& name,
12501 Location location)
12503 if (type->deref()->is_error_type())
12504 return Expression::make_error(location);
12506 const Named_type* nt = type->deref()->named_type();
12507 const Struct_type* st = type->deref()->struct_type();
12508 const Interface_type* it = type->interface_type();
12510 // If this is a pointer to a pointer, then it is possible that the
12511 // pointed-to type has methods.
12512 bool dereferenced = false;
12513 if (nt == NULL
12514 && st == NULL
12515 && it == NULL
12516 && type->points_to() != NULL
12517 && type->points_to()->points_to() != NULL)
12519 expr = Expression::make_dereference(expr, Expression::NIL_CHECK_DEFAULT,
12520 location);
12521 type = type->points_to();
12522 if (type->deref()->is_error_type())
12523 return Expression::make_error(location);
12524 nt = type->points_to()->named_type();
12525 st = type->points_to()->struct_type();
12526 dereferenced = true;
12529 bool receiver_can_be_pointer = (expr->type()->points_to() != NULL
12530 || expr->is_addressable());
12531 std::vector<const Named_type*> seen;
12532 bool is_method = false;
12533 bool found_pointer_method = false;
12534 std::string ambig1;
12535 std::string ambig2;
12536 if (Type::find_field_or_method(type, name, receiver_can_be_pointer,
12537 &seen, NULL, &is_method,
12538 &found_pointer_method, &ambig1, &ambig2))
12540 Expression* ret;
12541 if (!is_method)
12543 go_assert(st != NULL);
12544 if (type->struct_type() == NULL)
12546 if (dereferenced)
12548 go_error_at(location, "pointer type has no field %qs",
12549 Gogo::message_name(name).c_str());
12550 return Expression::make_error(location);
12552 go_assert(type->points_to() != NULL);
12553 expr = Expression::make_dereference(expr,
12554 Expression::NIL_CHECK_DEFAULT,
12555 location);
12556 go_assert(expr->type()->struct_type() == st);
12558 ret = st->field_reference(expr, name, location);
12559 if (ret == NULL)
12561 go_error_at(location, "type has no field %qs",
12562 Gogo::message_name(name).c_str());
12563 return Expression::make_error(location);
12566 else if (it != NULL && it->find_method(name) != NULL)
12567 ret = Expression::make_interface_field_reference(expr, name,
12568 location);
12569 else
12571 Method* m;
12572 if (nt != NULL)
12573 m = nt->method_function(name, NULL);
12574 else if (st != NULL)
12575 m = st->method_function(name, NULL);
12576 else
12577 go_unreachable();
12578 go_assert(m != NULL);
12579 if (dereferenced)
12581 go_error_at(location,
12582 "calling method %qs requires explicit dereference",
12583 Gogo::message_name(name).c_str());
12584 return Expression::make_error(location);
12586 if (!m->is_value_method() && expr->type()->points_to() == NULL)
12587 expr = Expression::make_unary(OPERATOR_AND, expr, location);
12588 ret = m->bind_method(expr, location);
12590 go_assert(ret != NULL);
12591 return ret;
12593 else
12595 if (Gogo::is_erroneous_name(name))
12597 // An error was already reported.
12599 else if (!ambig1.empty())
12600 go_error_at(location, "%qs is ambiguous via %qs and %qs",
12601 Gogo::message_name(name).c_str(), ambig1.c_str(),
12602 ambig2.c_str());
12603 else if (found_pointer_method)
12604 go_error_at(location, "method requires a pointer receiver");
12605 else if (it != NULL && it->is_empty())
12606 go_error_at(location,
12607 "reference to method %qs in interface with no methods",
12608 Gogo::message_name(name).c_str());
12609 else if (it == NULL && type->deref()->interface_type() != NULL)
12610 go_error_at(location,
12611 ("reference to method %qs in type that is "
12612 "pointer to interface, not interface"),
12613 Gogo::message_name(name).c_str());
12614 else if (nt == NULL && st == NULL && it == NULL)
12615 go_error_at(location,
12616 ("reference to field %qs in object which "
12617 "has no fields or methods"),
12618 Gogo::message_name(name).c_str());
12619 else
12621 bool is_unexported;
12622 // The test for 'a' and 'z' is to handle builtin names,
12623 // which are not hidden.
12624 if (!Gogo::is_hidden_name(name) && (name[0] < 'a' || name[0] > 'z'))
12625 is_unexported = false;
12626 else
12628 std::string unpacked = Gogo::unpack_hidden_name(name);
12629 seen.clear();
12630 is_unexported = Type::is_unexported_field_or_method(gogo, type,
12631 unpacked,
12632 &seen);
12634 if (is_unexported)
12635 go_error_at(location, "reference to unexported field or method %qs",
12636 Gogo::message_name(name).c_str());
12637 else
12638 go_error_at(location, "reference to undefined field or method %qs",
12639 Gogo::message_name(name).c_str());
12641 return Expression::make_error(location);
12645 // Look in TYPE for a field or method named NAME, return true if one
12646 // is found. This looks through embedded anonymous fields and handles
12647 // ambiguity. If a method is found, sets *IS_METHOD to true;
12648 // otherwise, if a field is found, set it to false. If
12649 // RECEIVER_CAN_BE_POINTER is false, then the receiver is a value
12650 // whose address can not be taken. SEEN is used to avoid infinite
12651 // recursion on invalid types.
12653 // When returning false, this sets *FOUND_POINTER_METHOD if we found a
12654 // method we couldn't use because it requires a pointer. LEVEL is
12655 // used for recursive calls, and can be NULL for a non-recursive call.
12656 // When this function returns false because it finds that the name is
12657 // ambiguous, it will store a path to the ambiguous names in *AMBIG1
12658 // and *AMBIG2. If the name is not found at all, *AMBIG1 and *AMBIG2
12659 // will be unchanged.
12661 // This function just returns whether or not there is a field or
12662 // method, and whether it is a field or method. It doesn't build an
12663 // expression to refer to it. If it is a method, we then look in the
12664 // list of all methods for the type. If it is a field, the search has
12665 // to be done again, looking only for fields, and building up the
12666 // expression as we go.
12668 bool
12669 Type::find_field_or_method(const Type* type,
12670 const std::string& name,
12671 bool receiver_can_be_pointer,
12672 std::vector<const Named_type*>* seen,
12673 int* level,
12674 bool* is_method,
12675 bool* found_pointer_method,
12676 std::string* ambig1,
12677 std::string* ambig2)
12679 // Named types can have locally defined methods.
12680 const Named_type* nt = type->unalias()->named_type();
12681 if (nt == NULL && type->points_to() != NULL)
12682 nt = type->points_to()->unalias()->named_type();
12683 if (nt != NULL)
12685 Named_object* no = nt->find_local_method(name);
12686 if (no != NULL)
12688 if (receiver_can_be_pointer || !Type::method_expects_pointer(no))
12690 *is_method = true;
12691 return true;
12694 // Record that we have found a pointer method in order to
12695 // give a better error message if we don't find anything
12696 // else.
12697 *found_pointer_method = true;
12700 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12701 p != seen->end();
12702 ++p)
12704 if (*p == nt)
12706 // We've already seen this type when searching for methods.
12707 return false;
12712 // Interface types can have methods.
12713 const Interface_type* it = type->interface_type();
12714 if (it != NULL && it->find_method(name) != NULL)
12716 *is_method = true;
12717 return true;
12720 // Struct types can have fields. They can also inherit fields and
12721 // methods from anonymous fields.
12722 const Struct_type* st = type->deref()->struct_type();
12723 if (st == NULL)
12724 return false;
12725 const Struct_field_list* fields = st->fields();
12726 if (fields == NULL)
12727 return false;
12729 if (nt != NULL)
12730 seen->push_back(nt);
12732 int found_level = 0;
12733 bool found_is_method = false;
12734 std::string found_ambig1;
12735 std::string found_ambig2;
12736 const Struct_field* found_parent = NULL;
12737 for (Struct_field_list::const_iterator pf = fields->begin();
12738 pf != fields->end();
12739 ++pf)
12741 if (pf->is_field_name(name))
12743 *is_method = false;
12744 if (nt != NULL)
12745 seen->pop_back();
12746 return true;
12749 if (!pf->is_anonymous())
12750 continue;
12752 if (pf->type()->deref()->is_error_type()
12753 || pf->type()->deref()->is_undefined())
12754 continue;
12756 Named_type* fnt = pf->type()->named_type();
12757 if (fnt == NULL)
12758 fnt = pf->type()->deref()->named_type();
12759 go_assert(fnt != NULL);
12761 // Methods with pointer receivers on embedded field are
12762 // inherited by the pointer to struct, and also by the struct
12763 // type if the field itself is a pointer.
12764 bool can_be_pointer = (receiver_can_be_pointer
12765 || pf->type()->points_to() != NULL);
12766 int sublevel = level == NULL ? 1 : *level + 1;
12767 bool sub_is_method;
12768 std::string subambig1;
12769 std::string subambig2;
12770 bool subfound = Type::find_field_or_method(fnt,
12771 name,
12772 can_be_pointer,
12773 seen,
12774 &sublevel,
12775 &sub_is_method,
12776 found_pointer_method,
12777 &subambig1,
12778 &subambig2);
12779 if (!subfound)
12781 if (!subambig1.empty())
12783 // The name was found via this field, but is ambiguous.
12784 // if the ambiguity is lower or at the same level as
12785 // anything else we have already found, then we want to
12786 // pass the ambiguity back to the caller.
12787 if (found_level == 0 || sublevel <= found_level)
12789 found_ambig1 = (Gogo::message_name(pf->field_name())
12790 + '.' + subambig1);
12791 found_ambig2 = (Gogo::message_name(pf->field_name())
12792 + '.' + subambig2);
12793 found_level = sublevel;
12797 else
12799 // The name was found via this field. Use the level to see
12800 // if we want to use this one, or whether it introduces an
12801 // ambiguity.
12802 if (found_level == 0 || sublevel < found_level)
12804 found_level = sublevel;
12805 found_is_method = sub_is_method;
12806 found_ambig1.clear();
12807 found_ambig2.clear();
12808 found_parent = &*pf;
12810 else if (sublevel > found_level)
12812 else if (found_ambig1.empty())
12814 // We found an ambiguity.
12815 go_assert(found_parent != NULL);
12816 found_ambig1 = Gogo::message_name(found_parent->field_name());
12817 found_ambig2 = Gogo::message_name(pf->field_name());
12819 else
12821 // We found an ambiguity, but we already know of one.
12822 // Just report the earlier one.
12827 // Here if we didn't find anything FOUND_LEVEL is 0. If we found
12828 // something ambiguous, FOUND_LEVEL is not 0 and FOUND_AMBIG1 and
12829 // FOUND_AMBIG2 are not empty. If we found the field, FOUND_LEVEL
12830 // is not 0 and FOUND_AMBIG1 and FOUND_AMBIG2 are empty.
12832 if (nt != NULL)
12833 seen->pop_back();
12835 if (found_level == 0)
12836 return false;
12837 else if (found_is_method
12838 && type->named_type() != NULL
12839 && type->points_to() != NULL)
12841 // If this is a method inherited from a struct field in a named pointer
12842 // type, it is invalid to automatically dereference the pointer to the
12843 // struct to find this method.
12844 if (level != NULL)
12845 *level = found_level;
12846 *is_method = true;
12847 return false;
12849 else if (!found_ambig1.empty())
12851 go_assert(!found_ambig1.empty());
12852 ambig1->assign(found_ambig1);
12853 ambig2->assign(found_ambig2);
12854 if (level != NULL)
12855 *level = found_level;
12856 return false;
12858 else
12860 if (level != NULL)
12861 *level = found_level;
12862 *is_method = found_is_method;
12863 return true;
12867 // Return whether NAME is an unexported field or method for TYPE.
12869 bool
12870 Type::is_unexported_field_or_method(Gogo* gogo, const Type* type,
12871 const std::string& name,
12872 std::vector<const Named_type*>* seen)
12874 const Named_type* nt = type->named_type();
12875 if (nt == NULL)
12876 nt = type->deref()->named_type();
12877 if (nt != NULL)
12879 if (nt->is_unexported_local_method(gogo, name))
12880 return true;
12882 for (std::vector<const Named_type*>::const_iterator p = seen->begin();
12883 p != seen->end();
12884 ++p)
12886 if (*p == nt)
12888 // We've already seen this type.
12889 return false;
12894 const Interface_type* it = type->interface_type();
12895 if (it != NULL && it->is_unexported_method(gogo, name))
12896 return true;
12898 type = type->deref();
12900 const Struct_type* st = type->struct_type();
12901 if (st != NULL && st->is_unexported_local_field(gogo, name))
12902 return true;
12904 if (st == NULL)
12905 return false;
12907 const Struct_field_list* fields = st->fields();
12908 if (fields == NULL)
12909 return false;
12911 if (nt != NULL)
12912 seen->push_back(nt);
12914 for (Struct_field_list::const_iterator pf = fields->begin();
12915 pf != fields->end();
12916 ++pf)
12918 if (pf->is_anonymous()
12919 && !pf->type()->deref()->is_error_type()
12920 && !pf->type()->deref()->is_undefined())
12922 Named_type* subtype = pf->type()->named_type();
12923 if (subtype == NULL)
12924 subtype = pf->type()->deref()->named_type();
12925 if (subtype == NULL)
12927 // This is an error, but it will be diagnosed elsewhere.
12928 continue;
12930 if (Type::is_unexported_field_or_method(gogo, subtype, name, seen))
12932 if (nt != NULL)
12933 seen->pop_back();
12934 return true;
12939 if (nt != NULL)
12940 seen->pop_back();
12942 return false;
12945 // Class Forward_declaration.
12947 Forward_declaration_type::Forward_declaration_type(Named_object* named_object)
12948 : Type(TYPE_FORWARD),
12949 named_object_(named_object->resolve()), warned_(false)
12951 go_assert(this->named_object_->is_unknown()
12952 || this->named_object_->is_type_declaration());
12955 // Return the named object.
12957 Named_object*
12958 Forward_declaration_type::named_object()
12960 return this->named_object_->resolve();
12963 const Named_object*
12964 Forward_declaration_type::named_object() const
12966 return this->named_object_->resolve();
12969 // Return the name of the forward declared type.
12971 const std::string&
12972 Forward_declaration_type::name() const
12974 return this->named_object()->name();
12977 // Warn about a use of a type which has been declared but not defined.
12979 void
12980 Forward_declaration_type::warn() const
12982 Named_object* no = this->named_object_->resolve();
12983 if (no->is_unknown())
12985 // The name was not defined anywhere.
12986 if (!this->warned_)
12988 go_error_at(this->named_object_->location(),
12989 "use of undefined type %qs",
12990 no->message_name().c_str());
12991 this->warned_ = true;
12994 else if (no->is_type_declaration())
12996 // The name was seen as a type, but the type was never defined.
12997 if (no->type_declaration_value()->using_type())
12999 go_error_at(this->named_object_->location(),
13000 "use of undefined type %qs",
13001 no->message_name().c_str());
13002 this->warned_ = true;
13005 else
13007 // The name was defined, but not as a type.
13008 if (!this->warned_)
13010 go_error_at(this->named_object_->location(), "expected type");
13011 this->warned_ = true;
13016 // Get the base type of a declaration. This gives an error if the
13017 // type has not yet been defined.
13019 Type*
13020 Forward_declaration_type::real_type()
13022 if (this->is_defined())
13024 Named_type* nt = this->named_object()->type_value();
13025 if (!nt->is_valid())
13026 return Type::make_error_type();
13027 return this->named_object()->type_value();
13029 else
13031 this->warn();
13032 return Type::make_error_type();
13036 const Type*
13037 Forward_declaration_type::real_type() const
13039 if (this->is_defined())
13041 const Named_type* nt = this->named_object()->type_value();
13042 if (!nt->is_valid())
13043 return Type::make_error_type();
13044 return this->named_object()->type_value();
13046 else
13048 this->warn();
13049 return Type::make_error_type();
13053 // Return whether the base type is defined.
13055 bool
13056 Forward_declaration_type::is_defined() const
13058 return this->named_object()->is_type();
13061 // Add a method. This is used when methods are defined before the
13062 // type.
13064 Named_object*
13065 Forward_declaration_type::add_method(const std::string& name,
13066 Function* function)
13068 Named_object* no = this->named_object();
13069 if (no->is_unknown())
13070 no->declare_as_type();
13071 return no->type_declaration_value()->add_method(name, function);
13074 // Add a method declaration. This is used when methods are declared
13075 // before the type.
13077 Named_object*
13078 Forward_declaration_type::add_method_declaration(const std::string& name,
13079 Package* package,
13080 Function_type* type,
13081 Location location)
13083 Named_object* no = this->named_object();
13084 if (no->is_unknown())
13085 no->declare_as_type();
13086 Type_declaration* td = no->type_declaration_value();
13087 return td->add_method_declaration(name, package, type, location);
13090 // Add an already created object as a method.
13092 void
13093 Forward_declaration_type::add_existing_method(Named_object* nom)
13095 Named_object* no = this->named_object();
13096 if (no->is_unknown())
13097 no->declare_as_type();
13098 no->type_declaration_value()->add_existing_method(nom);
13101 // Message name.
13103 void
13104 Forward_declaration_type::do_message_name(std::string* ret) const
13106 if (this->is_defined())
13107 this->append_message_name(this->real_type(), ret);
13108 else
13109 ret->append(this->named_object_->message_name());
13112 // Traversal.
13115 Forward_declaration_type::do_traverse(Traverse* traverse)
13117 if (this->is_defined()
13118 && Type::traverse(this->real_type(), traverse) == TRAVERSE_EXIT)
13119 return TRAVERSE_EXIT;
13120 return TRAVERSE_CONTINUE;
13123 // Verify the type.
13125 bool
13126 Forward_declaration_type::do_verify(Gogo*)
13128 if (!this->is_defined() && !this->is_nil_constant_as_type())
13130 this->warn();
13131 return false;
13133 return true;
13136 // Get the backend representation for the type.
13138 Btype*
13139 Forward_declaration_type::do_get_backend(Gogo* gogo)
13141 if (this->is_defined())
13142 return Type::get_named_base_btype(gogo, this->real_type());
13144 if (this->warned_)
13145 return gogo->backend()->error_type();
13147 // We represent an undefined type as a struct with no fields. That
13148 // should work fine for the backend, since the same case can arise
13149 // in C.
13150 std::vector<Backend::Btyped_identifier> fields;
13151 Btype* bt = gogo->backend()->struct_type(fields);
13152 return gogo->backend()->named_type(this->name(), bt,
13153 this->named_object()->location());
13156 // Build a type descriptor for a forwarded type.
13158 Expression*
13159 Forward_declaration_type::do_type_descriptor(Gogo* gogo, Named_type* name)
13161 Location ploc = Linemap::predeclared_location();
13162 if (!this->is_defined())
13163 return Expression::make_error(ploc);
13164 else
13166 Type* t = this->real_type();
13167 if (name != NULL)
13168 return this->named_type_descriptor(gogo, t, name);
13169 else
13170 return Expression::make_error(this->named_object_->location());
13174 // The reflection string.
13176 void
13177 Forward_declaration_type::do_reflection(Gogo* gogo, std::string* ret) const
13179 this->append_reflection(this->real_type(), gogo, ret);
13182 // Export a forward declaration. This can happen when a defined type
13183 // refers to a type which is only declared (and is presumably defined
13184 // in some other file in the same package).
13186 void
13187 Forward_declaration_type::do_export(Export*) const
13189 // If there is a base type, that should be exported instead of this.
13190 go_assert(!this->is_defined());
13192 // We don't output anything.
13195 // Make a forward declaration.
13197 Type*
13198 Type::make_forward_declaration(Named_object* named_object)
13200 return new Forward_declaration_type(named_object);
13203 // Class Typed_identifier_list.
13205 // Sort the entries by name.
13207 struct Typed_identifier_list_sort
13209 public:
13210 bool
13211 operator()(const Typed_identifier& t1, const Typed_identifier& t2) const
13213 return (Gogo::unpack_hidden_name(t1.name())
13214 < Gogo::unpack_hidden_name(t2.name()));
13218 void
13219 Typed_identifier_list::sort_by_name()
13221 std::sort(this->entries_.begin(), this->entries_.end(),
13222 Typed_identifier_list_sort());
13225 // Traverse types.
13228 Typed_identifier_list::traverse(Traverse* traverse) const
13230 for (Typed_identifier_list::const_iterator p = this->begin();
13231 p != this->end();
13232 ++p)
13234 if (Type::traverse(p->type(), traverse) == TRAVERSE_EXIT)
13235 return TRAVERSE_EXIT;
13237 return TRAVERSE_CONTINUE;
13240 // Copy the list.
13242 Typed_identifier_list*
13243 Typed_identifier_list::copy() const
13245 Typed_identifier_list* ret = new Typed_identifier_list();
13246 for (Typed_identifier_list::const_iterator p = this->begin();
13247 p != this->end();
13248 ++p)
13249 ret->push_back(Typed_identifier(p->name(), p->type(), p->location()));
13250 return ret;