1 // gogo.cc -- Go frontend parsed representation.
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.
15 #include "statements.h"
16 #include "expressions.h"
26 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
31 globals_(new Bindings(NULL
)),
34 imported_unsafe_(false),
48 pkgpath_from_option_(false),
49 prefix_from_option_(false),
50 relative_import_path_(),
53 specific_type_functions_(),
54 specific_type_functions_are_written_(false),
55 named_types_are_converted_(false)
57 const Location loc
= Linemap::predeclared_location();
59 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
60 RUNTIME_TYPE_KIND_UINT8
);
61 this->add_named_type(uint8_type
);
62 this->add_named_type(Type::make_integer_type("uint16", true, 16,
63 RUNTIME_TYPE_KIND_UINT16
));
64 this->add_named_type(Type::make_integer_type("uint32", true, 32,
65 RUNTIME_TYPE_KIND_UINT32
));
66 this->add_named_type(Type::make_integer_type("uint64", true, 64,
67 RUNTIME_TYPE_KIND_UINT64
));
69 this->add_named_type(Type::make_integer_type("int8", false, 8,
70 RUNTIME_TYPE_KIND_INT8
));
71 this->add_named_type(Type::make_integer_type("int16", false, 16,
72 RUNTIME_TYPE_KIND_INT16
));
73 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
74 RUNTIME_TYPE_KIND_INT32
);
75 this->add_named_type(int32_type
);
76 this->add_named_type(Type::make_integer_type("int64", false, 64,
77 RUNTIME_TYPE_KIND_INT64
));
79 this->add_named_type(Type::make_float_type("float32", 32,
80 RUNTIME_TYPE_KIND_FLOAT32
));
81 this->add_named_type(Type::make_float_type("float64", 64,
82 RUNTIME_TYPE_KIND_FLOAT64
));
84 this->add_named_type(Type::make_complex_type("complex64", 64,
85 RUNTIME_TYPE_KIND_COMPLEX64
));
86 this->add_named_type(Type::make_complex_type("complex128", 128,
87 RUNTIME_TYPE_KIND_COMPLEX128
));
89 int int_type_size
= pointer_size
;
90 if (int_type_size
< 32)
92 this->add_named_type(Type::make_integer_type("uint", true,
94 RUNTIME_TYPE_KIND_UINT
));
95 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
96 RUNTIME_TYPE_KIND_INT
);
97 this->add_named_type(int_type
);
99 this->add_named_type(Type::make_integer_type("uintptr", true,
101 RUNTIME_TYPE_KIND_UINTPTR
));
103 // "byte" is an alias for "uint8".
104 uint8_type
->integer_type()->set_is_byte();
105 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
107 this->add_named_type(byte_type
->type_value());
109 // "rune" is an alias for "int32".
110 int32_type
->integer_type()->set_is_rune();
111 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
113 this->add_named_type(rune_type
->type_value());
115 this->add_named_type(Type::make_named_bool_type());
117 this->add_named_type(Type::make_named_string_type());
119 // "error" is interface { Error() string }.
121 Typed_identifier_list
*methods
= new Typed_identifier_list
;
122 Typed_identifier_list
*results
= new Typed_identifier_list
;
123 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
124 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
125 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
126 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
127 error_iface
->finalize_methods();
128 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
129 this->add_named_type(error_type
);
132 this->globals_
->add_constant(Typed_identifier("true",
133 Type::make_boolean_type(),
136 Expression::make_boolean(true, loc
),
138 this->globals_
->add_constant(Typed_identifier("false",
139 Type::make_boolean_type(),
142 Expression::make_boolean(false, loc
),
145 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
148 Expression::make_nil(loc
),
151 Type
* abstract_int_type
= Type::make_abstract_integer_type();
152 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
155 Expression::make_iota(),
158 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
159 new_type
->set_is_varargs();
160 new_type
->set_is_builtin();
161 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
163 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
164 make_type
->set_is_varargs();
165 make_type
->set_is_builtin();
166 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
168 Typed_identifier_list
* len_result
= new Typed_identifier_list();
169 len_result
->push_back(Typed_identifier("", int_type
, loc
));
170 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
172 len_type
->set_is_builtin();
173 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
175 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
176 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
177 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
179 cap_type
->set_is_builtin();
180 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
182 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
183 print_type
->set_is_varargs();
184 print_type
->set_is_builtin();
185 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
187 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
188 print_type
->set_is_varargs();
189 print_type
->set_is_builtin();
190 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
192 Type
*empty
= Type::make_empty_interface_type(loc
);
193 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
194 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
195 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
197 panic_type
->set_is_builtin();
198 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
200 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
201 recover_result
->push_back(Typed_identifier("", empty
, loc
));
202 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
205 recover_type
->set_is_builtin();
206 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
208 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
209 close_type
->set_is_varargs();
210 close_type
->set_is_builtin();
211 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
213 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
214 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
215 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
217 copy_type
->set_is_varargs();
218 copy_type
->set_is_builtin();
219 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
221 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
222 append_type
->set_is_varargs();
223 append_type
->set_is_builtin();
224 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
226 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
227 complex_type
->set_is_varargs();
228 complex_type
->set_is_builtin();
229 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
231 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
232 real_type
->set_is_varargs();
233 real_type
->set_is_builtin();
234 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
236 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
237 imag_type
->set_is_varargs();
238 imag_type
->set_is_builtin();
239 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
241 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
242 delete_type
->set_is_varargs();
243 delete_type
->set_is_builtin();
244 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
247 // Convert a pkgpath into a string suitable for a symbol. Note that
248 // this transformation is convenient but imperfect. A -fgo-pkgpath
249 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
250 // possibly leading to link time errors.
253 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
255 std::string s
= pkgpath
;
256 for (size_t i
= 0; i
< s
.length(); ++i
)
259 if ((c
>= 'a' && c
<= 'z')
260 || (c
>= 'A' && c
<= 'Z')
261 || (c
>= '0' && c
<= '9'))
269 // Get the package path to use for type reflection data. This should
270 // ideally be unique across the entire link.
273 Gogo::pkgpath() const
275 go_assert(this->pkgpath_set_
);
276 return this->pkgpath_
;
279 // Set the package path from the -fgo-pkgpath command line option.
282 Gogo::set_pkgpath(const std::string
& arg
)
284 go_assert(!this->pkgpath_set_
);
285 this->pkgpath_
= arg
;
286 this->pkgpath_set_
= true;
287 this->pkgpath_from_option_
= true;
290 // Get the package path to use for symbol names.
293 Gogo::pkgpath_symbol() const
295 go_assert(this->pkgpath_set_
);
296 return this->pkgpath_symbol_
;
299 // Set the unique prefix to use to determine the package path, from
300 // the -fgo-prefix command line option.
303 Gogo::set_prefix(const std::string
& arg
)
305 go_assert(!this->prefix_from_option_
);
307 this->prefix_from_option_
= true;
310 // Munge name for use in an error message.
313 Gogo::message_name(const std::string
& name
)
315 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
318 // Get the package name.
321 Gogo::package_name() const
323 go_assert(this->package_
!= NULL
);
324 return this->package_
->package_name();
327 // Set the package name.
330 Gogo::set_package_name(const std::string
& package_name
,
333 if (this->package_
!= NULL
)
335 if (this->package_
->package_name() != package_name
)
336 error_at(location
, "expected package %<%s%>",
337 Gogo::message_name(this->package_
->package_name()).c_str());
341 // Now that we know the name of the package we are compiling, set
342 // the package path to use for reflect.Type.PkgPath and global
344 if (this->pkgpath_set_
)
345 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
348 if (!this->prefix_from_option_
&& package_name
== "main")
350 this->pkgpath_
= package_name
;
351 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
355 if (!this->prefix_from_option_
)
356 this->prefix_
= "go";
357 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
358 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
359 + Gogo::pkgpath_for_symbol(package_name
));
361 this->pkgpath_set_
= true;
364 this->package_
= this->register_package(this->pkgpath_
,
365 this->pkgpath_symbol_
, location
);
366 this->package_
->set_package_name(package_name
, location
);
368 if (this->is_main_package())
370 // Declare "main" as a function which takes no parameters and
372 Location uloc
= Linemap::unknown_location();
373 this->declare_function(Gogo::pack_hidden_name("main", false),
374 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
379 // Return whether this is the "main" package. This is not true if
380 // -fgo-pkgpath or -fgo-prefix was used.
383 Gogo::is_main_package() const
385 return (this->package_name() == "main"
386 && !this->pkgpath_from_option_
387 && !this->prefix_from_option_
);
393 Gogo::import_package(const std::string
& filename
,
394 const std::string
& local_name
,
395 bool is_local_name_exported
,
398 if (filename
.empty())
400 error_at(location
, "import path is empty");
404 const char *pf
= filename
.data();
405 const char *pend
= pf
+ filename
.length();
409 int adv
= Lex::fetch_char(pf
, &c
);
412 error_at(location
, "import path contains invalid UTF-8 sequence");
417 error_at(location
, "import path contains NUL");
420 if (c
< 0x20 || c
== 0x7f)
422 error_at(location
, "import path contains control character");
427 error_at(location
, "import path contains backslash; use slash");
430 if (Lex::is_unicode_space(c
))
432 error_at(location
, "import path contains space character");
435 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
437 error_at(location
, "import path contains invalid character '%c'", c
);
443 if (IS_ABSOLUTE_PATH(filename
.c_str()))
445 error_at(location
, "import path cannot be absolute path");
449 if (local_name
== "init")
450 error_at(location
, "cannot import package as init");
452 if (filename
== "unsafe")
454 this->import_unsafe(local_name
, is_local_name_exported
, location
);
458 Imports::const_iterator p
= this->imports_
.find(filename
);
459 if (p
!= this->imports_
.end())
461 Package
* package
= p
->second
;
462 package
->set_location(location
);
463 package
->set_is_imported();
464 std::string ln
= local_name
;
465 bool is_ln_exported
= is_local_name_exported
;
468 ln
= package
->package_name();
469 go_assert(!ln
.empty());
470 is_ln_exported
= Lex::is_exported_name(ln
);
474 Bindings
* bindings
= package
->bindings();
475 for (Bindings::const_declarations_iterator p
=
476 bindings
->begin_declarations();
477 p
!= bindings
->end_declarations();
479 this->add_dot_import_object(p
->second
);
482 package
->set_uses_sink_alias();
485 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
486 this->package_
->bindings()->add_package(ln
, package
);
491 Import::Stream
* stream
= Import::open_package(filename
, location
,
492 this->relative_import_path_
);
495 error_at(location
, "import file %qs not found", filename
.c_str());
499 Import
imp(stream
, location
);
500 imp
.register_builtin_types(this);
501 Package
* package
= imp
.import(this, local_name
, is_local_name_exported
);
504 if (package
->pkgpath() == this->pkgpath())
506 ("imported package uses same package path as package "
507 "being compiled (see -fgo-pkgpath option)"));
509 this->imports_
.insert(std::make_pair(filename
, package
));
510 package
->set_is_imported();
516 // Add an import control function for an imported package to the list.
519 Gogo::add_import_init_fn(const std::string
& package_name
,
520 const std::string
& init_name
, int prio
)
522 for (std::set
<Import_init
>::const_iterator p
=
523 this->imported_init_fns_
.begin();
524 p
!= this->imported_init_fns_
.end();
527 if (p
->init_name() == init_name
)
529 // If a test of package P1, built as part of package P1,
530 // imports package P2, and P2 imports P1 (perhaps
531 // indirectly), then we will see the same import name with
532 // different import priorities. That is OK, so don't give
533 // an error about it.
534 if (p
->package_name() != package_name
)
536 error("duplicate package initialization name %qs",
537 Gogo::message_name(init_name
).c_str());
538 inform(UNKNOWN_LOCATION
, "used by package %qs at priority %d",
539 Gogo::message_name(p
->package_name()).c_str(),
541 inform(UNKNOWN_LOCATION
, " and by package %qs at priority %d",
542 Gogo::message_name(package_name
).c_str(), prio
);
548 this->imported_init_fns_
.insert(Import_init(package_name
, init_name
,
552 // Return whether we are at the global binding level.
555 Gogo::in_global_scope() const
557 return this->functions_
.empty();
560 // Return the current binding contour.
563 Gogo::current_bindings()
565 if (!this->functions_
.empty())
566 return this->functions_
.back().blocks
.back()->bindings();
567 else if (this->package_
!= NULL
)
568 return this->package_
->bindings();
570 return this->globals_
;
574 Gogo::current_bindings() const
576 if (!this->functions_
.empty())
577 return this->functions_
.back().blocks
.back()->bindings();
578 else if (this->package_
!= NULL
)
579 return this->package_
->bindings();
581 return this->globals_
;
584 // Return the special variable used as the zero value of types.
587 Gogo::zero_value(Type
*type
)
589 if (this->zero_value_
== NULL
)
591 Location bloc
= Linemap::predeclared_location();
593 // We will change the type later, when we know the size.
594 Type
* byte_type
= this->lookup_global("byte")->type_value();
596 Expression
* zero
= Expression::make_integer_ul(0, NULL
, bloc
);
597 Type
* array_type
= Type::make_array_type(byte_type
, zero
);
599 Variable
* var
= new Variable(array_type
, NULL
, true, false, false, bloc
);
600 this->zero_value_
= Named_object::make_variable("go$zerovalue", NULL
,
604 // The zero value will be the maximum required size.
606 bool ok
= type
->backend_type_size(this, &size
);
608 go_assert(saw_errors());
611 if (size
> this->zero_value_size_
)
612 this->zero_value_size_
= size
;
615 ok
= type
->backend_type_align(this, &align
);
617 go_assert(saw_errors());
620 if (align
> this->zero_value_align_
)
621 this->zero_value_align_
= align
;
623 return this->zero_value_
;
626 // Return whether V is the zero value variable.
629 Gogo::is_zero_value(Variable
* v
) const
631 return this->zero_value_
!= NULL
&& this->zero_value_
->var_value() == v
;
634 // Return the backend variable for the special zero value, or NULL if
638 Gogo::backend_zero_value()
640 if (this->zero_value_
== NULL
)
643 Type
* byte_type
= this->lookup_global("byte")->type_value();
644 Btype
* bbtype_type
= byte_type
->get_backend(this);
646 Type
* int_type
= this->lookup_global("int")->type_value();
647 Btype
* bint_type
= int_type
->get_backend(this);
650 mpz_init_set_ui(val
, this->zero_value_size_
);
651 Bexpression
* blength
=
652 this->backend()->integer_constant_expression(bint_type
, val
);
655 Btype
* barray_type
= this->backend()->array_type(bbtype_type
, blength
);
657 std::string zname
= this->zero_value_
->name();
659 this->backend()->implicit_variable(zname
, barray_type
, false,
660 true, true, this->zero_value_align_
);
661 this->backend()->implicit_variable_set_init(zvar
, zname
, barray_type
,
662 false, true, true, NULL
);
666 // Add statements to INIT_STMTS which run the initialization
667 // functions for imported packages. This is only used for the "main"
671 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
)
673 go_assert(this->is_main_package());
675 if (this->imported_init_fns_
.empty())
678 Location unknown_loc
= Linemap::unknown_location();
679 Function_type
* func_type
=
680 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
681 Btype
* fntype
= func_type
->get_backend_fntype(this);
683 // We must call them in increasing priority order.
684 std::vector
<Import_init
> v
;
685 for (std::set
<Import_init
>::const_iterator p
=
686 this->imported_init_fns_
.begin();
687 p
!= this->imported_init_fns_
.end();
690 std::sort(v
.begin(), v
.end());
692 // We build calls to the init functions, which take no arguments.
693 std::vector
<Bexpression
*> empty_args
;
694 for (std::vector
<Import_init
>::const_iterator p
= v
.begin();
698 std::string user_name
= p
->package_name() + ".init";
699 const std::string
& init_name(p
->init_name());
701 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
702 true, true, true, false,
704 Bexpression
* pfunc_code
=
705 this->backend()->function_code_expression(pfunc
, unknown_loc
);
706 Bexpression
* pfunc_call
=
707 this->backend()->call_expression(pfunc_code
, empty_args
,
709 init_stmts
.push_back(this->backend()->expression_statement(pfunc_call
));
713 // Register global variables with the garbage collector. We need to
714 // register all variables which can hold a pointer value. They become
715 // roots during the mark phase. We build a struct that is easy to
716 // hook into a list of roots.
718 // struct __go_gc_root_list
720 // struct __go_gc_root_list* __next;
721 // struct __go_gc_root
728 // The last entry in the roots array has a NULL decl field.
731 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
732 std::vector
<Bstatement
*>& init_stmts
)
737 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
738 Type
* uint_type
= Type::lookup_integer_type("uint");
739 Struct_type
* root_type
= Type::make_builtin_struct_type(2,
741 "__size", uint_type
);
743 Location builtin_loc
= Linemap::predeclared_location();
744 Expression
* length
= Expression::make_integer_ul(var_gc
.size(), NULL
,
747 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
748 Type
* ptdt
= Type::make_type_descriptor_ptr_type();
749 Struct_type
* root_list_type
=
750 Type::make_builtin_struct_type(2,
752 "__roots", root_array_type
);
754 // Build an initializer for the __roots array.
756 Expression_list
* roots_init
= new Expression_list();
759 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
763 Expression_list
* init
= new Expression_list();
765 Location no_loc
= (*p
)->location();
766 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
767 Expression
* decl_addr
=
768 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
769 init
->push_back(decl_addr
);
771 Expression
* decl_size
=
772 Expression::make_type_info(decl
->type(), Expression::TYPE_INFO_SIZE
);
773 init
->push_back(decl_size
);
775 Expression
* root_ctor
=
776 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
777 roots_init
->push_back(root_ctor
);
780 // The list ends with a NULL entry.
782 Expression_list
* null_init
= new Expression_list();
783 Expression
* nil
= Expression::make_nil(builtin_loc
);
784 null_init
->push_back(nil
);
786 Expression
*zero
= Expression::make_integer_ul(0, NULL
, builtin_loc
);
787 null_init
->push_back(zero
);
789 Expression
* null_root_ctor
=
790 Expression::make_struct_composite_literal(root_type
, null_init
,
792 roots_init
->push_back(null_root_ctor
);
794 // Build a constructor for the struct.
796 Expression_list
* root_list_init
= new Expression_list();
797 root_list_init
->push_back(nil
);
799 Expression
* roots_ctor
=
800 Expression::make_array_composite_literal(root_array_type
, roots_init
,
802 root_list_init
->push_back(roots_ctor
);
804 Expression
* root_list_ctor
=
805 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
808 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
810 root_addr
->unary_expression()->set_is_gc_root();
811 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
812 builtin_loc
, 1, root_addr
);
814 Translate_context
context(this, NULL
, NULL
, NULL
);
815 Bexpression
* bcall
= register_roots
->get_backend(&context
);
816 init_stmts
.push_back(this->backend()->expression_statement(bcall
));
819 // Get the name to use for the import control function. If there is a
820 // global function or variable, then we know that that name must be
821 // unique in the link, and we use it as the basis for our name.
824 Gogo::get_init_fn_name()
826 if (this->init_fn_name_
.empty())
828 go_assert(this->package_
!= NULL
);
829 if (this->is_main_package())
831 // Use a name which the runtime knows.
832 this->init_fn_name_
= "__go_init_main";
836 std::string s
= this->pkgpath_symbol();
837 s
.append("..import");
838 this->init_fn_name_
= s
;
842 return this->init_fn_name_
;
845 // Build the decl for the initialization function.
848 Gogo::initialization_function_decl()
850 std::string name
= this->get_init_fn_name();
851 Location loc
= this->package_
->location();
853 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
854 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
855 return Named_object::make_function(name
, NULL
, initfn
);
858 // Create the magic initialization function. CODE_STMT is the
859 // code that it needs to run.
862 Gogo::create_initialization_function(Named_object
* initfn
,
863 Bstatement
* code_stmt
)
865 // Make sure that we thought we needed an initialization function,
866 // as otherwise we will not have reported it in the export data.
867 go_assert(this->is_main_package() || this->need_init_fn_
);
870 initfn
= this->initialization_function_decl();
872 // Bind the initialization function code to a block.
873 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
874 Location pkg_loc
= this->package_
->location();
875 std::vector
<Bvariable
*> vars
;
876 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
878 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
880 go_assert(saw_errors());
886 // Search for references to VAR in any statements or called functions.
888 class Find_var
: public Traverse
891 // A hash table we use to avoid looping. The index is the name of a
892 // named object. We only look through objects defined in this
894 typedef Unordered_set(const void*) Seen_objects
;
896 Find_var(Named_object
* var
, Seen_objects
* seen_objects
)
897 : Traverse(traverse_expressions
),
898 var_(var
), seen_objects_(seen_objects
), found_(false)
901 // Whether the variable was found.
904 { return this->found_
; }
907 expression(Expression
**);
910 // The variable we are looking for.
912 // Names of objects we have already seen.
913 Seen_objects
* seen_objects_
;
914 // True if the variable was found.
918 // See if EXPR refers to VAR, looking through function calls and
919 // variable initializations.
922 Find_var::expression(Expression
** pexpr
)
924 Expression
* e
= *pexpr
;
926 Var_expression
* ve
= e
->var_expression();
929 Named_object
* v
= ve
->named_object();
933 return TRAVERSE_EXIT
;
936 if (v
->is_variable() && v
->package() == NULL
)
938 Expression
* init
= v
->var_value()->init();
941 std::pair
<Seen_objects::iterator
, bool> ins
=
942 this->seen_objects_
->insert(v
);
945 // This is the first time we have seen this name.
946 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
947 return TRAVERSE_EXIT
;
953 // We traverse the code of any function or bound method we see. Note that
954 // this means that we will traverse the code of a function or bound method
955 // whose address is taken even if it is not called.
956 Func_expression
* fe
= e
->func_expression();
957 Bound_method_expression
* bme
= e
->bound_method_expression();
958 if (fe
!= NULL
|| bme
!= NULL
)
960 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
961 if (f
->is_function() && f
->package() == NULL
)
963 std::pair
<Seen_objects::iterator
, bool> ins
=
964 this->seen_objects_
->insert(f
);
967 // This is the first time we have seen this name.
968 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
969 return TRAVERSE_EXIT
;
974 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
977 Temporary_statement
* ts
= tre
->statement();
978 Expression
* init
= ts
->init();
981 std::pair
<Seen_objects::iterator
, bool> ins
=
982 this->seen_objects_
->insert(ts
);
985 // This is the first time we have seen this temporary
987 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
988 return TRAVERSE_EXIT
;
993 return TRAVERSE_CONTINUE
;
996 // Return true if EXPR, PREINIT, or DEP refers to VAR.
999 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1002 Find_var::Seen_objects seen_objects
;
1003 Find_var
find_var(var
, &seen_objects
);
1005 Expression::traverse(&expr
, &find_var
);
1006 if (preinit
!= NULL
)
1007 preinit
->traverse(&find_var
);
1010 Expression
* init
= dep
->var_value()->init();
1012 Expression::traverse(&init
, &find_var
);
1013 if (dep
->var_value()->has_pre_init())
1014 dep
->var_value()->preinit()->traverse(&find_var
);
1017 return find_var
.found();
1020 // Sort variable initializations. If the initialization expression
1021 // for variable A refers directly or indirectly to the initialization
1022 // expression for variable B, then we must initialize B before A.
1028 : var_(NULL
), init_(NULL
), dep_count_(0)
1031 Var_init(Named_object
* var
, Bstatement
* init
)
1032 : var_(var
), init_(init
), dep_count_(0)
1035 // Return the variable.
1038 { return this->var_
; }
1040 // Return the initialization expression.
1043 { return this->init_
; }
1045 // Return the number of remaining dependencies.
1048 { return this->dep_count_
; }
1050 // Increment the number of dependencies.
1053 { ++this->dep_count_
; }
1055 // Decrement the number of dependencies.
1058 { --this->dep_count_
; }
1061 // The variable being initialized.
1063 // The initialization statement.
1065 // The number of initializations this is dependent on. A variable
1066 // initialization should not be emitted if any of its dependencies
1067 // have not yet been resolved.
1071 // For comparing Var_init keys in a map.
1074 operator<(const Var_init
& v1
, const Var_init
& v2
)
1075 { return v1
.var()->name() < v2
.var()->name(); }
1077 typedef std::list
<Var_init
> Var_inits
;
1079 // Sort the variable initializations. The rule we follow is that we
1080 // emit them in the order they appear in the array, except that if the
1081 // initialization expression for a variable V1 depends upon another
1082 // variable V2 then we initialize V1 after V2.
1085 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1087 if (var_inits
->empty())
1090 typedef std::pair
<Named_object
*, Named_object
*> No_no
;
1091 typedef std::map
<No_no
, bool> Cache
;
1094 // A mapping from a variable initialization to a set of
1095 // variable initializations that depend on it.
1096 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1097 Init_deps init_deps
;
1098 bool init_loop
= false;
1099 for (Var_inits::iterator p1
= var_inits
->begin();
1100 p1
!= var_inits
->end();
1103 Named_object
* var
= p1
->var();
1104 Expression
* init
= var
->var_value()->init();
1105 Block
* preinit
= var
->var_value()->preinit();
1106 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1108 // Start walking through the list to see which variables VAR
1109 // needs to wait for.
1110 for (Var_inits::iterator p2
= var_inits
->begin();
1111 p2
!= var_inits
->end();
1114 if (var
== p2
->var())
1117 Named_object
* p2var
= p2
->var();
1118 No_no
key(var
, p2var
);
1119 std::pair
<Cache::iterator
, bool> ins
=
1120 cache
.insert(std::make_pair(key
, false));
1122 ins
.first
->second
= expression_requires(init
, preinit
, dep
, p2var
);
1123 if (ins
.first
->second
)
1125 // VAR depends on P2VAR.
1126 init_deps
[*p2
].insert(&(*p1
));
1127 p1
->add_dependency();
1129 // Check for cycles.
1130 key
= std::make_pair(p2var
, var
);
1131 ins
= cache
.insert(std::make_pair(key
, false));
1134 expression_requires(p2var
->var_value()->init(),
1135 p2var
->var_value()->preinit(),
1136 gogo
->var_depends_on(p2var
->var_value()),
1138 if (ins
.first
->second
)
1140 error_at(var
->location(),
1141 ("initialization expressions for %qs and "
1142 "%qs depend upon each other"),
1143 var
->message_name().c_str(),
1144 p2var
->message_name().c_str());
1145 inform(p2
->var()->location(), "%qs defined here",
1146 p2var
->message_name().c_str());
1154 // If there are no dependencies then the declaration order is sorted.
1155 if (!init_deps
.empty() && !init_loop
)
1157 // Otherwise, sort variable initializations by emitting all variables with
1158 // no dependencies in declaration order. VAR_INITS is already in
1159 // declaration order.
1161 while (!var_inits
->empty())
1163 Var_inits::iterator v1
;;
1164 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1166 if (v1
->dep_count() == 0)
1169 go_assert(v1
!= var_inits
->end());
1171 // V1 either has no dependencies or its dependencies have already
1172 // been emitted, add it to READY next. When V1 is emitted, remove
1173 // a dependency from each V that depends on V1.
1174 ready
.splice(ready
.end(), *var_inits
, v1
);
1176 Init_deps::iterator p1
= init_deps
.find(*v1
);
1177 if (p1
!= init_deps
.end())
1179 std::set
<Var_init
*> resolved
= p1
->second
;
1180 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1181 pv
!= resolved
.end();
1183 (*pv
)->remove_dependency();
1184 init_deps
.erase(p1
);
1187 var_inits
->swap(ready
);
1188 go_assert(init_deps
.empty());
1191 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1192 // check for a loop of VAR on itself. We only do this if
1193 // INIT is not NULL and there is no dependency; when INIT is
1194 // NULL, it means that PREINIT sets VAR, which we will
1195 // interpret as a loop.
1196 for (Var_inits::const_iterator p
= var_inits
->begin();
1197 p
!= var_inits
->end();
1200 Named_object
* var
= p
->var();
1201 Expression
* init
= var
->var_value()->init();
1202 Block
* preinit
= var
->var_value()->preinit();
1203 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1204 if (init
!= NULL
&& dep
== NULL
1205 && expression_requires(init
, preinit
, NULL
, var
))
1206 error_at(var
->location(),
1207 "initialization expression for %qs depends upon itself",
1208 var
->message_name().c_str());
1212 // Write out the global definitions.
1215 Gogo::write_globals()
1217 this->build_interface_method_tables();
1219 Bindings
* bindings
= this->current_bindings();
1221 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1222 p
!= bindings
->end_declarations();
1225 // If any function declarations needed a descriptor, make sure
1227 Named_object
* no
= p
->second
;
1228 if (no
->is_function_declaration())
1229 no
->func_declaration_value()->build_backend_descriptor(this);
1232 // Lists of globally declared types, variables, constants, and functions
1233 // that must be defined.
1234 std::vector
<Btype
*> type_decls
;
1235 std::vector
<Bvariable
*> var_decls
;
1236 std::vector
<Bexpression
*> const_decls
;
1237 std::vector
<Bfunction
*> func_decls
;
1239 // The init function declaration, if necessary.
1240 Named_object
* init_fndecl
= NULL
;
1242 std::vector
<Bstatement
*> init_stmts
;
1243 std::vector
<Bstatement
*> var_init_stmts
;
1245 if (this->is_main_package())
1246 this->init_imports(init_stmts
);
1248 // A list of variable initializations.
1249 Var_inits var_inits
;
1251 // A list of variables which need to be registered with the garbage
1253 size_t count_definitions
= bindings
->size_definitions();
1254 std::vector
<Named_object
*> var_gc
;
1255 var_gc
.reserve(count_definitions
);
1257 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1258 p
!= bindings
->end_definitions();
1261 Named_object
* no
= *p
;
1262 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1264 // There is nothing to do for a package.
1265 if (no
->is_package())
1268 // There is nothing to do for an object which was imported from
1269 // a different package into the global scope.
1270 if (no
->package() != NULL
)
1273 // Skip blank named functions and constants.
1274 if ((no
->is_function() && no
->func_value()->is_sink())
1275 || (no
->is_const() && no
->const_value()->is_sink()))
1278 // There is nothing useful we can output for constants which
1279 // have ideal or non-integral type.
1282 Type
* type
= no
->const_value()->type();
1284 type
= no
->const_value()->expr()->type();
1285 if (type
->is_abstract() || !type
->is_numeric_type())
1289 if (!no
->is_variable())
1290 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1293 Variable
* var
= no
->var_value();
1294 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1295 var_decls
.push_back(bvar
);
1297 // Check for a sink variable, which may be used to run an
1298 // initializer purely for its side effects.
1299 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1301 Bstatement
* var_init_stmt
= NULL
;
1302 if (!var
->has_pre_init())
1304 // If the backend representation of the variable initializer is
1305 // constant, we can just set the initial value using
1306 // global_var_set_init instead of during the init() function.
1307 // The initializer is constant if it is the zero-value of the
1308 // variable's type or if the initial value is an immutable value
1309 // that is not copied to the heap.
1310 bool is_constant_initializer
= false;
1311 if (var
->init() == NULL
)
1312 is_constant_initializer
= true;
1315 Type
* var_type
= var
->type();
1316 Expression
* init
= var
->init();
1317 Expression
* init_cast
=
1318 Expression::make_cast(var_type
, init
, var
->location());
1319 is_constant_initializer
=
1320 init_cast
->is_immutable() && !var_type
->has_pointer();
1323 // Non-constant variable initializations might need to create
1324 // temporary variables, which will need the initialization
1325 // function as context.
1326 if (!is_constant_initializer
&& init_fndecl
== NULL
)
1327 init_fndecl
= this->initialization_function_decl();
1328 Bexpression
* var_binit
= var
->get_init(this, init_fndecl
);
1330 if (var_binit
== NULL
)
1332 else if (is_constant_initializer
)
1334 if (expression_requires(var
->init(), NULL
,
1335 this->var_depends_on(var
), no
))
1336 error_at(no
->location(),
1337 "initialization expression for %qs depends "
1339 no
->message_name().c_str());
1340 this->backend()->global_variable_set_init(bvar
, var_binit
);
1344 this->backend()->expression_statement(var_binit
);
1347 Location loc
= var
->location();
1348 Bexpression
* var_expr
=
1349 this->backend()->var_expression(bvar
, loc
);
1351 this->backend()->assignment_statement(var_expr
, var_binit
,
1357 // We are going to create temporary variables which
1358 // means that we need an fndecl.
1359 if (init_fndecl
== NULL
)
1360 init_fndecl
= this->initialization_function_decl();
1362 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1363 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1366 if (var_init_stmt
!= NULL
)
1368 if (var
->init() == NULL
&& !var
->has_pre_init())
1369 var_init_stmts
.push_back(var_init_stmt
);
1371 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1373 else if (this->var_depends_on(var
) != NULL
)
1375 // This variable is initialized from something that is
1376 // not in its init or preinit. This variable needs to
1377 // participate in dependency analysis sorting, in case
1378 // some other variable depends on this one.
1379 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1380 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1381 Bstatement
* zero_stmt
=
1382 this->backend()->expression_statement(zero
);
1383 var_inits
.push_back(Var_init(no
, zero_stmt
));
1386 if (!is_sink
&& var
->type()->has_pointer())
1387 var_gc
.push_back(no
);
1391 // Register global variables with the garbage collector.
1392 this->register_gc_vars(var_gc
, init_stmts
);
1394 // Simple variable initializations, after all variables are
1396 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1398 // Complete variable initializations, first sorting them into a
1400 if (!var_inits
.empty())
1402 sort_var_inits(this, &var_inits
);
1403 for (Var_inits::const_iterator p
= var_inits
.begin();
1404 p
!= var_inits
.end();
1406 init_stmts
.push_back(p
->init());
1409 // After all the variables are initialized, call the init
1410 // functions if there are any. Init functions take no arguments, so
1411 // we pass in EMPTY_ARGS to call them.
1412 std::vector
<Bexpression
*> empty_args
;
1413 for (std::vector
<Named_object
*>::const_iterator p
=
1414 this->init_functions_
.begin();
1415 p
!= this->init_functions_
.end();
1418 Location func_loc
= (*p
)->location();
1419 Function
* func
= (*p
)->func_value();
1420 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1421 Bexpression
* func_code
=
1422 this->backend()->function_code_expression(initfn
, func_loc
);
1423 Bexpression
* call
= this->backend()->call_expression(func_code
,
1426 init_stmts
.push_back(this->backend()->expression_statement(call
));
1429 // Set up a magic function to do all the initialization actions.
1430 // This will be called if this package is imported.
1431 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1432 if (this->need_init_fn_
|| this->is_main_package())
1435 this->create_initialization_function(init_fndecl
, init_fncode
);
1436 if (init_fndecl
!= NULL
)
1437 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1440 // We should not have seen any new bindings created during the conversion.
1441 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1443 // Define all globally declared values.
1445 this->backend()->write_global_definitions(type_decls
, const_decls
,
1446 func_decls
, var_decls
);
1449 // Return the current block.
1452 Gogo::current_block()
1454 if (this->functions_
.empty())
1457 return this->functions_
.back().blocks
.back();
1460 // Look up a name in the current binding contour. If PFUNCTION is not
1461 // NULL, set it to the function in which the name is defined, or NULL
1462 // if the name is defined in global scope.
1465 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1467 if (pfunction
!= NULL
)
1470 if (Gogo::is_sink_name(name
))
1471 return Named_object::make_sink();
1473 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1474 p
!= this->functions_
.rend();
1477 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1480 if (pfunction
!= NULL
)
1481 *pfunction
= p
->function
;
1486 if (this->package_
!= NULL
)
1488 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1491 if (ret
->package() != NULL
)
1492 ret
->package()->note_usage();
1497 // We do not look in the global namespace. If we did, the global
1498 // namespace would effectively hide names which were defined in
1499 // package scope which we have not yet seen. Instead,
1500 // define_global_names is called after parsing is over to connect
1501 // undefined names at package scope with names defined at global
1507 // Look up a name in the current block, without searching enclosing
1511 Gogo::lookup_in_block(const std::string
& name
) const
1513 go_assert(!this->functions_
.empty());
1514 go_assert(!this->functions_
.back().blocks
.empty());
1515 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1518 // Look up a name in the global namespace.
1521 Gogo::lookup_global(const char* name
) const
1523 return this->globals_
->lookup(name
);
1526 // Add an imported package.
1529 Gogo::add_imported_package(const std::string
& real_name
,
1530 const std::string
& alias_arg
,
1531 bool is_alias_exported
,
1532 const std::string
& pkgpath
,
1533 const std::string
& pkgpath_symbol
,
1535 bool* padd_to_globals
)
1537 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1538 ret
->set_package_name(real_name
, location
);
1540 *padd_to_globals
= false;
1542 if (alias_arg
== ".")
1543 *padd_to_globals
= true;
1544 else if (alias_arg
== "_")
1545 ret
->set_uses_sink_alias();
1548 std::string alias
= alias_arg
;
1552 is_alias_exported
= Lex::is_exported_name(alias
);
1554 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1555 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1556 if (!no
->is_package())
1563 // Register a package. This package may or may not be imported. This
1564 // returns the Package structure for the package, creating if it
1565 // necessary. LOCATION is the location of the import statement that
1566 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1567 // for names in the package; it may be the empty string, in which case
1568 // we either get it later or make a guess when we need it.
1571 Gogo::register_package(const std::string
& pkgpath
,
1572 const std::string
& pkgpath_symbol
, Location location
)
1574 Package
* package
= NULL
;
1575 std::pair
<Packages::iterator
, bool> ins
=
1576 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1579 // We have seen this package name before.
1580 package
= ins
.first
->second
;
1581 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1582 if (!pkgpath_symbol
.empty())
1583 package
->set_pkgpath_symbol(pkgpath_symbol
);
1584 if (Linemap::is_unknown_location(package
->location()))
1585 package
->set_location(location
);
1589 // First time we have seen this package name.
1590 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1591 go_assert(ins
.first
->second
== NULL
);
1592 ins
.first
->second
= package
;
1598 // Start compiling a function.
1601 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1602 bool add_method_to_type
, Location location
)
1604 bool at_top_level
= this->functions_
.empty();
1606 Block
* block
= new Block(NULL
, location
);
1608 Function
* enclosing
= (at_top_level
1610 : this->functions_
.back().function
->func_value());
1612 Function
* function
= new Function(type
, enclosing
, block
, location
);
1614 if (type
->is_method())
1616 const Typed_identifier
* receiver
= type
->receiver();
1617 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1618 true, true, location
);
1619 std::string rname
= receiver
->name();
1620 if (rname
.empty() || Gogo::is_sink_name(rname
))
1622 // We need to give receivers a name since they wind up in
1623 // DECL_ARGUMENTS. FIXME.
1624 static unsigned int count
;
1626 snprintf(buf
, sizeof buf
, "r.%u", count
);
1630 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1633 const Typed_identifier_list
* parameters
= type
->parameters();
1634 bool is_varargs
= type
->is_varargs();
1635 if (parameters
!= NULL
)
1637 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1638 p
!= parameters
->end();
1641 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1643 if (is_varargs
&& p
+ 1 == parameters
->end())
1644 param
->set_is_varargs_parameter();
1646 std::string pname
= p
->name();
1647 if (pname
.empty() || Gogo::is_sink_name(pname
))
1649 // We need to give parameters a name since they wind up
1650 // in DECL_ARGUMENTS. FIXME.
1651 static unsigned int count
;
1653 snprintf(buf
, sizeof buf
, "p.%u", count
);
1657 block
->bindings()->add_variable(pname
, NULL
, param
);
1661 function
->create_result_variables(this);
1663 const std::string
* pname
;
1664 std::string nested_name
;
1665 bool is_init
= false;
1666 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1668 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1669 || (type
->results() != NULL
&& !type
->results()->empty()))
1671 "func init must have no arguments and no return values");
1672 // There can be multiple "init" functions, so give them each a
1674 static int init_count
;
1676 snprintf(buf
, sizeof buf
, ".$init%d", init_count
);
1679 pname
= &nested_name
;
1682 else if (!name
.empty())
1686 // Invent a name for a nested function.
1687 static int nested_count
;
1689 snprintf(buf
, sizeof buf
, ".$nested%d", nested_count
);
1692 pname
= &nested_name
;
1696 if (Gogo::is_sink_name(*pname
))
1698 static int sink_count
;
1700 snprintf(buf
, sizeof buf
, ".$sink%d", sink_count
);
1702 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1703 ret
->func_value()->set_is_sink();
1705 else if (!type
->is_method())
1707 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1708 if (!ret
->is_function() || ret
->func_value() != function
)
1710 // Redefinition error. Invent a name to avoid knockon
1712 static int redefinition_count
;
1714 snprintf(buf
, sizeof buf
, ".$redefined%d", redefinition_count
);
1715 ++redefinition_count
;
1716 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1721 if (!add_method_to_type
)
1722 ret
= Named_object::make_function(name
, NULL
, function
);
1725 go_assert(at_top_level
);
1726 Type
* rtype
= type
->receiver()->type();
1728 // We want to look through the pointer created by the
1729 // parser, without getting an error if the type is not yet
1731 if (rtype
->classification() == Type::TYPE_POINTER
)
1732 rtype
= rtype
->points_to();
1734 if (rtype
->is_error_type())
1735 ret
= Named_object::make_function(name
, NULL
, function
);
1736 else if (rtype
->named_type() != NULL
)
1738 ret
= rtype
->named_type()->add_method(name
, function
);
1739 if (!ret
->is_function())
1741 // Redefinition error.
1742 ret
= Named_object::make_function(name
, NULL
, function
);
1745 else if (rtype
->forward_declaration_type() != NULL
)
1747 Named_object
* type_no
=
1748 rtype
->forward_declaration_type()->named_object();
1749 if (type_no
->is_unknown())
1751 // If we are seeing methods it really must be a
1752 // type. Declare it as such. An alternative would
1753 // be to support lists of methods for unknown
1754 // expressions. Either way the error messages if
1755 // this is not a type are going to get confusing.
1756 Named_object
* declared
=
1757 this->declare_package_type(type_no
->name(),
1758 type_no
->location());
1760 == type_no
->unknown_value()->real_named_object());
1762 ret
= rtype
->forward_declaration_type()->add_method(name
,
1768 this->package_
->bindings()->add_method(ret
);
1771 this->functions_
.resize(this->functions_
.size() + 1);
1772 Open_function
& of(this->functions_
.back());
1774 of
.blocks
.push_back(block
);
1778 this->init_functions_
.push_back(ret
);
1779 this->need_init_fn_
= true;
1785 // Finish compiling a function.
1788 Gogo::finish_function(Location location
)
1790 this->finish_block(location
);
1791 go_assert(this->functions_
.back().blocks
.empty());
1792 this->functions_
.pop_back();
1795 // Return the current function.
1798 Gogo::current_function() const
1800 go_assert(!this->functions_
.empty());
1801 return this->functions_
.back().function
;
1804 // Start a new block.
1807 Gogo::start_block(Location location
)
1809 go_assert(!this->functions_
.empty());
1810 Block
* block
= new Block(this->current_block(), location
);
1811 this->functions_
.back().blocks
.push_back(block
);
1817 Gogo::finish_block(Location location
)
1819 go_assert(!this->functions_
.empty());
1820 go_assert(!this->functions_
.back().blocks
.empty());
1821 Block
* block
= this->functions_
.back().blocks
.back();
1822 this->functions_
.back().blocks
.pop_back();
1823 block
->set_end_location(location
);
1827 // Add an erroneous name.
1830 Gogo::add_erroneous_name(const std::string
& name
)
1832 return this->package_
->bindings()->add_erroneous_name(name
);
1835 // Add an unknown name.
1838 Gogo::add_unknown_name(const std::string
& name
, Location location
)
1840 return this->package_
->bindings()->add_unknown_name(name
, location
);
1843 // Declare a function.
1846 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
1849 if (!type
->is_method())
1850 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
1854 // We don't bother to add this to the list of global
1856 Type
* rtype
= type
->receiver()->type();
1858 // We want to look through the pointer created by the
1859 // parser, without getting an error if the type is not yet
1861 if (rtype
->classification() == Type::TYPE_POINTER
)
1862 rtype
= rtype
->points_to();
1864 if (rtype
->is_error_type())
1866 else if (rtype
->named_type() != NULL
)
1867 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
1869 else if (rtype
->forward_declaration_type() != NULL
)
1871 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
1872 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
1879 // Add a label definition.
1882 Gogo::add_label_definition(const std::string
& label_name
,
1885 // A label with a blank identifier is never declared or defined.
1886 if (label_name
== "_")
1889 go_assert(!this->functions_
.empty());
1890 Function
* func
= this->functions_
.back().function
->func_value();
1891 Label
* label
= func
->add_label_definition(this, label_name
, location
);
1892 this->add_statement(Statement::make_label_statement(label
, location
));
1896 // Add a label reference.
1899 Gogo::add_label_reference(const std::string
& label_name
,
1900 Location location
, bool issue_goto_errors
)
1902 go_assert(!this->functions_
.empty());
1903 Function
* func
= this->functions_
.back().function
->func_value();
1904 return func
->add_label_reference(this, label_name
, location
,
1908 // Return the current binding state.
1911 Gogo::bindings_snapshot(Location location
)
1913 return new Bindings_snapshot(this->current_block(), location
);
1919 Gogo::add_statement(Statement
* statement
)
1921 go_assert(!this->functions_
.empty()
1922 && !this->functions_
.back().blocks
.empty());
1923 this->functions_
.back().blocks
.back()->add_statement(statement
);
1929 Gogo::add_block(Block
* block
, Location location
)
1931 go_assert(!this->functions_
.empty()
1932 && !this->functions_
.back().blocks
.empty());
1933 Statement
* statement
= Statement::make_block_statement(block
, location
);
1934 this->functions_
.back().blocks
.back()->add_statement(statement
);
1940 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
1943 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
1949 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
1951 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
1953 if (!this->in_global_scope() && no
->is_type())
1955 Named_object
* f
= this->functions_
.back().function
;
1957 if (f
->is_function())
1958 index
= f
->func_value()->new_local_type_index();
1961 no
->type_value()->set_in_function(f
, index
);
1965 // Add a named type.
1968 Gogo::add_named_type(Named_type
* type
)
1970 go_assert(this->in_global_scope());
1971 this->current_bindings()->add_named_type(type
);
1977 Gogo::declare_type(const std::string
& name
, Location location
)
1979 Bindings
* bindings
= this->current_bindings();
1980 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
1981 if (!this->in_global_scope() && no
->is_type_declaration())
1983 Named_object
* f
= this->functions_
.back().function
;
1985 if (f
->is_function())
1986 index
= f
->func_value()->new_local_type_index();
1989 no
->type_declaration_value()->set_in_function(f
, index
);
1994 // Declare a type at the package level.
1997 Gogo::declare_package_type(const std::string
& name
, Location location
)
1999 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2002 // Declare a function at the package level.
2005 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2008 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2012 // Define a type which was already declared.
2015 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2017 this->current_bindings()->define_type(no
, type
);
2023 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2025 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2028 // In a function the middle-end wants to see a DECL_EXPR node.
2030 && no
->is_variable()
2031 && !no
->var_value()->is_parameter()
2032 && !this->functions_
.empty())
2033 this->add_statement(Statement::make_variable_declaration(no
));
2038 // Add a sink--a reference to the blank identifier _.
2043 return Named_object::make_sink();
2046 // Add a named object for a dot import.
2049 Gogo::add_dot_import_object(Named_object
* no
)
2051 // If the name already exists, then it was defined in some file seen
2052 // earlier. If the earlier name is just a declaration, don't add
2053 // this name, because that will cause the previous declaration to
2054 // merge to this imported name, which should not happen. Just add
2055 // this name to the list of file block names to get appropriate
2056 // errors if we see a later definition.
2057 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2058 if (e
!= NULL
&& e
->package() == NULL
)
2060 if (e
->is_unknown())
2062 if (e
->package() == NULL
2063 && (e
->is_type_declaration()
2064 || e
->is_function_declaration()
2065 || e
->is_unknown()))
2067 this->add_file_block_name(no
->name(), no
->location());
2072 this->current_bindings()->add_named_object(no
);
2075 // Mark all local variables used. This is used when some types of
2076 // parse error occur.
2079 Gogo::mark_locals_used()
2081 for (Open_functions::iterator pf
= this->functions_
.begin();
2082 pf
!= this->functions_
.end();
2085 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2086 pb
!= pf
->blocks
.end();
2088 (*pb
)->bindings()->mark_locals_used();
2092 // Record that we've seen an interface type.
2095 Gogo::record_interface_type(Interface_type
* itype
)
2097 this->interface_types_
.push_back(itype
);
2100 // Return an erroneous name that indicates that an error has already
2104 Gogo::erroneous_name()
2106 static int erroneous_count
;
2108 snprintf(name
, sizeof name
, "$erroneous%d", erroneous_count
);
2113 // Return whether a name is an erroneous name.
2116 Gogo::is_erroneous_name(const std::string
& name
)
2118 return name
.compare(0, 10, "$erroneous") == 0;
2121 // Return a name for a thunk object.
2126 static int thunk_count
;
2127 char thunk_name
[50];
2128 snprintf(thunk_name
, sizeof thunk_name
, "$thunk%d", thunk_count
);
2133 // Return whether a function is a thunk.
2136 Gogo::is_thunk(const Named_object
* no
)
2138 return no
->name().compare(0, 6, "$thunk") == 0;
2141 // Define the global names. We do this only after parsing all the
2142 // input files, because the program might define the global names
2146 Gogo::define_global_names()
2148 for (Bindings::const_declarations_iterator p
=
2149 this->globals_
->begin_declarations();
2150 p
!= this->globals_
->end_declarations();
2153 Named_object
* global_no
= p
->second
;
2154 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2155 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2159 if (no
->is_type_declaration())
2161 if (global_no
->is_type())
2163 if (no
->type_declaration_value()->has_methods())
2164 error_at(no
->location(),
2165 "may not define methods for global type");
2166 no
->set_type_value(global_no
->type_value());
2170 error_at(no
->location(), "expected type");
2171 Type
* errtype
= Type::make_error_type();
2173 Named_object::make_type("erroneous_type", NULL
, errtype
,
2174 Linemap::predeclared_location());
2175 no
->set_type_value(err
->type_value());
2178 else if (no
->is_unknown())
2179 no
->unknown_value()->set_real_named_object(global_no
);
2182 // Give an error if any name is defined in both the package block
2183 // and the file block. For example, this can happen if one file
2184 // imports "fmt" and another file defines a global variable fmt.
2185 for (Bindings::const_declarations_iterator p
=
2186 this->package_
->bindings()->begin_declarations();
2187 p
!= this->package_
->bindings()->end_declarations();
2190 if (p
->second
->is_unknown()
2191 && p
->second
->unknown_value()->real_named_object() == NULL
)
2193 // No point in warning about an undefined name, as we will
2194 // get other errors later anyhow.
2197 File_block_names::const_iterator pf
=
2198 this->file_block_names_
.find(p
->second
->name());
2199 if (pf
!= this->file_block_names_
.end())
2201 std::string n
= p
->second
->message_name();
2202 error_at(p
->second
->location(),
2203 "%qs defined as both imported name and global name",
2205 inform(pf
->second
, "%qs imported here", n
.c_str());
2208 // No package scope identifier may be named "init".
2209 if (!p
->second
->is_function()
2210 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2212 error_at(p
->second
->location(),
2213 "cannot declare init - must be func");
2218 // Clear out names in file scope.
2221 Gogo::clear_file_scope()
2223 this->package_
->bindings()->clear_file_scope(this);
2225 // Warn about packages which were imported but not used.
2226 bool quiet
= saw_errors();
2227 for (Packages::iterator p
= this->packages_
.begin();
2228 p
!= this->packages_
.end();
2231 Package
* package
= p
->second
;
2232 if (package
!= this->package_
2233 && package
->is_imported()
2235 && !package
->uses_sink_alias()
2237 error_at(package
->location(), "imported and not used: %s",
2238 Gogo::message_name(package
->package_name()).c_str());
2239 package
->clear_is_imported();
2240 package
->clear_uses_sink_alias();
2241 package
->clear_used();
2245 // Queue up a type specific function for later writing. These are
2246 // written out in write_specific_type_functions, called after the
2247 // parse tree is lowered.
2250 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
,
2251 const std::string
& hash_name
,
2252 Function_type
* hash_fntype
,
2253 const std::string
& equal_name
,
2254 Function_type
* equal_fntype
)
2256 go_assert(!this->specific_type_functions_are_written_
);
2257 go_assert(!this->in_global_scope());
2258 Specific_type_function
* tsf
= new Specific_type_function(type
, name
,
2263 this->specific_type_functions_
.push_back(tsf
);
2266 // Look for types which need specific hash or equality functions.
2268 class Specific_type_functions
: public Traverse
2271 Specific_type_functions(Gogo
* gogo
)
2272 : Traverse(traverse_types
),
2284 Specific_type_functions::type(Type
* t
)
2286 Named_object
* hash_fn
;
2287 Named_object
* equal_fn
;
2288 switch (t
->classification())
2290 case Type::TYPE_NAMED
:
2292 Named_type
* nt
= t
->named_type();
2293 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2294 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2296 // If this is a struct type, we don't want to make functions
2297 // for the unnamed struct.
2298 Type
* rt
= nt
->real_type();
2299 if (rt
->struct_type() == NULL
)
2301 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2302 return TRAVERSE_EXIT
;
2306 // If this type is defined in another package, then we don't
2307 // need to worry about the unexported fields.
2308 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2309 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2310 for (Struct_field_list::const_iterator p
= fields
->begin();
2314 if (is_defined_elsewhere
2315 && Gogo::is_hidden_name(p
->field_name()))
2317 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2318 return TRAVERSE_EXIT
;
2322 return TRAVERSE_SKIP_COMPONENTS
;
2325 case Type::TYPE_STRUCT
:
2326 case Type::TYPE_ARRAY
:
2327 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2328 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2335 return TRAVERSE_CONTINUE
;
2338 // Write out type specific functions.
2341 Gogo::write_specific_type_functions()
2343 Specific_type_functions
stf(this);
2344 this->traverse(&stf
);
2346 while (!this->specific_type_functions_
.empty())
2348 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2349 this->specific_type_functions_
.pop_back();
2350 tsf
->type
->write_specific_type_functions(this, tsf
->name
,
2357 this->specific_type_functions_are_written_
= true;
2360 // Traverse the tree.
2363 Gogo::traverse(Traverse
* traverse
)
2365 // Traverse the current package first for consistency. The other
2366 // packages will only contain imported types, constants, and
2368 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2370 for (Packages::const_iterator p
= this->packages_
.begin();
2371 p
!= this->packages_
.end();
2374 if (p
->second
!= this->package_
)
2376 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2382 // Add a type to verify. This is used for types of sink variables, in
2383 // order to give appropriate error messages.
2386 Gogo::add_type_to_verify(Type
* type
)
2388 this->verify_types_
.push_back(type
);
2391 // Traversal class used to verify types.
2393 class Verify_types
: public Traverse
2397 : Traverse(traverse_types
)
2404 // Verify that a type is correct.
2407 Verify_types::type(Type
* t
)
2410 return TRAVERSE_SKIP_COMPONENTS
;
2411 return TRAVERSE_CONTINUE
;
2414 // Verify that all types are correct.
2417 Gogo::verify_types()
2419 Verify_types traverse
;
2420 this->traverse(&traverse
);
2422 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2423 p
!= this->verify_types_
.end();
2426 this->verify_types_
.clear();
2429 // Traversal class used to lower parse tree.
2431 class Lower_parse_tree
: public Traverse
2434 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2435 : Traverse(traverse_variables
2436 | traverse_constants
2437 | traverse_functions
2438 | traverse_statements
2439 | traverse_expressions
),
2440 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2444 set_inserter(const Statement_inserter
* inserter
)
2445 { this->inserter_
= *inserter
; }
2448 variable(Named_object
*);
2451 constant(Named_object
*, bool);
2454 function(Named_object
*);
2457 statement(Block
*, size_t* pindex
, Statement
*);
2460 expression(Expression
**);
2465 // The function we are traversing.
2466 Named_object
* function_
;
2467 // Value to use for the predeclared constant iota.
2469 // Current statement inserter for use by expressions.
2470 Statement_inserter inserter_
;
2476 Lower_parse_tree::variable(Named_object
* no
)
2478 if (!no
->is_variable())
2479 return TRAVERSE_CONTINUE
;
2481 if (no
->is_variable() && no
->var_value()->is_global())
2483 // Global variables can have loops in their initialization
2484 // expressions. This is handled in lower_init_expression.
2485 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2487 return TRAVERSE_CONTINUE
;
2490 // This is a local variable. We are going to return
2491 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2492 // initialization expression when we reach the variable declaration
2493 // statement. However, that means that we need to traverse the type
2495 if (no
->var_value()->has_type())
2497 Type
* type
= no
->var_value()->type();
2500 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2501 return TRAVERSE_EXIT
;
2504 go_assert(!no
->var_value()->has_pre_init());
2506 return TRAVERSE_SKIP_COMPONENTS
;
2509 // Lower constants. We handle constants specially so that we can set
2510 // the right value for the predeclared constant iota. This works in
2511 // conjunction with the way we lower Const_expression objects.
2514 Lower_parse_tree::constant(Named_object
* no
, bool)
2516 Named_constant
* nc
= no
->const_value();
2518 // Don't get into trouble if the constant's initializer expression
2519 // refers to the constant itself.
2521 return TRAVERSE_CONTINUE
;
2524 go_assert(this->iota_value_
== -1);
2525 this->iota_value_
= nc
->iota_value();
2526 nc
->traverse_expression(this);
2527 this->iota_value_
= -1;
2529 nc
->clear_lowering();
2531 // We will traverse the expression a second time, but that will be
2534 return TRAVERSE_CONTINUE
;
2537 // Lower the body of a function, and set the closure type. Record the
2538 // function while lowering it, so that we can pass it down when
2539 // lowering an expression.
2542 Lower_parse_tree::function(Named_object
* no
)
2544 no
->func_value()->set_closure_type();
2546 go_assert(this->function_
== NULL
);
2547 this->function_
= no
;
2548 int t
= no
->func_value()->traverse(this);
2549 this->function_
= NULL
;
2551 if (t
== TRAVERSE_EXIT
)
2553 return TRAVERSE_SKIP_COMPONENTS
;
2556 // Lower statement parse trees.
2559 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2561 // Because we explicitly traverse the statement's contents
2562 // ourselves, we want to skip block statements here. There is
2563 // nothing to lower in a block statement.
2564 if (sorig
->is_block_statement())
2565 return TRAVERSE_CONTINUE
;
2567 Statement_inserter
hold_inserter(this->inserter_
);
2568 this->inserter_
= Statement_inserter(block
, pindex
);
2570 // Lower the expressions first.
2571 int t
= sorig
->traverse_contents(this);
2572 if (t
== TRAVERSE_EXIT
)
2574 this->inserter_
= hold_inserter
;
2578 // Keep lowering until nothing changes.
2579 Statement
* s
= sorig
;
2582 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2587 t
= s
->traverse_contents(this);
2588 if (t
== TRAVERSE_EXIT
)
2590 this->inserter_
= hold_inserter
;
2596 block
->replace_statement(*pindex
, s
);
2598 this->inserter_
= hold_inserter
;
2599 return TRAVERSE_SKIP_COMPONENTS
;
2602 // Lower expression parse trees.
2605 Lower_parse_tree::expression(Expression
** pexpr
)
2607 // We have to lower all subexpressions first, so that we can get
2608 // their type if necessary. This is awkward, because we don't have
2609 // a postorder traversal pass.
2610 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2611 return TRAVERSE_EXIT
;
2612 // Keep lowering until nothing changes.
2615 Expression
* e
= *pexpr
;
2616 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2617 &this->inserter_
, this->iota_value_
);
2620 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2621 return TRAVERSE_EXIT
;
2624 return TRAVERSE_SKIP_COMPONENTS
;
2627 // Lower the parse tree. This is called after the parse is complete,
2628 // when all names should be resolved.
2631 Gogo::lower_parse_tree()
2633 Lower_parse_tree
lower_parse_tree(this, NULL
);
2634 this->traverse(&lower_parse_tree
);
2640 Gogo::lower_block(Named_object
* function
, Block
* block
)
2642 Lower_parse_tree
lower_parse_tree(this, function
);
2643 block
->traverse(&lower_parse_tree
);
2646 // Lower an expression. INSERTER may be NULL, in which case the
2647 // expression had better not need to create any temporaries.
2650 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2653 Lower_parse_tree
lower_parse_tree(this, function
);
2654 if (inserter
!= NULL
)
2655 lower_parse_tree
.set_inserter(inserter
);
2656 lower_parse_tree
.expression(pexpr
);
2659 // Lower a constant. This is called when lowering a reference to a
2660 // constant. We have to make sure that the constant has already been
2664 Gogo::lower_constant(Named_object
* no
)
2666 go_assert(no
->is_const());
2667 Lower_parse_tree
lower(this, NULL
);
2668 lower
.constant(no
, false);
2671 // Traverse the tree to create function descriptors as needed.
2673 class Create_function_descriptors
: public Traverse
2676 Create_function_descriptors(Gogo
* gogo
)
2677 : Traverse(traverse_functions
| traverse_expressions
),
2682 function(Named_object
*);
2685 expression(Expression
**);
2691 // Create a descriptor for every top-level exported function.
2694 Create_function_descriptors::function(Named_object
* no
)
2696 if (no
->is_function()
2697 && no
->func_value()->enclosing() == NULL
2698 && !no
->func_value()->is_method()
2699 && !Gogo::is_hidden_name(no
->name())
2700 && !Gogo::is_thunk(no
))
2701 no
->func_value()->descriptor(this->gogo_
, no
);
2703 return TRAVERSE_CONTINUE
;
2706 // If we see a function referenced in any way other than calling it,
2707 // create a descriptor for it.
2710 Create_function_descriptors::expression(Expression
** pexpr
)
2712 Expression
* expr
= *pexpr
;
2714 Func_expression
* fe
= expr
->func_expression();
2717 // We would not get here for a call to this function, so this is
2718 // a reference to a function other than calling it. We need a
2720 if (fe
->closure() != NULL
)
2721 return TRAVERSE_CONTINUE
;
2722 Named_object
* no
= fe
->named_object();
2723 if (no
->is_function() && !no
->func_value()->is_method())
2724 no
->func_value()->descriptor(this->gogo_
, no
);
2725 else if (no
->is_function_declaration()
2726 && !no
->func_declaration_value()->type()->is_method()
2727 && !Linemap::is_predeclared_location(no
->location()))
2728 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
2729 return TRAVERSE_CONTINUE
;
2732 Bound_method_expression
* bme
= expr
->bound_method_expression();
2735 // We would not get here for a call to this method, so this is a
2736 // method value. We need to create a thunk.
2737 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
2739 return TRAVERSE_CONTINUE
;
2742 Interface_field_reference_expression
* ifre
=
2743 expr
->interface_field_reference_expression();
2746 // We would not get here for a call to this interface method, so
2747 // this is a method value. We need to create a thunk.
2748 Interface_type
* type
= ifre
->expr()->type()->interface_type();
2750 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
2752 return TRAVERSE_CONTINUE
;
2755 Call_expression
* ce
= expr
->call_expression();
2758 Expression
* fn
= ce
->fn();
2759 if (fn
->func_expression() != NULL
2760 || fn
->bound_method_expression() != NULL
2761 || fn
->interface_field_reference_expression() != NULL
)
2763 // Traverse the arguments but not the function.
2764 Expression_list
* args
= ce
->args();
2767 if (args
->traverse(this) == TRAVERSE_EXIT
)
2768 return TRAVERSE_EXIT
;
2770 return TRAVERSE_SKIP_COMPONENTS
;
2774 return TRAVERSE_CONTINUE
;
2777 // Create function descriptors as needed. We need a function
2778 // descriptor for all exported functions and for all functions that
2779 // are referenced without being called.
2782 Gogo::create_function_descriptors()
2784 // Create a function descriptor for any exported function that is
2785 // declared in this package. This is so that we have a descriptor
2786 // for functions written in assembly. Gather the descriptors first
2787 // so that we don't add declarations while looping over them.
2788 std::vector
<Named_object
*> fndecls
;
2789 Bindings
* b
= this->package_
->bindings();
2790 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
2791 p
!= b
->end_declarations();
2794 Named_object
* no
= p
->second
;
2795 if (no
->is_function_declaration()
2796 && !no
->func_declaration_value()->type()->is_method()
2797 && !Linemap::is_predeclared_location(no
->location())
2798 && !Gogo::is_hidden_name(no
->name()))
2799 fndecls
.push_back(no
);
2801 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
2804 (*p
)->func_declaration_value()->descriptor(this, *p
);
2807 Create_function_descriptors
cfd(this);
2808 this->traverse(&cfd
);
2811 // Look for interface types to finalize methods of inherited
2814 class Finalize_methods
: public Traverse
2817 Finalize_methods(Gogo
* gogo
)
2818 : Traverse(traverse_types
),
2829 // Finalize the methods of an interface type.
2832 Finalize_methods::type(Type
* t
)
2834 // Check the classification so that we don't finalize the methods
2835 // twice for a named interface type.
2836 switch (t
->classification())
2838 case Type::TYPE_INTERFACE
:
2839 t
->interface_type()->finalize_methods();
2842 case Type::TYPE_NAMED
:
2844 // We have to finalize the methods of the real type first.
2845 // But if the real type is a struct type, then we only want to
2846 // finalize the methods of the field types, not of the struct
2847 // type itself. We don't want to add methods to the struct,
2848 // since it has a name.
2849 Named_type
* nt
= t
->named_type();
2850 Type
* rt
= nt
->real_type();
2851 if (rt
->classification() != Type::TYPE_STRUCT
)
2853 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2854 return TRAVERSE_EXIT
;
2858 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2859 return TRAVERSE_EXIT
;
2862 nt
->finalize_methods(this->gogo_
);
2864 // If this type is defined in a different package, then finalize the
2865 // types of all the methods, since we won't see them otherwise.
2866 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
2868 const Methods
* methods
= nt
->methods();
2869 for (Methods::const_iterator p
= methods
->begin();
2870 p
!= methods
->end();
2873 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
2874 return TRAVERSE_EXIT
;
2878 // Finalize the types of all methods that are declared but not
2879 // defined, since we won't see the declarations otherwise.
2880 if (nt
->named_object()->package() == NULL
2881 && nt
->local_methods() != NULL
)
2883 const Bindings
* methods
= nt
->local_methods();
2884 for (Bindings::const_declarations_iterator p
=
2885 methods
->begin_declarations();
2886 p
!= methods
->end_declarations();
2889 if (p
->second
->is_function_declaration())
2891 Type
* mt
= p
->second
->func_declaration_value()->type();
2892 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
2893 return TRAVERSE_EXIT
;
2898 return TRAVERSE_SKIP_COMPONENTS
;
2901 case Type::TYPE_STRUCT
:
2902 // Traverse the field types first in case there is an embedded
2903 // field with methods that the struct should inherit.
2904 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2905 return TRAVERSE_EXIT
;
2906 t
->struct_type()->finalize_methods(this->gogo_
);
2907 return TRAVERSE_SKIP_COMPONENTS
;
2913 return TRAVERSE_CONTINUE
;
2916 // Finalize method lists and build stub methods for types.
2919 Gogo::finalize_methods()
2921 Finalize_methods
finalize(this);
2922 this->traverse(&finalize
);
2925 // Set types for unspecified variables and constants.
2928 Gogo::determine_types()
2930 Bindings
* bindings
= this->current_bindings();
2931 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
2932 p
!= bindings
->end_definitions();
2935 if ((*p
)->is_function())
2936 (*p
)->func_value()->determine_types();
2937 else if ((*p
)->is_variable())
2938 (*p
)->var_value()->determine_type();
2939 else if ((*p
)->is_const())
2940 (*p
)->const_value()->determine_type();
2942 // See if a variable requires us to build an initialization
2943 // function. We know that we will see all global variables
2945 if (!this->need_init_fn_
&& (*p
)->is_variable())
2947 Variable
* variable
= (*p
)->var_value();
2949 // If this is a global variable which requires runtime
2950 // initialization, we need an initialization function.
2951 if (!variable
->is_global())
2953 else if (variable
->init() == NULL
)
2955 else if (variable
->type()->interface_type() != NULL
)
2956 this->need_init_fn_
= true;
2957 else if (variable
->init()->is_constant())
2959 else if (!variable
->init()->is_composite_literal())
2960 this->need_init_fn_
= true;
2961 else if (variable
->init()->is_nonconstant_composite_literal())
2962 this->need_init_fn_
= true;
2964 // If this is a global variable which holds a pointer value,
2965 // then we need an initialization function to register it as a
2967 if (variable
->is_global() && variable
->type()->has_pointer())
2968 this->need_init_fn_
= true;
2972 // Determine the types of constants in packages.
2973 for (Packages::const_iterator p
= this->packages_
.begin();
2974 p
!= this->packages_
.end();
2976 p
->second
->determine_types();
2979 // Traversal class used for type checking.
2981 class Check_types_traverse
: public Traverse
2984 Check_types_traverse(Gogo
* gogo
)
2985 : Traverse(traverse_variables
2986 | traverse_constants
2987 | traverse_functions
2988 | traverse_statements
2989 | traverse_expressions
),
2994 variable(Named_object
*);
2997 constant(Named_object
*, bool);
3000 function(Named_object
*);
3003 statement(Block
*, size_t* pindex
, Statement
*);
3006 expression(Expression
**);
3013 // Check that a variable initializer has the right type.
3016 Check_types_traverse::variable(Named_object
* named_object
)
3018 if (named_object
->is_variable())
3020 Variable
* var
= named_object
->var_value();
3022 // Give error if variable type is not defined.
3023 var
->type()->base();
3025 Expression
* init
= var
->init();
3028 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3031 error_at(var
->location(), "incompatible type in initialization");
3033 error_at(var
->location(),
3034 "incompatible type in initialization (%s)",
3038 else if (!var
->is_used()
3039 && !var
->is_global()
3040 && !var
->is_parameter()
3041 && !var
->is_receiver()
3042 && !var
->type()->is_error()
3043 && (init
== NULL
|| !init
->is_error_expression())
3044 && !Lex::is_invalid_identifier(named_object
->name()))
3045 error_at(var
->location(), "%qs declared and not used",
3046 named_object
->message_name().c_str());
3048 return TRAVERSE_CONTINUE
;
3051 // Check that a constant initializer has the right type.
3054 Check_types_traverse::constant(Named_object
* named_object
, bool)
3056 Named_constant
* constant
= named_object
->const_value();
3057 Type
* ctype
= constant
->type();
3058 if (ctype
->integer_type() == NULL
3059 && ctype
->float_type() == NULL
3060 && ctype
->complex_type() == NULL
3061 && !ctype
->is_boolean_type()
3062 && !ctype
->is_string_type())
3064 if (ctype
->is_nil_type())
3065 error_at(constant
->location(), "const initializer cannot be nil");
3066 else if (!ctype
->is_error())
3067 error_at(constant
->location(), "invalid constant type");
3068 constant
->set_error();
3070 else if (!constant
->expr()->is_constant())
3072 error_at(constant
->expr()->location(), "expression is not constant");
3073 constant
->set_error();
3075 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3078 error_at(constant
->location(),
3079 "initialization expression has wrong type");
3080 constant
->set_error();
3082 return TRAVERSE_CONTINUE
;
3085 // There are no types to check in a function, but this is where we
3086 // issue warnings about labels which are defined but not referenced.
3089 Check_types_traverse::function(Named_object
* no
)
3091 no
->func_value()->check_labels();
3092 return TRAVERSE_CONTINUE
;
3095 // Check that types are valid in a statement.
3098 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3100 s
->check_types(this->gogo_
);
3101 return TRAVERSE_CONTINUE
;
3104 // Check that types are valid in an expression.
3107 Check_types_traverse::expression(Expression
** expr
)
3109 (*expr
)->check_types(this->gogo_
);
3110 return TRAVERSE_CONTINUE
;
3113 // Check that types are valid.
3118 Check_types_traverse
traverse(this);
3119 this->traverse(&traverse
);
3122 // Check the types in a single block.
3125 Gogo::check_types_in_block(Block
* block
)
3127 Check_types_traverse
traverse(this);
3128 block
->traverse(&traverse
);
3131 // A traversal class used to find a single shortcut operator within an
3134 class Find_shortcut
: public Traverse
3138 : Traverse(traverse_blocks
3139 | traverse_statements
3140 | traverse_expressions
),
3144 // A pointer to the expression which was found, or NULL if none was
3148 { return this->found_
; }
3153 { return TRAVERSE_SKIP_COMPONENTS
; }
3156 statement(Block
*, size_t*, Statement
*)
3157 { return TRAVERSE_SKIP_COMPONENTS
; }
3160 expression(Expression
**);
3163 Expression
** found_
;
3166 // Find a shortcut expression.
3169 Find_shortcut::expression(Expression
** pexpr
)
3171 Expression
* expr
= *pexpr
;
3172 Binary_expression
* be
= expr
->binary_expression();
3174 return TRAVERSE_CONTINUE
;
3175 Operator op
= be
->op();
3176 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3177 return TRAVERSE_CONTINUE
;
3178 go_assert(this->found_
== NULL
);
3179 this->found_
= pexpr
;
3180 return TRAVERSE_EXIT
;
3183 // A traversal class used to turn shortcut operators into explicit if
3186 class Shortcuts
: public Traverse
3189 Shortcuts(Gogo
* gogo
)
3190 : Traverse(traverse_variables
3191 | traverse_statements
),
3197 variable(Named_object
*);
3200 statement(Block
*, size_t*, Statement
*);
3203 // Convert a shortcut operator.
3205 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3211 // Remove shortcut operators in a single statement.
3214 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3216 // FIXME: This approach doesn't work for switch statements, because
3217 // we add the new statements before the whole switch when we need to
3218 // instead add them just before the switch expression. The right
3219 // fix is probably to lower switch statements with nonconstant cases
3220 // to a series of conditionals.
3221 if (s
->switch_statement() != NULL
)
3222 return TRAVERSE_CONTINUE
;
3226 Find_shortcut find_shortcut
;
3228 // If S is a variable declaration, then ordinary traversal won't
3229 // do anything. We want to explicitly traverse the
3230 // initialization expression if there is one.
3231 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3232 Expression
* init
= NULL
;
3234 s
->traverse_contents(&find_shortcut
);
3237 init
= vds
->var()->var_value()->init();
3239 return TRAVERSE_CONTINUE
;
3240 init
->traverse(&init
, &find_shortcut
);
3242 Expression
** pshortcut
= find_shortcut
.found();
3243 if (pshortcut
== NULL
)
3244 return TRAVERSE_CONTINUE
;
3246 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3247 block
->insert_statement_before(*pindex
, snew
);
3250 if (pshortcut
== &init
)
3251 vds
->var()->var_value()->set_init(init
);
3255 // Remove shortcut operators in the initializer of a global variable.
3258 Shortcuts::variable(Named_object
* no
)
3260 if (no
->is_result_variable())
3261 return TRAVERSE_CONTINUE
;
3262 Variable
* var
= no
->var_value();
3263 Expression
* init
= var
->init();
3264 if (!var
->is_global() || init
== NULL
)
3265 return TRAVERSE_CONTINUE
;
3269 Find_shortcut find_shortcut
;
3270 init
->traverse(&init
, &find_shortcut
);
3271 Expression
** pshortcut
= find_shortcut
.found();
3272 if (pshortcut
== NULL
)
3273 return TRAVERSE_CONTINUE
;
3275 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3276 var
->add_preinit_statement(this->gogo_
, snew
);
3277 if (pshortcut
== &init
)
3278 var
->set_init(init
);
3282 // Given an expression which uses a shortcut operator, return a
3283 // statement which implements it, and update *PSHORTCUT accordingly.
3286 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3288 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3289 Expression
* left
= shortcut
->left();
3290 Expression
* right
= shortcut
->right();
3291 Location loc
= shortcut
->location();
3293 Block
* retblock
= new Block(enclosing
, loc
);
3294 retblock
->set_end_location(loc
);
3296 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3298 retblock
->add_statement(ts
);
3300 Block
* block
= new Block(retblock
, loc
);
3301 block
->set_end_location(loc
);
3302 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
3303 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
3304 block
->add_statement(assign
);
3306 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
3307 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
3308 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
3310 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
3312 retblock
->add_statement(if_statement
);
3314 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
3318 // Now convert any shortcut operators in LEFT and RIGHT.
3319 Shortcuts
shortcuts(this->gogo_
);
3320 retblock
->traverse(&shortcuts
);
3322 return Statement::make_block_statement(retblock
, loc
);
3325 // Turn shortcut operators into explicit if statements. Doing this
3326 // considerably simplifies the order of evaluation rules.
3329 Gogo::remove_shortcuts()
3331 Shortcuts
shortcuts(this);
3332 this->traverse(&shortcuts
);
3335 // A traversal class which finds all the expressions which must be
3336 // evaluated in order within a statement or larger expression. This
3337 // is used to implement the rules about order of evaluation.
3339 class Find_eval_ordering
: public Traverse
3342 typedef std::vector
<Expression
**> Expression_pointers
;
3345 Find_eval_ordering()
3346 : Traverse(traverse_blocks
3347 | traverse_statements
3348 | traverse_expressions
),
3354 { return this->exprs_
.size(); }
3356 typedef Expression_pointers::const_iterator const_iterator
;
3360 { return this->exprs_
.begin(); }
3364 { return this->exprs_
.end(); }
3369 { return TRAVERSE_SKIP_COMPONENTS
; }
3372 statement(Block
*, size_t*, Statement
*)
3373 { return TRAVERSE_SKIP_COMPONENTS
; }
3376 expression(Expression
**);
3379 // A list of pointers to expressions with side-effects.
3380 Expression_pointers exprs_
;
3383 // If an expression must be evaluated in order, put it on the list.
3386 Find_eval_ordering::expression(Expression
** expression_pointer
)
3388 // We have to look at subexpressions before this one.
3389 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3390 return TRAVERSE_EXIT
;
3391 if ((*expression_pointer
)->must_eval_in_order())
3392 this->exprs_
.push_back(expression_pointer
);
3393 return TRAVERSE_SKIP_COMPONENTS
;
3396 // A traversal class for ordering evaluations.
3398 class Order_eval
: public Traverse
3401 Order_eval(Gogo
* gogo
)
3402 : Traverse(traverse_variables
3403 | traverse_statements
),
3408 variable(Named_object
*);
3411 statement(Block
*, size_t*, Statement
*);
3418 // Implement the order of evaluation rules for a statement.
3421 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3423 // FIXME: This approach doesn't work for switch statements, because
3424 // we add the new statements before the whole switch when we need to
3425 // instead add them just before the switch expression. The right
3426 // fix is probably to lower switch statements with nonconstant cases
3427 // to a series of conditionals.
3428 if (s
->switch_statement() != NULL
)
3429 return TRAVERSE_CONTINUE
;
3431 Find_eval_ordering find_eval_ordering
;
3433 // If S is a variable declaration, then ordinary traversal won't do
3434 // anything. We want to explicitly traverse the initialization
3435 // expression if there is one.
3436 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3437 Expression
* init
= NULL
;
3438 Expression
* orig_init
= NULL
;
3440 s
->traverse_contents(&find_eval_ordering
);
3443 init
= vds
->var()->var_value()->init();
3445 return TRAVERSE_CONTINUE
;
3448 // It might seem that this could be
3449 // init->traverse_subexpressions. Unfortunately that can fail
3452 // newvar, err := call(arg())
3453 // Here newvar will have an init of call result 0 of
3454 // call(arg()). If we only traverse subexpressions, we will
3455 // only find arg(), and we won't bother to move anything out.
3456 // Then we get to the assignment to err, we will traverse the
3457 // whole statement, and this time we will find both call() and
3458 // arg(), and so we will move them out. This will cause them to
3459 // be put into temporary variables before the assignment to err
3460 // but after the declaration of newvar. To avoid that problem,
3461 // we traverse the entire expression here.
3462 Expression::traverse(&init
, &find_eval_ordering
);
3465 size_t c
= find_eval_ordering
.size();
3467 return TRAVERSE_CONTINUE
;
3469 // If there is only one expression with a side-effect, we can
3470 // usually leave it in place.
3473 switch (s
->classification())
3475 case Statement::STATEMENT_ASSIGNMENT
:
3476 // For an assignment statement, we need to evaluate an
3477 // expression on the right hand side before we evaluate any
3478 // index expression on the left hand side, so for that case
3479 // we always move the expression. Otherwise we mishandle
3480 // m[0] = len(m) where m is a map.
3483 case Statement::STATEMENT_EXPRESSION
:
3485 // If this is a call statement that doesn't return any
3486 // values, it will not have been counted as a value to
3487 // move. We need to move any subexpressions in case they
3488 // are themselves call statements that require passing a
3490 Expression
* expr
= s
->expression_statement()->expr();
3491 if (expr
->call_expression() != NULL
3492 && expr
->call_expression()->result_count() == 0)
3494 return TRAVERSE_CONTINUE
;
3498 // We can leave the expression in place.
3499 return TRAVERSE_CONTINUE
;
3503 bool is_thunk
= s
->thunk_statement() != NULL
;
3504 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3505 p
!= find_eval_ordering
.end();
3508 Expression
** pexpr
= *p
;
3510 // The last expression in a thunk will be the call passed to go
3511 // or defer, which we must not evaluate early.
3512 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3515 Location loc
= (*pexpr
)->location();
3517 if ((*pexpr
)->call_expression() == NULL
3518 || (*pexpr
)->call_expression()->result_count() < 2)
3520 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3523 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3527 // A call expression which returns multiple results needs to
3528 // be handled specially. We can't create a temporary
3529 // because there is no type to give it. Any actual uses of
3530 // the values will be done via Call_result_expressions.
3531 s
= Statement::make_statement(*pexpr
, true);
3534 block
->insert_statement_before(*pindex
, s
);
3538 if (init
!= orig_init
)
3539 vds
->var()->var_value()->set_init(init
);
3541 return TRAVERSE_CONTINUE
;
3544 // Implement the order of evaluation rules for the initializer of a
3548 Order_eval::variable(Named_object
* no
)
3550 if (no
->is_result_variable())
3551 return TRAVERSE_CONTINUE
;
3552 Variable
* var
= no
->var_value();
3553 Expression
* init
= var
->init();
3554 if (!var
->is_global() || init
== NULL
)
3555 return TRAVERSE_CONTINUE
;
3557 Find_eval_ordering find_eval_ordering
;
3558 Expression::traverse(&init
, &find_eval_ordering
);
3560 if (find_eval_ordering
.size() <= 1)
3562 // If there is only one expression with a side-effect, we can
3563 // leave it in place.
3564 return TRAVERSE_SKIP_COMPONENTS
;
3567 Expression
* orig_init
= init
;
3569 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3570 p
!= find_eval_ordering
.end();
3573 Expression
** pexpr
= *p
;
3574 Location loc
= (*pexpr
)->location();
3576 if ((*pexpr
)->call_expression() == NULL
3577 || (*pexpr
)->call_expression()->result_count() < 2)
3579 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3582 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3586 // A call expression which returns multiple results needs to
3587 // be handled specially.
3588 s
= Statement::make_statement(*pexpr
, true);
3590 var
->add_preinit_statement(this->gogo_
, s
);
3593 if (init
!= orig_init
)
3594 var
->set_init(init
);
3596 return TRAVERSE_SKIP_COMPONENTS
;
3599 // Use temporary variables to implement the order of evaluation rules.
3602 Gogo::order_evaluations()
3604 Order_eval
order_eval(this);
3605 this->traverse(&order_eval
);
3608 // Traversal to flatten parse tree after order of evaluation rules are applied.
3610 class Flatten
: public Traverse
3613 Flatten(Gogo
* gogo
, Named_object
* function
)
3614 : Traverse(traverse_variables
3615 | traverse_functions
3616 | traverse_statements
3617 | traverse_expressions
),
3618 gogo_(gogo
), function_(function
), inserter_()
3622 set_inserter(const Statement_inserter
* inserter
)
3623 { this->inserter_
= *inserter
; }
3626 variable(Named_object
*);
3629 function(Named_object
*);
3632 statement(Block
*, size_t* pindex
, Statement
*);
3635 expression(Expression
**);
3640 // The function we are traversing.
3641 Named_object
* function_
;
3642 // Current statement inserter for use by expressions.
3643 Statement_inserter inserter_
;
3646 // Flatten variables.
3649 Flatten::variable(Named_object
* no
)
3651 if (!no
->is_variable())
3652 return TRAVERSE_CONTINUE
;
3654 if (no
->is_variable() && no
->var_value()->is_global())
3656 // Global variables can have loops in their initialization
3657 // expressions. This is handled in flatten_init_expression.
3658 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
3660 return TRAVERSE_CONTINUE
;
3663 go_assert(!no
->var_value()->has_pre_init());
3665 return TRAVERSE_SKIP_COMPONENTS
;
3668 // Flatten the body of a function. Record the function while flattening it,
3669 // so that we can pass it down when flattening an expression.
3672 Flatten::function(Named_object
* no
)
3674 go_assert(this->function_
== NULL
);
3675 this->function_
= no
;
3676 int t
= no
->func_value()->traverse(this);
3677 this->function_
= NULL
;
3679 if (t
== TRAVERSE_EXIT
)
3681 return TRAVERSE_SKIP_COMPONENTS
;
3684 // Flatten statement parse trees.
3687 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3689 // Because we explicitly traverse the statement's contents
3690 // ourselves, we want to skip block statements here. There is
3691 // nothing to flatten in a block statement.
3692 if (sorig
->is_block_statement())
3693 return TRAVERSE_CONTINUE
;
3695 Statement_inserter
hold_inserter(this->inserter_
);
3696 this->inserter_
= Statement_inserter(block
, pindex
);
3698 // Flatten the expressions first.
3699 int t
= sorig
->traverse_contents(this);
3700 if (t
== TRAVERSE_EXIT
)
3702 this->inserter_
= hold_inserter
;
3706 // Keep flattening until nothing changes.
3707 Statement
* s
= sorig
;
3710 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
3715 t
= s
->traverse_contents(this);
3716 if (t
== TRAVERSE_EXIT
)
3718 this->inserter_
= hold_inserter
;
3724 block
->replace_statement(*pindex
, s
);
3726 this->inserter_
= hold_inserter
;
3727 return TRAVERSE_SKIP_COMPONENTS
;
3730 // Flatten expression parse trees.
3733 Flatten::expression(Expression
** pexpr
)
3735 // Keep flattening until nothing changes.
3738 Expression
* e
= *pexpr
;
3739 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3740 return TRAVERSE_EXIT
;
3742 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
3748 return TRAVERSE_SKIP_COMPONENTS
;
3754 Gogo::flatten_block(Named_object
* function
, Block
* block
)
3756 Flatten
flatten(this, function
);
3757 block
->traverse(&flatten
);
3760 // Flatten an expression. INSERTER may be NULL, in which case the
3761 // expression had better not need to create any temporaries.
3764 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
3767 Flatten
flatten(this, function
);
3768 if (inserter
!= NULL
)
3769 flatten
.set_inserter(inserter
);
3770 flatten
.expression(pexpr
);
3776 Flatten
flatten(this, NULL
);
3777 this->traverse(&flatten
);
3780 // Traversal to convert calls to the predeclared recover function to
3781 // pass in an argument indicating whether it can recover from a panic
3784 class Convert_recover
: public Traverse
3787 Convert_recover(Named_object
* arg
)
3788 : Traverse(traverse_expressions
),
3794 expression(Expression
**);
3797 // The argument to pass to the function.
3801 // Convert calls to recover.
3804 Convert_recover::expression(Expression
** pp
)
3806 Call_expression
* ce
= (*pp
)->call_expression();
3807 if (ce
!= NULL
&& ce
->is_recover_call())
3808 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
3810 return TRAVERSE_CONTINUE
;
3813 // Traversal for build_recover_thunks.
3815 class Build_recover_thunks
: public Traverse
3818 Build_recover_thunks(Gogo
* gogo
)
3819 : Traverse(traverse_functions
),
3824 function(Named_object
*);
3828 can_recover_arg(Location
);
3834 // If this function calls recover, turn it into a thunk.
3837 Build_recover_thunks::function(Named_object
* orig_no
)
3839 Function
* orig_func
= orig_no
->func_value();
3840 if (!orig_func
->calls_recover()
3841 || orig_func
->is_recover_thunk()
3842 || orig_func
->has_recover_thunk())
3843 return TRAVERSE_CONTINUE
;
3845 Gogo
* gogo
= this->gogo_
;
3846 Location location
= orig_func
->location();
3851 Function_type
* orig_fntype
= orig_func
->type();
3852 Typed_identifier_list
* new_params
= new Typed_identifier_list();
3853 std::string receiver_name
;
3854 if (orig_fntype
->is_method())
3856 const Typed_identifier
* receiver
= orig_fntype
->receiver();
3857 snprintf(buf
, sizeof buf
, "rt.%u", count
);
3859 receiver_name
= buf
;
3860 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
3861 receiver
->location()));
3863 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
3864 if (orig_params
!= NULL
&& !orig_params
->empty())
3866 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
3867 p
!= orig_params
->end();
3870 snprintf(buf
, sizeof buf
, "pt.%u", count
);
3872 new_params
->push_back(Typed_identifier(buf
, p
->type(),
3876 snprintf(buf
, sizeof buf
, "pr.%u", count
);
3878 std::string can_recover_name
= buf
;
3879 new_params
->push_back(Typed_identifier(can_recover_name
,
3880 Type::lookup_bool_type(),
3881 orig_fntype
->location()));
3883 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
3884 Typed_identifier_list
* new_results
;
3885 if (orig_results
== NULL
|| orig_results
->empty())
3889 new_results
= new Typed_identifier_list();
3890 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
3891 p
!= orig_results
->end();
3893 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
3896 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
3898 orig_fntype
->location());
3899 if (orig_fntype
->is_varargs())
3900 new_fntype
->set_is_varargs();
3902 std::string name
= orig_no
->name();
3903 if (orig_fntype
->is_method())
3904 name
+= "$" + orig_fntype
->receiver()->type()->mangled_name(gogo
);
3906 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
3908 Function
*new_func
= new_no
->func_value();
3909 if (orig_func
->enclosing() != NULL
)
3910 new_func
->set_enclosing(orig_func
->enclosing());
3912 // We build the code for the original function attached to the new
3913 // function, and then swap the original and new function bodies.
3914 // This means that existing references to the original function will
3915 // then refer to the new function. That makes this code a little
3916 // confusing, in that the reference to NEW_NO really refers to the
3917 // other function, not the one we are building.
3919 Expression
* closure
= NULL
;
3920 if (orig_func
->needs_closure())
3922 // For the new function we are creating, declare a new parameter
3923 // variable NEW_CLOSURE_NO and set it to be the closure variable
3924 // of the function. This will be set to the closure value
3925 // passed in by the caller. Then pass a reference to this
3926 // variable as the closure value when calling the original
3927 // function. In other words, simply pass the closure value
3928 // through the thunk we are creating.
3929 Named_object
* orig_closure_no
= orig_func
->closure_var();
3930 Variable
* orig_closure_var
= orig_closure_no
->var_value();
3931 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
3932 false, false, location
);
3933 new_var
->set_is_closure();
3934 snprintf(buf
, sizeof buf
, "closure.%u", count
);
3936 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
3938 new_func
->set_closure_var(new_closure_no
);
3939 closure
= Expression::make_var_reference(new_closure_no
, location
);
3942 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
3944 Expression_list
* args
= new Expression_list();
3945 if (new_params
!= NULL
)
3947 // Note that we skip the last parameter, which is the boolean
3948 // indicating whether recover can succed.
3949 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
3950 p
+ 1 != new_params
->end();
3953 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
3954 go_assert(p_no
!= NULL
3955 && p_no
->is_variable()
3956 && p_no
->var_value()->is_parameter());
3957 args
->push_back(Expression::make_var_reference(p_no
, location
));
3960 args
->push_back(this->can_recover_arg(location
));
3962 gogo
->start_block(location
);
3964 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
3966 // Any varargs call has already been lowered.
3967 call
->set_varargs_are_lowered();
3969 Statement
* s
= Statement::make_return_from_call(call
, location
);
3970 s
->determine_types();
3971 gogo
->add_statement(s
);
3973 Block
* b
= gogo
->finish_block(location
);
3975 gogo
->add_block(b
, location
);
3977 // Lower the call in case it returns multiple results.
3978 gogo
->lower_block(new_no
, b
);
3980 gogo
->finish_function(location
);
3982 // Swap the function bodies and types.
3983 new_func
->swap_for_recover(orig_func
);
3984 orig_func
->set_is_recover_thunk();
3985 new_func
->set_calls_recover();
3986 new_func
->set_has_recover_thunk();
3988 Bindings
* orig_bindings
= orig_func
->block()->bindings();
3989 Bindings
* new_bindings
= new_func
->block()->bindings();
3990 if (orig_fntype
->is_method())
3992 // We changed the receiver to be a regular parameter. We have
3993 // to update the binding accordingly in both functions.
3994 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
3995 go_assert(orig_rec_no
!= NULL
3996 && orig_rec_no
->is_variable()
3997 && !orig_rec_no
->var_value()->is_receiver());
3998 orig_rec_no
->var_value()->set_is_receiver();
4000 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4001 if (new_receiver_name
.empty())
4003 // Find the receiver. It was named "r.NNN" in
4004 // Gogo::start_function.
4005 for (Bindings::const_definitions_iterator p
=
4006 new_bindings
->begin_definitions();
4007 p
!= new_bindings
->end_definitions();
4010 const std::string
& pname((*p
)->name());
4011 if (pname
[0] == 'r' && pname
[1] == '.')
4013 new_receiver_name
= pname
;
4017 go_assert(!new_receiver_name
.empty());
4019 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4020 if (new_rec_no
== NULL
)
4021 go_assert(saw_errors());
4024 go_assert(new_rec_no
->is_variable()
4025 && new_rec_no
->var_value()->is_receiver());
4026 new_rec_no
->var_value()->set_is_not_receiver();
4030 // Because we flipped blocks but not types, the can_recover
4031 // parameter appears in the (now) old bindings as a parameter.
4032 // Change it to a local variable, whereupon it will be discarded.
4033 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4034 go_assert(can_recover_no
!= NULL
4035 && can_recover_no
->is_variable()
4036 && can_recover_no
->var_value()->is_parameter());
4037 orig_bindings
->remove_binding(can_recover_no
);
4039 // Add the can_recover argument to the (now) new bindings, and
4040 // attach it to any recover statements.
4041 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4042 false, true, false, location
);
4043 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4045 Convert_recover
convert_recover(can_recover_no
);
4046 new_func
->traverse(&convert_recover
);
4048 // Update the function pointers in any named results.
4049 new_func
->update_result_variables();
4050 orig_func
->update_result_variables();
4052 return TRAVERSE_CONTINUE
;
4055 // Return the expression to pass for the .can_recover parameter to the
4056 // new function. This indicates whether a call to recover may return
4057 // non-nil. The expression is
4058 // __go_can_recover(__builtin_return_address()).
4061 Build_recover_thunks::can_recover_arg(Location location
)
4063 static Named_object
* builtin_return_address
;
4064 if (builtin_return_address
== NULL
)
4066 const Location bloc
= Linemap::predeclared_location();
4068 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4069 Type
* uint_type
= Type::lookup_integer_type("uint");
4070 param_types
->push_back(Typed_identifier("l", uint_type
, bloc
));
4072 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4073 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4074 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4076 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4077 return_types
, bloc
);
4078 builtin_return_address
=
4079 Named_object::make_function_declaration("__builtin_return_address",
4080 NULL
, fntype
, bloc
);
4081 const char* n
= "__builtin_return_address";
4082 builtin_return_address
->func_declaration_value()->set_asm_name(n
);
4085 static Named_object
* can_recover
;
4086 if (can_recover
== NULL
)
4088 const Location bloc
= Linemap::predeclared_location();
4089 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4090 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4091 param_types
->push_back(Typed_identifier("a", voidptr_type
, bloc
));
4092 Type
* boolean_type
= Type::lookup_bool_type();
4093 Typed_identifier_list
* results
= new Typed_identifier_list();
4094 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4095 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4097 can_recover
= Named_object::make_function_declaration("__go_can_recover",
4100 can_recover
->func_declaration_value()->set_asm_name("__go_can_recover");
4103 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4106 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4107 Expression_list
*args
= new Expression_list();
4108 args
->push_back(zexpr
);
4110 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4112 args
= new Expression_list();
4113 args
->push_back(call
);
4115 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4116 return Expression::make_call(fn
, args
, false, location
);
4119 // Build thunks for functions which call recover. We build a new
4120 // function with an extra parameter, which is whether a call to
4121 // recover can succeed. We then move the body of this function to
4122 // that one. We then turn this function into a thunk which calls the
4123 // new one, passing the value of
4124 // __go_can_recover(__builtin_return_address()). The function will be
4125 // marked as not splitting the stack. This will cooperate with the
4126 // implementation of defer to make recover do the right thing.
4129 Gogo::build_recover_thunks()
4131 Build_recover_thunks
build_recover_thunks(this);
4132 this->traverse(&build_recover_thunks
);
4135 // Build a call to the runtime error function.
4138 Gogo::runtime_error(int code
, Location location
)
4140 Type
* int32_type
= Type::lookup_integer_type("int32");
4141 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4143 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4146 // Look for named types to see whether we need to create an interface
4149 class Build_method_tables
: public Traverse
4152 Build_method_tables(Gogo
* gogo
,
4153 const std::vector
<Interface_type
*>& interfaces
)
4154 : Traverse(traverse_types
),
4155 gogo_(gogo
), interfaces_(interfaces
)
4164 // A list of locally defined interfaces which have hidden methods.
4165 const std::vector
<Interface_type
*>& interfaces_
;
4168 // Build all required interface method tables for types. We need to
4169 // ensure that we have an interface method table for every interface
4170 // which has a hidden method, for every named type which implements
4171 // that interface. Normally we can just build interface method tables
4172 // as we need them. However, in some cases we can require an
4173 // interface method table for an interface defined in a different
4174 // package for a type defined in that package. If that interface and
4175 // type both use a hidden method, that is OK. However, we will not be
4176 // able to build that interface method table when we need it, because
4177 // the type's hidden method will be static. So we have to build it
4178 // here, and just refer it from other packages as needed.
4181 Gogo::build_interface_method_tables()
4186 std::vector
<Interface_type
*> hidden_interfaces
;
4187 hidden_interfaces
.reserve(this->interface_types_
.size());
4188 for (std::vector
<Interface_type
*>::const_iterator pi
=
4189 this->interface_types_
.begin();
4190 pi
!= this->interface_types_
.end();
4193 const Typed_identifier_list
* methods
= (*pi
)->methods();
4194 if (methods
== NULL
)
4196 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4197 pm
!= methods
->end();
4200 if (Gogo::is_hidden_name(pm
->name()))
4202 hidden_interfaces
.push_back(*pi
);
4208 if (!hidden_interfaces
.empty())
4210 // Now traverse the tree looking for all named types.
4211 Build_method_tables
bmt(this, hidden_interfaces
);
4212 this->traverse(&bmt
);
4215 // We no longer need the list of interfaces.
4217 this->interface_types_
.clear();
4220 // This is called for each type. For a named type, for each of the
4221 // interfaces with hidden methods that it implements, create the
4225 Build_method_tables::type(Type
* type
)
4227 Named_type
* nt
= type
->named_type();
4228 Struct_type
* st
= type
->struct_type();
4229 if (nt
!= NULL
|| st
!= NULL
)
4231 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4232 for (std::vector
<Interface_type
*>::const_iterator p
=
4233 this->interfaces_
.begin();
4234 p
!= this->interfaces_
.end();
4237 // We ask whether a pointer to the named type implements the
4238 // interface, because a pointer can implement more methods
4242 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4245 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4246 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4251 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4254 st
->interface_method_table(*p
, false)->get_backend(&context
);
4255 st
->interface_method_table(*p
, true)->get_backend(&context
);
4260 return TRAVERSE_CONTINUE
;
4263 // Return an expression which allocates memory to hold values of type TYPE.
4266 Gogo::allocate_memory(Type
* type
, Location location
)
4268 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4270 Expression::make_type_info(type
, Expression::TYPE_INFO_SIZE
);
4272 // If this package imports unsafe, then it may play games with
4273 // pointers that look like integers. We should be able to determine
4274 // whether or not to use new pointers in libgo/go-new.c. FIXME.
4275 bool use_new_pointers
= this->imported_unsafe_
|| type
->has_pointer();
4276 return Runtime::make_call((use_new_pointers
4278 : Runtime::NEW_NOPOINTERS
),
4279 location
, 2, td
, size
);
4282 // Traversal class used to check for return statements.
4284 class Check_return_statements_traverse
: public Traverse
4287 Check_return_statements_traverse()
4288 : Traverse(traverse_functions
)
4292 function(Named_object
*);
4295 // Check that a function has a return statement if it needs one.
4298 Check_return_statements_traverse::function(Named_object
* no
)
4300 Function
* func
= no
->func_value();
4301 const Function_type
* fntype
= func
->type();
4302 const Typed_identifier_list
* results
= fntype
->results();
4304 // We only need a return statement if there is a return value.
4305 if (results
== NULL
|| results
->empty())
4306 return TRAVERSE_CONTINUE
;
4308 if (func
->block()->may_fall_through())
4309 error_at(func
->block()->end_location(),
4310 "missing return at end of function");
4312 return TRAVERSE_CONTINUE
;
4315 // Check return statements.
4318 Gogo::check_return_statements()
4320 Check_return_statements_traverse traverse
;
4321 this->traverse(&traverse
);
4324 // Work out the package priority. It is one more than the maximum
4325 // priority of an imported package.
4328 Gogo::package_priority() const
4331 for (Packages::const_iterator p
= this->packages_
.begin();
4332 p
!= this->packages_
.end();
4334 if (p
->second
->priority() > priority
)
4335 priority
= p
->second
->priority();
4336 return priority
+ 1;
4339 // Export identifiers as requested.
4344 // For now we always stream to a section. Later we may want to
4345 // support streaming to a separate file.
4346 Stream_to_section stream
;
4348 // Write out either the prefix or pkgpath depending on how we were
4351 std::string pkgpath
;
4352 if (this->pkgpath_from_option_
)
4353 pkgpath
= this->pkgpath_
;
4354 else if (this->prefix_from_option_
)
4355 prefix
= this->prefix_
;
4356 else if (this->is_main_package())
4361 Export
exp(&stream
);
4362 exp
.register_builtin_types(this);
4363 exp
.export_globals(this->package_name(),
4366 this->package_priority(),
4368 (this->need_init_fn_
&& !this->is_main_package()
4369 ? this->get_init_fn_name()
4371 this->imported_init_fns_
,
4372 this->package_
->bindings());
4375 // Find the blocks in order to convert named types defined in blocks.
4377 class Convert_named_types
: public Traverse
4380 Convert_named_types(Gogo
* gogo
)
4381 : Traverse(traverse_blocks
),
4387 block(Block
* block
);
4394 Convert_named_types::block(Block
* block
)
4396 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
4397 return TRAVERSE_CONTINUE
;
4400 // Convert all named types to the backend representation. Since named
4401 // types can refer to other types, this needs to be done in the right
4402 // sequence, which is handled by Named_type::convert. Here we arrange
4403 // to call that for each named type.
4406 Gogo::convert_named_types()
4408 this->convert_named_types_in_bindings(this->globals_
);
4409 for (Packages::iterator p
= this->packages_
.begin();
4410 p
!= this->packages_
.end();
4413 Package
* package
= p
->second
;
4414 this->convert_named_types_in_bindings(package
->bindings());
4417 Convert_named_types
cnt(this);
4418 this->traverse(&cnt
);
4420 // Make all the builtin named types used for type descriptors, and
4421 // then convert them. They will only be written out if they are
4423 Type::make_type_descriptor_type();
4424 Type::make_type_descriptor_ptr_type();
4425 Function_type::make_function_type_descriptor_type();
4426 Pointer_type::make_pointer_type_descriptor_type();
4427 Struct_type::make_struct_type_descriptor_type();
4428 Array_type::make_array_type_descriptor_type();
4429 Array_type::make_slice_type_descriptor_type();
4430 Map_type::make_map_type_descriptor_type();
4431 Map_type::make_map_descriptor_type();
4432 Channel_type::make_chan_type_descriptor_type();
4433 Interface_type::make_interface_type_descriptor_type();
4434 Expression::make_func_descriptor_type();
4435 Type::convert_builtin_named_types(this);
4437 Runtime::convert_types(this);
4439 this->named_types_are_converted_
= true;
4442 // Convert all names types in a set of bindings.
4445 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
4447 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
4448 p
!= bindings
->end_definitions();
4451 if ((*p
)->is_type())
4452 (*p
)->type_value()->convert(this);
4458 Function::Function(Function_type
* type
, Function
* enclosing
, Block
* block
,
4460 : type_(type
), enclosing_(enclosing
), results_(NULL
),
4461 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
4462 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
4463 is_sink_(false), results_are_named_(false), nointerface_(false),
4464 is_unnamed_type_stub_method_(false), calls_recover_(false),
4465 is_recover_thunk_(false), has_recover_thunk_(false),
4466 calls_defer_retaddr_(false), is_type_specific_function_(false),
4467 in_unique_section_(false)
4471 // Create the named result variables.
4474 Function::create_result_variables(Gogo
* gogo
)
4476 const Typed_identifier_list
* results
= this->type_
->results();
4477 if (results
== NULL
|| results
->empty())
4480 if (!results
->front().name().empty())
4481 this->results_are_named_
= true;
4483 this->results_
= new Results();
4484 this->results_
->reserve(results
->size());
4486 Block
* block
= this->block_
;
4488 for (Typed_identifier_list::const_iterator p
= results
->begin();
4489 p
!= results
->end();
4492 std::string name
= p
->name();
4493 if (name
.empty() || Gogo::is_sink_name(name
))
4495 static int result_counter
;
4497 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
4499 name
= gogo
->pack_hidden_name(buf
, false);
4501 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
4503 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
4504 if (no
->is_result_variable())
4505 this->results_
->push_back(no
);
4508 static int dummy_result_count
;
4510 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
4511 ++dummy_result_count
;
4512 name
= gogo
->pack_hidden_name(buf
, false);
4513 no
= block
->bindings()->add_result_variable(name
, result
);
4514 go_assert(no
->is_result_variable());
4515 this->results_
->push_back(no
);
4520 // Update the named result variables when cloning a function which
4524 Function::update_result_variables()
4526 if (this->results_
== NULL
)
4529 for (Results::iterator p
= this->results_
->begin();
4530 p
!= this->results_
->end();
4532 (*p
)->result_var_value()->set_function(this);
4535 // Return the closure variable, creating it if necessary.
4538 Function::closure_var()
4540 if (this->closure_var_
== NULL
)
4542 go_assert(this->descriptor_
== NULL
);
4543 // We don't know the type of the variable yet. We add fields as
4545 Location loc
= this->type_
->location();
4546 Struct_field_list
* sfl
= new Struct_field_list
;
4547 Type
* struct_type
= Type::make_struct_type(sfl
, loc
);
4548 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
4549 NULL
, false, false, false, loc
);
4551 var
->set_is_closure();
4552 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
4553 // Note that the new variable is not in any binding contour.
4555 return this->closure_var_
;
4558 // Set the type of the closure variable.
4561 Function::set_closure_type()
4563 if (this->closure_var_
== NULL
)
4565 Named_object
* closure
= this->closure_var_
;
4566 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
4568 // The first field of a closure is always a pointer to the function
4570 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4571 st
->push_field(Struct_field(Typed_identifier(".$f", voidptr_type
,
4574 unsigned int index
= 1;
4575 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
4576 p
!= this->closure_fields_
.end();
4579 Named_object
* no
= p
->first
;
4581 snprintf(buf
, sizeof buf
, "%u", index
);
4582 std::string n
= no
->name() + buf
;
4584 if (no
->is_variable())
4585 var_type
= no
->var_value()->type();
4587 var_type
= no
->result_var_value()->type();
4588 Type
* field_type
= Type::make_pointer_type(var_type
);
4589 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
4593 // Return whether this function is a method.
4596 Function::is_method() const
4598 return this->type_
->is_method();
4601 // Add a label definition.
4604 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
4607 Label
* lnull
= NULL
;
4608 std::pair
<Labels::iterator
, bool> ins
=
4609 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4613 // This is a new label.
4614 label
= new Label(label_name
);
4615 ins
.first
->second
= label
;
4619 // The label was already in the hash table.
4620 label
= ins
.first
->second
;
4621 if (label
->is_defined())
4623 error_at(location
, "label %qs already defined",
4624 Gogo::message_name(label_name
).c_str());
4625 inform(label
->location(), "previous definition of %qs was here",
4626 Gogo::message_name(label_name
).c_str());
4627 return new Label(label_name
);
4631 label
->define(location
, gogo
->bindings_snapshot(location
));
4633 // Issue any errors appropriate for any previous goto's to this
4635 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
4636 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
4639 (*p
)->check_goto_to(gogo
->current_block());
4640 label
->clear_refs();
4645 // Add a reference to a label.
4648 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
4649 Location location
, bool issue_goto_errors
)
4651 Label
* lnull
= NULL
;
4652 std::pair
<Labels::iterator
, bool> ins
=
4653 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4657 // The label was already in the hash table.
4658 label
= ins
.first
->second
;
4662 go_assert(ins
.first
->second
== NULL
);
4663 label
= new Label(label_name
);
4664 ins
.first
->second
= label
;
4667 label
->set_is_used();
4669 if (issue_goto_errors
)
4671 Bindings_snapshot
* snapshot
= label
->snapshot();
4672 if (snapshot
!= NULL
)
4673 snapshot
->check_goto_from(gogo
->current_block(), location
);
4675 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
4681 // Warn about labels that are defined but not used.
4684 Function::check_labels() const
4686 for (Labels::const_iterator p
= this->labels_
.begin();
4687 p
!= this->labels_
.end();
4690 Label
* label
= p
->second
;
4691 if (!label
->is_used())
4692 error_at(label
->location(), "label %qs defined and not used",
4693 Gogo::message_name(label
->name()).c_str());
4697 // Swap one function with another. This is used when building the
4698 // thunk we use to call a function which calls recover. It may not
4699 // work for any other case.
4702 Function::swap_for_recover(Function
*x
)
4704 go_assert(this->enclosing_
== x
->enclosing_
);
4705 std::swap(this->results_
, x
->results_
);
4706 std::swap(this->closure_var_
, x
->closure_var_
);
4707 std::swap(this->block_
, x
->block_
);
4708 go_assert(this->location_
== x
->location_
);
4709 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
4710 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
4713 // Traverse the tree.
4716 Function::traverse(Traverse
* traverse
)
4718 unsigned int traverse_mask
= traverse
->traverse_mask();
4721 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
4724 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
4725 return TRAVERSE_EXIT
;
4728 // FIXME: We should check traverse_functions here if nested
4729 // functions are stored in block bindings.
4730 if (this->block_
!= NULL
4732 & (Traverse::traverse_variables
4733 | Traverse::traverse_constants
4734 | Traverse::traverse_blocks
4735 | Traverse::traverse_statements
4736 | Traverse::traverse_expressions
4737 | Traverse::traverse_types
)) != 0)
4739 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
4740 return TRAVERSE_EXIT
;
4743 return TRAVERSE_CONTINUE
;
4746 // Work out types for unspecified variables and constants.
4749 Function::determine_types()
4751 if (this->block_
!= NULL
)
4752 this->block_
->determine_types();
4755 // Return the function descriptor, the value you get when you refer to
4756 // the function in Go code without calling it.
4759 Function::descriptor(Gogo
*, Named_object
* no
)
4761 go_assert(!this->is_method());
4762 go_assert(this->closure_var_
== NULL
);
4763 if (this->descriptor_
== NULL
)
4764 this->descriptor_
= Expression::make_func_descriptor(no
);
4765 return this->descriptor_
;
4768 // Get a pointer to the variable representing the defer stack for this
4769 // function, making it if necessary. The value of the variable is set
4770 // by the runtime routines to true if the function is returning,
4771 // rather than panicing through. A pointer to this variable is used
4772 // as a marker for the functions on the defer stack associated with
4773 // this function. A function-specific variable permits inlining a
4774 // function which uses defer.
4777 Function::defer_stack(Location location
)
4779 if (this->defer_stack_
== NULL
)
4781 Type
* t
= Type::lookup_bool_type();
4782 Expression
* n
= Expression::make_boolean(false, location
);
4783 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
4784 this->defer_stack_
->set_is_address_taken();
4786 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
4788 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
4791 // Export the function.
4794 Function::export_func(Export
* exp
, const std::string
& name
) const
4796 Function::export_func_with_type(exp
, name
, this->type_
);
4799 // Export a function with a type.
4802 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
4803 const Function_type
* fntype
)
4805 exp
->write_c_string("func ");
4807 if (fntype
->is_method())
4809 exp
->write_c_string("(");
4810 const Typed_identifier
* receiver
= fntype
->receiver();
4811 exp
->write_name(receiver
->name());
4812 exp
->write_c_string(" ");
4813 exp
->write_type(receiver
->type());
4814 exp
->write_c_string(") ");
4817 exp
->write_string(name
);
4819 exp
->write_c_string(" (");
4820 const Typed_identifier_list
* parameters
= fntype
->parameters();
4821 if (parameters
!= NULL
)
4823 bool is_varargs
= fntype
->is_varargs();
4825 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
4826 p
!= parameters
->end();
4832 exp
->write_c_string(", ");
4833 exp
->write_name(p
->name());
4834 exp
->write_c_string(" ");
4835 if (!is_varargs
|| p
+ 1 != parameters
->end())
4836 exp
->write_type(p
->type());
4839 exp
->write_c_string("...");
4840 exp
->write_type(p
->type()->array_type()->element_type());
4844 exp
->write_c_string(")");
4846 const Typed_identifier_list
* results
= fntype
->results();
4847 if (results
!= NULL
)
4849 if (results
->size() == 1 && results
->begin()->name().empty())
4851 exp
->write_c_string(" ");
4852 exp
->write_type(results
->begin()->type());
4856 exp
->write_c_string(" (");
4858 for (Typed_identifier_list::const_iterator p
= results
->begin();
4859 p
!= results
->end();
4865 exp
->write_c_string(", ");
4866 exp
->write_name(p
->name());
4867 exp
->write_c_string(" ");
4868 exp
->write_type(p
->type());
4870 exp
->write_c_string(")");
4873 exp
->write_c_string(";\n");
4876 // Import a function.
4879 Function::import_func(Import
* imp
, std::string
* pname
,
4880 Typed_identifier
** preceiver
,
4881 Typed_identifier_list
** pparameters
,
4882 Typed_identifier_list
** presults
,
4885 imp
->require_c_string("func ");
4888 if (imp
->peek_char() == '(')
4890 imp
->require_c_string("(");
4891 std::string name
= imp
->read_name();
4892 imp
->require_c_string(" ");
4893 Type
* rtype
= imp
->read_type();
4894 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
4895 imp
->require_c_string(") ");
4898 *pname
= imp
->read_identifier();
4900 Typed_identifier_list
* parameters
;
4901 *is_varargs
= false;
4902 imp
->require_c_string(" (");
4903 if (imp
->peek_char() == ')')
4907 parameters
= new Typed_identifier_list();
4910 std::string name
= imp
->read_name();
4911 imp
->require_c_string(" ");
4913 if (imp
->match_c_string("..."))
4919 Type
* ptype
= imp
->read_type();
4921 ptype
= Type::make_array_type(ptype
, NULL
);
4922 parameters
->push_back(Typed_identifier(name
, ptype
,
4924 if (imp
->peek_char() != ',')
4926 go_assert(!*is_varargs
);
4927 imp
->require_c_string(", ");
4930 imp
->require_c_string(")");
4931 *pparameters
= parameters
;
4933 Typed_identifier_list
* results
;
4934 if (imp
->peek_char() != ' ')
4938 results
= new Typed_identifier_list();
4939 imp
->require_c_string(" ");
4940 if (imp
->peek_char() != '(')
4942 Type
* rtype
= imp
->read_type();
4943 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
4947 imp
->require_c_string("(");
4950 std::string name
= imp
->read_name();
4951 imp
->require_c_string(" ");
4952 Type
* rtype
= imp
->read_type();
4953 results
->push_back(Typed_identifier(name
, rtype
,
4955 if (imp
->peek_char() != ',')
4957 imp
->require_c_string(", ");
4959 imp
->require_c_string(")");
4962 imp
->require_c_string(";\n");
4963 *presults
= results
;
4966 // Get the backend representation.
4969 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
4971 if (this->fndecl_
== NULL
)
4973 std::string asm_name
;
4974 bool is_visible
= false;
4975 if (no
->package() != NULL
)
4977 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
4979 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
4980 && !this->type_
->is_method())
4982 else if (no
->name() == gogo
->get_init_fn_name())
4985 asm_name
= no
->name();
4987 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
4988 && gogo
->is_main_package())
4990 // Methods have to be public even if they are hidden because
4991 // they can be pulled into type descriptors when using
4992 // anonymous fields.
4993 else if (!Gogo::is_hidden_name(no
->name())
4994 || this->type_
->is_method())
4996 if (!this->is_unnamed_type_stub_method_
)
4998 std::string pkgpath
= gogo
->pkgpath_symbol();
4999 if (this->type_
->is_method()
5000 && Gogo::is_hidden_name(no
->name())
5001 && Gogo::hidden_name_pkgpath(no
->name()) != gogo
->pkgpath())
5003 // This is a method we created for an unexported
5004 // method of an imported embedded type. We need to
5005 // use the pkgpath of the imported package to avoid
5006 // a possible name collision. See bug478 for a test
5008 pkgpath
= Gogo::hidden_name_pkgpath(no
->name());
5009 pkgpath
= Gogo::pkgpath_for_symbol(pkgpath
);
5013 asm_name
.append(1, '.');
5014 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5015 if (this->type_
->is_method())
5017 asm_name
.append(1, '.');
5018 Type
* rtype
= this->type_
->receiver()->type();
5019 asm_name
.append(rtype
->mangled_name(gogo
));
5023 // If a function calls the predeclared recover function, we
5024 // can't inline it, because recover behaves differently in a
5025 // function passed directly to defer. If this is a recover
5026 // thunk that we built to test whether a function can be
5027 // recovered, we can't inline it, because that will mess up
5028 // our return address comparison.
5029 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5031 // If a function calls __go_set_defer_retaddr, then mark it as
5032 // uninlinable. This prevents the GCC backend from splitting
5033 // the function; splitting the function is a bad idea because we
5034 // want the return address label to be in the same function as
5036 if (this->calls_defer_retaddr_
)
5037 is_inlinable
= false;
5039 // If this is a thunk created to call a function which calls
5040 // the predeclared recover function, we need to disable
5041 // stack splitting for the thunk.
5042 bool disable_split_stack
= this->is_recover_thunk_
;
5044 // This should go into a unique section if that has been
5045 // requested elsewhere, or if this is a nointerface function.
5046 // We want to put a nointerface function into a unique section
5047 // because there is a good chance that the linker garbage
5048 // collection can discard it.
5049 bool in_unique_section
= this->in_unique_section_
|| this->nointerface_
;
5051 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5053 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5054 is_visible
, false, is_inlinable
,
5055 disable_split_stack
, in_unique_section
,
5058 return this->fndecl_
;
5061 // Get the backend representation.
5064 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5066 if (this->fndecl_
== NULL
)
5068 // Let Go code use an asm declaration to pick up a builtin
5070 if (!this->asm_name_
.empty())
5072 Bfunction
* builtin_decl
=
5073 gogo
->backend()->lookup_builtin(this->asm_name_
);
5074 if (builtin_decl
!= NULL
)
5076 this->fndecl_
= builtin_decl
;
5077 return this->fndecl_
;
5081 std::string asm_name
;
5082 if (this->asm_name_
.empty())
5084 asm_name
= (no
->package() == NULL
5085 ? gogo
->pkgpath_symbol()
5086 : no
->package()->pkgpath_symbol());
5087 asm_name
.append(1, '.');
5088 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5089 if (this->fntype_
->is_method())
5091 asm_name
.append(1, '.');
5092 Type
* rtype
= this->fntype_
->receiver()->type();
5093 asm_name
.append(rtype
->mangled_name(gogo
));
5097 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5099 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5100 true, true, true, false, false,
5104 return this->fndecl_
;
5107 // Build the descriptor for a function declaration. This won't
5108 // necessarily happen if the package has just a declaration for the
5109 // function and no other reference to it, but we may still need the
5110 // descriptor for references from other packages.
5112 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5114 if (this->descriptor_
!= NULL
)
5116 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5117 this->descriptor_
->get_backend(&context
);
5121 // Return the function's decl after it has been built.
5124 Function::get_decl() const
5126 go_assert(this->fndecl_
!= NULL
);
5127 return this->fndecl_
;
5130 // Build the backend representation for the function code.
5133 Function::build(Gogo
* gogo
, Named_object
* named_function
)
5135 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5137 // A list of parameter variables for this function.
5138 std::vector
<Bvariable
*> param_vars
;
5140 // Variables that need to be declared for this function and their
5142 std::vector
<Bvariable
*> vars
;
5143 std::vector
<Bexpression
*> var_inits
;
5144 for (Bindings::const_definitions_iterator p
=
5145 this->block_
->bindings()->begin_definitions();
5146 p
!= this->block_
->bindings()->end_definitions();
5149 Location loc
= (*p
)->location();
5150 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
5152 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5153 Bvariable
* parm_bvar
= bvar
;
5155 // We always pass the receiver to a method as a pointer. If
5156 // the receiver is declared as a non-pointer type, then we
5157 // copy the value into a local variable.
5158 if ((*p
)->var_value()->is_receiver()
5159 && (*p
)->var_value()->type()->points_to() == NULL
)
5161 std::string name
= (*p
)->name() + ".pointer";
5162 Type
* var_type
= (*p
)->var_value()->type();
5163 Variable
* parm_var
=
5164 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
5166 Named_object
* parm_no
=
5167 Named_object::make_variable(name
, NULL
, parm_var
);
5168 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5170 vars
.push_back(bvar
);
5171 Expression
* parm_ref
=
5172 Expression::make_var_reference(parm_no
, loc
);
5173 parm_ref
= Expression::make_unary(OPERATOR_MULT
, parm_ref
, loc
);
5174 if ((*p
)->var_value()->is_in_heap())
5175 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
5176 var_inits
.push_back(parm_ref
->get_backend(&context
));
5178 else if ((*p
)->var_value()->is_in_heap())
5180 // If we take the address of a parameter, then we need
5181 // to copy it into the heap.
5182 std::string parm_name
= (*p
)->name() + ".param";
5183 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
5184 false, true, false, loc
);
5185 Named_object
* parm_no
=
5186 Named_object::make_variable(parm_name
, NULL
, parm_var
);
5187 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5189 vars
.push_back(bvar
);
5190 Expression
* var_ref
=
5191 Expression::make_var_reference(parm_no
, loc
);
5192 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
5193 var_inits
.push_back(var_ref
->get_backend(&context
));
5195 param_vars
.push_back(parm_bvar
);
5197 else if ((*p
)->is_result_variable())
5199 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5201 Type
* type
= (*p
)->result_var_value()->type();
5203 if (!(*p
)->result_var_value()->is_in_heap())
5205 Btype
* btype
= type
->get_backend(gogo
);
5206 init
= gogo
->backend()->zero_expression(btype
);
5209 init
= Expression::make_allocation(type
,
5210 loc
)->get_backend(&context
);
5212 vars
.push_back(bvar
);
5213 var_inits
.push_back(init
);
5216 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
5218 go_assert(saw_errors());
5222 // If we need a closure variable, make sure to create it.
5223 // It gets installed in the function as a side effect of creation.
5224 if (this->closure_var_
!= NULL
)
5226 go_assert(this->closure_var_
->var_value()->is_closure());
5227 this->closure_var_
->get_backend_variable(gogo
, named_function
);
5230 if (this->block_
!= NULL
)
5232 // Declare variables if necessary.
5233 Bblock
* var_decls
= NULL
;
5235 Bstatement
* defer_init
= NULL
;
5236 if (!vars
.empty() || this->defer_stack_
!= NULL
)
5239 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
5240 this->block_
->start_location(),
5241 this->block_
->end_location());
5243 if (this->defer_stack_
!= NULL
)
5245 Translate_context
dcontext(gogo
, named_function
, this->block_
,
5247 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
5251 // Build the backend representation for all the statements in the
5253 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5254 Bblock
* code_block
= this->block_
->get_backend(&context
);
5256 // Initialize variables if necessary.
5257 std::vector
<Bstatement
*> init
;
5258 go_assert(vars
.size() == var_inits
.size());
5259 for (size_t i
= 0; i
< vars
.size(); ++i
)
5261 Bstatement
* init_stmt
=
5262 gogo
->backend()->init_statement(vars
[i
], var_inits
[i
]);
5263 init
.push_back(init_stmt
);
5265 if (defer_init
!= NULL
)
5266 init
.push_back(defer_init
);
5267 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
5269 // Initialize all variables before executing this code block.
5270 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
5271 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
5273 // If we have a defer stack, initialize it at the start of a
5275 Bstatement
* except
= NULL
;
5276 Bstatement
* fini
= NULL
;
5277 if (defer_init
!= NULL
)
5279 // Clean up the defer stack when we leave the function.
5280 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
5282 // Wrap the code for this function in an exception handler to handle
5285 gogo
->backend()->exception_handler_statement(code_stmt
,
5290 // Stick the code into the block we built for the receiver, if
5292 if (var_decls
!= NULL
)
5294 std::vector
<Bstatement
*> code_stmt_list(1, code_stmt
);
5295 gogo
->backend()->block_add_statements(var_decls
, code_stmt_list
);
5296 code_stmt
= gogo
->backend()->block_statement(var_decls
);
5299 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
5301 go_assert(saw_errors());
5306 // If we created a descriptor for the function, make sure we emit it.
5307 if (this->descriptor_
!= NULL
)
5309 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5310 this->descriptor_
->get_backend(&context
);
5314 // Build the wrappers around function code needed if the function has
5315 // any defer statements. This sets *EXCEPT to an exception handler
5316 // and *FINI to a finally handler.
5319 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
5320 Bstatement
** except
, Bstatement
** fini
)
5322 Location end_loc
= this->block_
->end_location();
5324 // Add an exception handler. This is used if a panic occurs. Its
5325 // purpose is to stop the stack unwinding if a deferred function
5326 // calls recover. There are more details in
5327 // libgo/runtime/go-unwind.c.
5329 std::vector
<Bstatement
*> stmts
;
5330 Expression
* call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5331 this->defer_stack(end_loc
));
5332 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5333 Bexpression
* defer
= call
->get_backend(&context
);
5334 stmts
.push_back(gogo
->backend()->expression_statement(defer
));
5336 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5337 if (ret_bstmt
!= NULL
)
5338 stmts
.push_back(ret_bstmt
);
5340 go_assert(*except
== NULL
);
5341 *except
= gogo
->backend()->statement_list(stmts
);
5343 call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5344 this->defer_stack(end_loc
));
5345 defer
= call
->get_backend(&context
);
5347 call
= Runtime::make_call(Runtime::UNDEFER
, end_loc
, 1,
5348 this->defer_stack(end_loc
));
5349 Bexpression
* undefer
= call
->get_backend(&context
);
5350 Bstatement
* function_defer
=
5351 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
5353 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
5354 if (this->type_
->results() != NULL
5355 && !this->type_
->results()->empty()
5356 && !this->type_
->results()->front().name().empty())
5358 // If the result variables are named, and we are returning from
5359 // this function rather than panicing through it, we need to
5360 // return them again, because they might have been changed by a
5361 // defer function. The runtime routines set the defer_stack
5362 // variable to true if we are returning from this function.
5364 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5365 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
5367 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
5369 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
5370 Bexpression
* bref
= ref
->get_backend(&context
);
5371 ret
= gogo
->backend()->conditional_expression(NULL
, bref
, ret
, NULL
,
5373 stmts
.push_back(gogo
->backend()->expression_statement(ret
));
5376 go_assert(*fini
== NULL
);
5377 *fini
= gogo
->backend()->statement_list(stmts
);
5380 // Return the statement that assigns values to this function's result struct.
5383 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
5384 Location location
) const
5386 const Typed_identifier_list
* results
= this->type_
->results();
5387 if (results
== NULL
|| results
->empty())
5390 go_assert(this->results_
!= NULL
);
5391 if (this->results_
->size() != results
->size())
5393 go_assert(saw_errors());
5394 return gogo
->backend()->error_statement();
5397 std::vector
<Bexpression
*> vals(results
->size());
5398 for (size_t i
= 0; i
< vals
.size(); ++i
)
5400 Named_object
* no
= (*this->results_
)[i
];
5401 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
5402 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
5403 if (no
->result_var_value()->is_in_heap())
5405 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
5406 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
5410 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
5415 Block::Block(Block
* enclosing
, Location location
)
5416 : enclosing_(enclosing
), statements_(),
5417 bindings_(new Bindings(enclosing
== NULL
5419 : enclosing
->bindings())),
5420 start_location_(location
),
5421 end_location_(UNKNOWN_LOCATION
)
5425 // Add a statement to a block.
5428 Block::add_statement(Statement
* statement
)
5430 this->statements_
.push_back(statement
);
5433 // Add a statement to the front of a block. This is slow but is only
5434 // used for reference counts of parameters.
5437 Block::add_statement_at_front(Statement
* statement
)
5439 this->statements_
.insert(this->statements_
.begin(), statement
);
5442 // Replace a statement in a block.
5445 Block::replace_statement(size_t index
, Statement
* s
)
5447 go_assert(index
< this->statements_
.size());
5448 this->statements_
[index
] = s
;
5451 // Add a statement before another statement.
5454 Block::insert_statement_before(size_t index
, Statement
* s
)
5456 go_assert(index
< this->statements_
.size());
5457 this->statements_
.insert(this->statements_
.begin() + index
, s
);
5460 // Add a statement after another statement.
5463 Block::insert_statement_after(size_t index
, Statement
* s
)
5465 go_assert(index
< this->statements_
.size());
5466 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
5469 // Traverse the tree.
5472 Block::traverse(Traverse
* traverse
)
5474 unsigned int traverse_mask
= traverse
->traverse_mask();
5476 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
5478 int t
= traverse
->block(this);
5479 if (t
== TRAVERSE_EXIT
)
5480 return TRAVERSE_EXIT
;
5481 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
5482 return TRAVERSE_CONTINUE
;
5486 & (Traverse::traverse_variables
5487 | Traverse::traverse_constants
5488 | Traverse::traverse_expressions
5489 | Traverse::traverse_types
)) != 0)
5491 const unsigned int e_or_t
= (Traverse::traverse_expressions
5492 | Traverse::traverse_types
);
5493 const unsigned int e_or_t_or_s
= (e_or_t
5494 | Traverse::traverse_statements
);
5495 for (Bindings::const_definitions_iterator pb
=
5496 this->bindings_
->begin_definitions();
5497 pb
!= this->bindings_
->end_definitions();
5500 int t
= TRAVERSE_CONTINUE
;
5501 switch ((*pb
)->classification())
5503 case Named_object::NAMED_OBJECT_CONST
:
5504 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
5505 t
= traverse
->constant(*pb
, false);
5506 if (t
== TRAVERSE_CONTINUE
5507 && (traverse_mask
& e_or_t
) != 0)
5509 Type
* tc
= (*pb
)->const_value()->type();
5511 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
5512 return TRAVERSE_EXIT
;
5513 t
= (*pb
)->const_value()->traverse_expression(traverse
);
5517 case Named_object::NAMED_OBJECT_VAR
:
5518 case Named_object::NAMED_OBJECT_RESULT_VAR
:
5519 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
5520 t
= traverse
->variable(*pb
);
5521 if (t
== TRAVERSE_CONTINUE
5522 && (traverse_mask
& e_or_t
) != 0)
5524 if ((*pb
)->is_result_variable()
5525 || (*pb
)->var_value()->has_type())
5527 Type
* tv
= ((*pb
)->is_variable()
5528 ? (*pb
)->var_value()->type()
5529 : (*pb
)->result_var_value()->type());
5531 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
5532 return TRAVERSE_EXIT
;
5535 if (t
== TRAVERSE_CONTINUE
5536 && (traverse_mask
& e_or_t_or_s
) != 0
5537 && (*pb
)->is_variable())
5538 t
= (*pb
)->var_value()->traverse_expression(traverse
,
5542 case Named_object::NAMED_OBJECT_FUNC
:
5543 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
5546 case Named_object::NAMED_OBJECT_TYPE
:
5547 if ((traverse_mask
& e_or_t
) != 0)
5548 t
= Type::traverse((*pb
)->type_value(), traverse
);
5551 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
5552 case Named_object::NAMED_OBJECT_UNKNOWN
:
5553 case Named_object::NAMED_OBJECT_ERRONEOUS
:
5556 case Named_object::NAMED_OBJECT_PACKAGE
:
5557 case Named_object::NAMED_OBJECT_SINK
:
5564 if (t
== TRAVERSE_EXIT
)
5565 return TRAVERSE_EXIT
;
5569 // No point in checking traverse_mask here--if we got here we always
5570 // want to walk the statements. The traversal can insert new
5571 // statements before or after the current statement. Inserting
5572 // statements before the current statement requires updating I via
5573 // the pointer; those statements will not be traversed. Any new
5574 // statements inserted after the current statement will be traversed
5576 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
5578 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
5579 return TRAVERSE_EXIT
;
5582 return TRAVERSE_CONTINUE
;
5585 // Work out types for unspecified variables and constants.
5588 Block::determine_types()
5590 for (Bindings::const_definitions_iterator pb
=
5591 this->bindings_
->begin_definitions();
5592 pb
!= this->bindings_
->end_definitions();
5595 if ((*pb
)->is_variable())
5596 (*pb
)->var_value()->determine_type();
5597 else if ((*pb
)->is_const())
5598 (*pb
)->const_value()->determine_type();
5601 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
5602 ps
!= this->statements_
.end();
5604 (*ps
)->determine_types();
5607 // Return true if the statements in this block may fall through.
5610 Block::may_fall_through() const
5612 if (this->statements_
.empty())
5614 return this->statements_
.back()->may_fall_through();
5617 // Convert a block to the backend representation.
5620 Block::get_backend(Translate_context
* context
)
5622 Gogo
* gogo
= context
->gogo();
5623 Named_object
* function
= context
->function();
5624 std::vector
<Bvariable
*> vars
;
5625 vars
.reserve(this->bindings_
->size_definitions());
5626 for (Bindings::const_definitions_iterator pv
=
5627 this->bindings_
->begin_definitions();
5628 pv
!= this->bindings_
->end_definitions();
5631 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
5632 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
5635 go_assert(function
!= NULL
);
5636 Bfunction
* bfunction
=
5637 function
->func_value()->get_or_make_decl(gogo
, function
);
5638 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
5639 vars
, this->start_location_
,
5640 this->end_location_
);
5642 Translate_context
subcontext(gogo
, function
, this, ret
);
5643 std::vector
<Bstatement
*> bstatements
;
5644 bstatements
.reserve(this->statements_
.size());
5645 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
5646 p
!= this->statements_
.end();
5648 bstatements
.push_back((*p
)->get_backend(&subcontext
));
5650 context
->backend()->block_add_statements(ret
, bstatements
);
5655 // Class Bindings_snapshot.
5657 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
5658 : block_(b
), counts_(), location_(location
)
5662 this->counts_
.push_back(b
->bindings()->size_definitions());
5667 // Report errors appropriate for a goto from B to this.
5670 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
5673 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
5675 this->check_goto_defs(loc
, this->block_
,
5676 this->block_
->bindings()->size_definitions(),
5680 // Report errors appropriate for a goto from this to B.
5683 Bindings_snapshot::check_goto_to(const Block
* b
)
5686 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
5688 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
5689 b
->bindings()->size_definitions());
5692 // Report errors appropriate for a goto at LOC from BFROM to BTO.
5693 // Return true if all is well, false if we reported an error. If this
5694 // returns true, it sets *PINDEX to the number of blocks BTO is above
5698 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
5699 const Block
* bto
, size_t* pindex
)
5701 // It is an error if BTO is not either BFROM or above BFROM.
5703 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
5707 error_at(loc
, "goto jumps into block");
5708 inform(bto
->start_location(), "goto target block starts here");
5716 // Report errors appropriate for a goto at LOC ending at BLOCK, where
5717 // CFROM is the number of names defined at the point of the goto and
5718 // CTO is the number of names defined at the point of the label.
5721 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
5722 size_t cfrom
, size_t cto
)
5726 Bindings::const_definitions_iterator p
=
5727 block
->bindings()->begin_definitions();
5728 for (size_t i
= 0; i
< cfrom
; ++i
)
5730 go_assert(p
!= block
->bindings()->end_definitions());
5733 go_assert(p
!= block
->bindings()->end_definitions());
5735 std::string n
= (*p
)->message_name();
5736 error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
5737 inform((*p
)->location(), "%qs defined here", n
.c_str());
5741 // Class Function_declaration.
5743 // Return the function descriptor.
5746 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
5748 go_assert(!this->fntype_
->is_method());
5749 if (this->descriptor_
== NULL
)
5750 this->descriptor_
= Expression::make_func_descriptor(no
);
5751 return this->descriptor_
;
5756 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
5757 bool is_parameter
, bool is_receiver
,
5759 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
5760 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
5761 is_closure_(false), is_receiver_(is_receiver
),
5762 is_varargs_parameter_(false), is_used_(false),
5763 is_address_taken_(false), is_non_escaping_address_taken_(false),
5764 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
5765 type_from_init_tuple_(false), type_from_range_index_(false),
5766 type_from_range_value_(false), type_from_chan_element_(false),
5767 is_type_switch_var_(false), determined_type_(false),
5768 in_unique_section_(false)
5770 go_assert(type
!= NULL
|| init
!= NULL
);
5771 go_assert(!is_parameter
|| init
== NULL
);
5774 // Traverse the initializer expression.
5777 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
5779 if (this->preinit_
!= NULL
)
5781 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
5782 return TRAVERSE_EXIT
;
5784 if (this->init_
!= NULL
5786 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
5789 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
5790 return TRAVERSE_EXIT
;
5792 return TRAVERSE_CONTINUE
;
5795 // Lower the initialization expression after parsing is complete.
5798 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
5799 Statement_inserter
* inserter
)
5801 Named_object
* dep
= gogo
->var_depends_on(this);
5802 if (dep
!= NULL
&& dep
->is_variable())
5803 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
5805 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
5809 // We will give an error elsewhere, this is just to prevent
5810 // an infinite loop.
5815 Statement_inserter global_inserter
;
5816 if (this->is_global_
)
5818 global_inserter
= Statement_inserter(gogo
, this);
5819 inserter
= &global_inserter
;
5822 gogo
->lower_expression(function
, inserter
, &this->init_
);
5824 this->seen_
= false;
5826 this->init_is_lowered_
= true;
5830 // Flatten the initialization expression after ordering evaluations.
5833 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
5834 Statement_inserter
* inserter
)
5836 Named_object
* dep
= gogo
->var_depends_on(this);
5837 if (dep
!= NULL
&& dep
->is_variable())
5838 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
5840 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
5844 // We will give an error elsewhere, this is just to prevent
5845 // an infinite loop.
5850 Statement_inserter global_inserter
;
5851 if (this->is_global_
)
5853 global_inserter
= Statement_inserter(gogo
, this);
5854 inserter
= &global_inserter
;
5857 gogo
->flatten_expression(function
, inserter
, &this->init_
);
5859 // If an interface conversion is needed, we need a temporary
5861 if (this->type_
!= NULL
5862 && !Type::are_identical(this->type_
, this->init_
->type(), false,
5864 && this->init_
->type()->interface_type() != NULL
5865 && !this->init_
->is_variable())
5867 Temporary_statement
* temp
=
5868 Statement::make_temporary(NULL
, this->init_
, this->location_
);
5869 inserter
->insert(temp
);
5870 this->init_
= Expression::make_temporary_reference(temp
,
5874 this->seen_
= false;
5875 this->init_is_flattened_
= true;
5879 // Get the preinit block.
5882 Variable::preinit_block(Gogo
* gogo
)
5884 go_assert(this->is_global_
);
5885 if (this->preinit_
== NULL
)
5886 this->preinit_
= new Block(NULL
, this->location());
5888 // If a global variable has a preinitialization statement, then we
5889 // need to have an initialization function.
5890 gogo
->set_need_init_fn();
5892 return this->preinit_
;
5895 // Add a statement to be run before the initialization expression.
5898 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
5900 Block
* b
= this->preinit_block(gogo
);
5901 b
->add_statement(s
);
5902 b
->set_end_location(s
->location());
5905 // Whether this variable has a type.
5908 Variable::has_type() const
5910 if (this->type_
== NULL
)
5913 // A variable created in a type switch case nil does not actually
5914 // have a type yet. It will be changed to use the initializer's
5915 // type in determine_type.
5916 if (this->is_type_switch_var_
5917 && this->type_
->is_nil_constant_as_type())
5923 // In an assignment which sets a variable to a tuple of EXPR, return
5924 // the type of the first element of the tuple.
5927 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
5929 if (expr
->map_index_expression() != NULL
)
5931 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
5933 return Type::make_error_type();
5934 return mt
->val_type();
5936 else if (expr
->receive_expression() != NULL
)
5938 Expression
* channel
= expr
->receive_expression()->channel();
5939 Type
* channel_type
= channel
->type();
5940 if (channel_type
->channel_type() == NULL
)
5941 return Type::make_error_type();
5942 return channel_type
->channel_type()->element_type();
5947 error_at(this->location(), "invalid tuple definition");
5948 return Type::make_error_type();
5952 // Given EXPR used in a range clause, return either the index type or
5953 // the value type of the range, depending upon GET_INDEX_TYPE.
5956 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
5957 bool report_error
) const
5959 Type
* t
= expr
->type();
5960 if (t
->array_type() != NULL
5961 || (t
->points_to() != NULL
5962 && t
->points_to()->array_type() != NULL
5963 && !t
->points_to()->is_slice_type()))
5966 return Type::lookup_integer_type("int");
5968 return t
->deref()->array_type()->element_type();
5970 else if (t
->is_string_type())
5973 return Type::lookup_integer_type("int");
5975 return Type::lookup_integer_type("int32");
5977 else if (t
->map_type() != NULL
)
5980 return t
->map_type()->key_type();
5982 return t
->map_type()->val_type();
5984 else if (t
->channel_type() != NULL
)
5987 return t
->channel_type()->element_type();
5991 error_at(this->location(),
5992 "invalid definition of value variable for channel range");
5993 return Type::make_error_type();
5999 error_at(this->location(), "invalid type for range clause");
6000 return Type::make_error_type();
6004 // EXPR should be a channel. Return the channel's element type.
6007 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
6009 Type
* t
= expr
->type();
6010 if (t
->channel_type() != NULL
)
6011 return t
->channel_type()->element_type();
6015 error_at(this->location(), "expected channel");
6016 return Type::make_error_type();
6020 // Return the type of the Variable. This may be called before
6021 // Variable::determine_type is called, which means that we may need to
6022 // get the type from the initializer. FIXME: If we combine lowering
6023 // with type determination, then this should be unnecessary.
6028 // A variable in a type switch with a nil case will have the wrong
6029 // type here. This gets fixed up in determine_type, below.
6030 Type
* type
= this->type_
;
6031 Expression
* init
= this->init_
;
6032 if (this->is_type_switch_var_
6033 && this->type_
->is_nil_constant_as_type())
6035 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6036 go_assert(tge
!= NULL
);
6043 if (this->type_
== NULL
|| !this->type_
->is_error_type())
6045 error_at(this->location_
, "variable initializer refers to itself");
6046 this->type_
= Type::make_error_type();
6055 else if (this->type_from_init_tuple_
)
6056 type
= this->type_from_tuple(init
, false);
6057 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6058 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
6059 else if (this->type_from_chan_element_
)
6060 type
= this->type_from_chan_element(init
, false);
6063 go_assert(init
!= NULL
);
6064 type
= init
->type();
6065 go_assert(type
!= NULL
);
6067 // Variables should not have abstract types.
6068 if (type
->is_abstract())
6069 type
= type
->make_non_abstract_type();
6071 if (type
->is_void_type())
6072 type
= Type::make_error_type();
6075 this->seen_
= false;
6080 // Fetch the type from a const pointer, in which case it should have
6081 // been set already.
6084 Variable::type() const
6086 go_assert(this->type_
!= NULL
);
6090 // Set the type if necessary.
6093 Variable::determine_type()
6095 if (this->determined_type_
)
6097 this->determined_type_
= true;
6099 if (this->preinit_
!= NULL
)
6100 this->preinit_
->determine_types();
6102 // A variable in a type switch with a nil case will have the wrong
6103 // type here. It will have an initializer which is a type guard.
6104 // We want to initialize it to the value without the type guard, and
6105 // use the type of that value as well.
6106 if (this->is_type_switch_var_
&& this->type_
->is_nil_constant_as_type())
6108 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6109 go_assert(tge
!= NULL
);
6111 this->init_
= tge
->expr();
6114 if (this->init_
== NULL
)
6115 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
6116 else if (this->type_from_init_tuple_
)
6118 Expression
*init
= this->init_
;
6119 init
->determine_type_no_context();
6120 this->type_
= this->type_from_tuple(init
, true);
6123 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6125 Expression
* init
= this->init_
;
6126 init
->determine_type_no_context();
6127 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
6131 else if (this->type_from_chan_element_
)
6133 Expression
* init
= this->init_
;
6134 init
->determine_type_no_context();
6135 this->type_
= this->type_from_chan_element(init
, true);
6140 Type_context
context(this->type_
, false);
6141 this->init_
->determine_type(&context
);
6142 if (this->type_
== NULL
)
6144 Type
* type
= this->init_
->type();
6145 go_assert(type
!= NULL
);
6146 if (type
->is_abstract())
6147 type
= type
->make_non_abstract_type();
6149 if (type
->is_void_type())
6151 error_at(this->location_
, "variable has no type");
6152 type
= Type::make_error_type();
6154 else if (type
->is_nil_type())
6156 error_at(this->location_
, "variable defined to nil type");
6157 type
= Type::make_error_type();
6159 else if (type
->is_call_multiple_result_type())
6161 error_at(this->location_
,
6162 "single variable set to multiple-value function call");
6163 type
= Type::make_error_type();
6171 // Get the initial value of a variable. This does not
6172 // consider whether the variable is in the heap--it returns the
6173 // initial value as though it were always stored in the stack.
6176 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
6178 go_assert(this->preinit_
== NULL
);
6179 Location loc
= this->location();
6180 if (this->init_
== NULL
)
6182 go_assert(!this->is_parameter_
);
6183 if (this->is_global_
|| this->is_in_heap())
6185 Btype
* btype
= this->type()->get_backend(gogo
);
6186 return gogo
->backend()->zero_expression(btype
);
6190 Translate_context
context(gogo
, function
, NULL
, NULL
);
6191 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
6192 return init
->get_backend(&context
);
6196 // Get the initial value of a variable when a block is required.
6197 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6200 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
6201 Bvariable
* var_decl
)
6203 go_assert(this->preinit_
!= NULL
);
6205 // We want to add the variable assignment to the end of the preinit
6208 Translate_context
context(gogo
, function
, NULL
, NULL
);
6209 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
6211 // It's possible to have pre-init statements without an initializer
6212 // if the pre-init statements set the variable.
6213 Bstatement
* decl_init
= NULL
;
6214 if (this->init_
!= NULL
)
6216 if (var_decl
== NULL
)
6218 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
6219 decl_init
= gogo
->backend()->expression_statement(init_bexpr
);
6223 Location loc
= this->location();
6224 Expression
* val_expr
=
6225 Expression::make_cast(this->type(), this->init_
, loc
);
6226 Bexpression
* val
= val_expr
->get_backend(&context
);
6227 Bexpression
* var_ref
= gogo
->backend()->var_expression(var_decl
, loc
);
6228 decl_init
= gogo
->backend()->assignment_statement(var_ref
, val
, loc
);
6231 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
6232 if (decl_init
!= NULL
)
6233 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
6237 // Export the variable
6240 Variable::export_var(Export
* exp
, const std::string
& name
) const
6242 go_assert(this->is_global_
);
6243 exp
->write_c_string("var ");
6244 exp
->write_string(name
);
6245 exp
->write_c_string(" ");
6246 exp
->write_type(this->type());
6247 exp
->write_c_string(";\n");
6250 // Import a variable.
6253 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
6255 imp
->require_c_string("var ");
6256 *pname
= imp
->read_identifier();
6257 imp
->require_c_string(" ");
6258 *ptype
= imp
->read_type();
6259 imp
->require_c_string(";\n");
6262 // Convert a variable to the backend representation.
6265 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6266 const Package
* package
, const std::string
& name
)
6268 if (this->backend_
== NULL
)
6270 Backend
* backend
= gogo
->backend();
6271 Type
* type
= this->type_
;
6272 if (type
->is_error_type()
6273 || (type
->is_undefined()
6274 && (!this->is_global_
|| package
== NULL
)))
6275 this->backend_
= backend
->error_variable();
6278 bool is_parameter
= this->is_parameter_
;
6279 if (this->is_receiver_
&& type
->points_to() == NULL
)
6280 is_parameter
= false;
6281 if (this->is_in_heap())
6283 is_parameter
= false;
6284 type
= Type::make_pointer_type(type
);
6287 std::string n
= Gogo::unpack_hidden_name(name
);
6288 Btype
* btype
= type
->get_backend(gogo
);
6291 if (gogo
->is_zero_value(this))
6292 bvar
= gogo
->backend_zero_value();
6293 else if (this->is_global_
)
6294 bvar
= backend
->global_variable((package
== NULL
6295 ? gogo
->package_name()
6296 : package
->package_name()),
6298 ? gogo
->pkgpath_symbol()
6299 : package
->pkgpath_symbol()),
6303 Gogo::is_hidden_name(name
),
6304 this->in_unique_section_
,
6306 else if (function
== NULL
)
6308 go_assert(saw_errors());
6309 bvar
= backend
->error_variable();
6313 Bfunction
* bfunction
= function
->func_value()->get_decl();
6314 bool is_address_taken
= (this->is_non_escaping_address_taken_
6315 && !this->is_in_heap());
6316 if (this->is_closure())
6317 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
6319 else if (is_parameter
)
6320 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
6324 bvar
= backend
->local_variable(bfunction
, n
, btype
,
6328 this->backend_
= bvar
;
6331 return this->backend_
;
6334 // Class Result_variable.
6336 // Convert a result variable to the backend representation.
6339 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6340 const std::string
& name
)
6342 if (this->backend_
== NULL
)
6344 Backend
* backend
= gogo
->backend();
6345 Type
* type
= this->type_
;
6346 if (type
->is_error())
6347 this->backend_
= backend
->error_variable();
6350 if (this->is_in_heap())
6351 type
= Type::make_pointer_type(type
);
6352 Btype
* btype
= type
->get_backend(gogo
);
6353 Bfunction
* bfunction
= function
->func_value()->get_decl();
6354 std::string n
= Gogo::unpack_hidden_name(name
);
6355 bool is_address_taken
= (this->is_non_escaping_address_taken_
6356 && !this->is_in_heap());
6357 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
6362 return this->backend_
;
6365 // Class Named_constant.
6367 // Traverse the initializer expression.
6370 Named_constant::traverse_expression(Traverse
* traverse
)
6372 return Expression::traverse(&this->expr_
, traverse
);
6375 // Determine the type of the constant.
6378 Named_constant::determine_type()
6380 if (this->type_
!= NULL
)
6382 Type_context
context(this->type_
, false);
6383 this->expr_
->determine_type(&context
);
6387 // A constant may have an abstract type.
6388 Type_context
context(NULL
, true);
6389 this->expr_
->determine_type(&context
);
6390 this->type_
= this->expr_
->type();
6391 go_assert(this->type_
!= NULL
);
6395 // Indicate that we found and reported an error for this constant.
6398 Named_constant::set_error()
6400 this->type_
= Type::make_error_type();
6401 this->expr_
= Expression::make_error(this->location_
);
6404 // Export a constant.
6407 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
6409 exp
->write_c_string("const ");
6410 exp
->write_string(name
);
6411 exp
->write_c_string(" ");
6412 if (!this->type_
->is_abstract())
6414 exp
->write_type(this->type_
);
6415 exp
->write_c_string(" ");
6417 exp
->write_c_string("= ");
6418 this->expr()->export_expression(exp
);
6419 exp
->write_c_string(";\n");
6422 // Import a constant.
6425 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
6428 imp
->require_c_string("const ");
6429 *pname
= imp
->read_identifier();
6430 imp
->require_c_string(" ");
6431 if (imp
->peek_char() == '=')
6435 *ptype
= imp
->read_type();
6436 imp
->require_c_string(" ");
6438 imp
->require_c_string("= ");
6439 *pexpr
= Expression::import_expression(imp
);
6440 imp
->require_c_string(";\n");
6443 // Get the backend representation.
6446 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
6448 if (this->bconst_
== NULL
)
6450 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
6451 Type
* type
= this->type();
6452 Location loc
= this->location();
6454 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
6455 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
6456 if (type
!= NULL
&& type
->is_numeric_type())
6458 Btype
* btype
= type
->get_backend(gogo
);
6459 std::string name
= const_no
->get_id(gogo
);
6461 gogo
->backend()->named_constant_expression(btype
, name
,
6464 this->bconst_
= const_decl
;
6466 return this->bconst_
;
6472 Type_declaration::add_method(const std::string
& name
, Function
* function
)
6474 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
6475 this->methods_
.push_back(ret
);
6479 // Add a method declaration.
6482 Type_declaration::add_method_declaration(const std::string
& name
,
6484 Function_type
* type
,
6487 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
6489 this->methods_
.push_back(ret
);
6493 // Return whether any methods ere defined.
6496 Type_declaration::has_methods() const
6498 return !this->methods_
.empty();
6501 // Define methods for the real type.
6504 Type_declaration::define_methods(Named_type
* nt
)
6506 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
6507 p
!= this->methods_
.end();
6509 nt
->add_existing_method(*p
);
6512 // We are using the type. Return true if we should issue a warning.
6515 Type_declaration::using_type()
6517 bool ret
= !this->issued_warning_
;
6518 this->issued_warning_
= true;
6522 // Class Unknown_name.
6524 // Set the real named object.
6527 Unknown_name::set_real_named_object(Named_object
* no
)
6529 go_assert(this->real_named_object_
== NULL
);
6530 go_assert(!no
->is_unknown());
6531 this->real_named_object_
= no
;
6534 // Class Named_object.
6536 Named_object::Named_object(const std::string
& name
,
6537 const Package
* package
,
6538 Classification classification
)
6539 : name_(name
), package_(package
), classification_(classification
)
6541 if (Gogo::is_sink_name(name
))
6542 go_assert(classification
== NAMED_OBJECT_SINK
);
6545 // Make an unknown name. This is used by the parser. The name must
6546 // be resolved later. Unknown names are only added in the current
6550 Named_object::make_unknown_name(const std::string
& name
,
6553 Named_object
* named_object
= new Named_object(name
, NULL
,
6554 NAMED_OBJECT_UNKNOWN
);
6555 Unknown_name
* value
= new Unknown_name(location
);
6556 named_object
->u_
.unknown_value
= value
;
6557 return named_object
;
6563 Named_object::make_constant(const Typed_identifier
& tid
,
6564 const Package
* package
, Expression
* expr
,
6567 Named_object
* named_object
= new Named_object(tid
.name(), package
,
6568 NAMED_OBJECT_CONST
);
6569 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
6572 named_object
->u_
.const_value
= named_constant
;
6573 return named_object
;
6576 // Make a named type.
6579 Named_object::make_type(const std::string
& name
, const Package
* package
,
6580 Type
* type
, Location location
)
6582 Named_object
* named_object
= new Named_object(name
, package
,
6584 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
6585 named_object
->u_
.type_value
= named_type
;
6586 return named_object
;
6589 // Make a type declaration.
6592 Named_object::make_type_declaration(const std::string
& name
,
6593 const Package
* package
,
6596 Named_object
* named_object
= new Named_object(name
, package
,
6597 NAMED_OBJECT_TYPE_DECLARATION
);
6598 Type_declaration
* type_declaration
= new Type_declaration(location
);
6599 named_object
->u_
.type_declaration
= type_declaration
;
6600 return named_object
;
6606 Named_object::make_variable(const std::string
& name
, const Package
* package
,
6609 Named_object
* named_object
= new Named_object(name
, package
,
6611 named_object
->u_
.var_value
= variable
;
6612 return named_object
;
6615 // Make a result variable.
6618 Named_object::make_result_variable(const std::string
& name
,
6619 Result_variable
* result
)
6621 Named_object
* named_object
= new Named_object(name
, NULL
,
6622 NAMED_OBJECT_RESULT_VAR
);
6623 named_object
->u_
.result_var_value
= result
;
6624 return named_object
;
6627 // Make a sink. This is used for the special blank identifier _.
6630 Named_object::make_sink()
6632 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
6635 // Make a named function.
6638 Named_object::make_function(const std::string
& name
, const Package
* package
,
6641 Named_object
* named_object
= new Named_object(name
, package
,
6643 named_object
->u_
.func_value
= function
;
6644 return named_object
;
6647 // Make a function declaration.
6650 Named_object::make_function_declaration(const std::string
& name
,
6651 const Package
* package
,
6652 Function_type
* fntype
,
6655 Named_object
* named_object
= new Named_object(name
, package
,
6656 NAMED_OBJECT_FUNC_DECLARATION
);
6657 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
6658 named_object
->u_
.func_declaration_value
= func_decl
;
6659 return named_object
;
6665 Named_object::make_package(const std::string
& alias
, Package
* package
)
6667 Named_object
* named_object
= new Named_object(alias
, NULL
,
6668 NAMED_OBJECT_PACKAGE
);
6669 named_object
->u_
.package_value
= package
;
6670 return named_object
;
6673 // Return the name to use in an error message.
6676 Named_object::message_name() const
6678 if (this->package_
== NULL
)
6679 return Gogo::message_name(this->name_
);
6681 if (this->package_
->has_package_name())
6682 ret
= this->package_
->package_name();
6684 ret
= this->package_
->pkgpath();
6685 ret
= Gogo::message_name(ret
);
6687 ret
+= Gogo::message_name(this->name_
);
6691 // Set the type when a declaration is defined.
6694 Named_object::set_type_value(Named_type
* named_type
)
6696 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
6697 Type_declaration
* td
= this->u_
.type_declaration
;
6698 td
->define_methods(named_type
);
6700 Named_object
* in_function
= td
->in_function(&index
);
6701 if (in_function
!= NULL
)
6702 named_type
->set_in_function(in_function
, index
);
6704 this->classification_
= NAMED_OBJECT_TYPE
;
6705 this->u_
.type_value
= named_type
;
6708 // Define a function which was previously declared.
6711 Named_object::set_function_value(Function
* function
)
6713 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
6714 if (this->func_declaration_value()->has_descriptor())
6716 Expression
* descriptor
=
6717 this->func_declaration_value()->descriptor(NULL
, NULL
);
6718 function
->set_descriptor(descriptor
);
6720 this->classification_
= NAMED_OBJECT_FUNC
;
6721 // FIXME: We should free the old value.
6722 this->u_
.func_value
= function
;
6725 // Declare an unknown object as a type declaration.
6728 Named_object::declare_as_type()
6730 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
6731 Unknown_name
* unk
= this->u_
.unknown_value
;
6732 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
6733 this->u_
.type_declaration
= new Type_declaration(unk
->location());
6737 // Return the location of a named object.
6740 Named_object::location() const
6742 switch (this->classification_
)
6745 case NAMED_OBJECT_UNINITIALIZED
:
6748 case NAMED_OBJECT_ERRONEOUS
:
6749 return Linemap::unknown_location();
6751 case NAMED_OBJECT_UNKNOWN
:
6752 return this->unknown_value()->location();
6754 case NAMED_OBJECT_CONST
:
6755 return this->const_value()->location();
6757 case NAMED_OBJECT_TYPE
:
6758 return this->type_value()->location();
6760 case NAMED_OBJECT_TYPE_DECLARATION
:
6761 return this->type_declaration_value()->location();
6763 case NAMED_OBJECT_VAR
:
6764 return this->var_value()->location();
6766 case NAMED_OBJECT_RESULT_VAR
:
6767 return this->result_var_value()->location();
6769 case NAMED_OBJECT_SINK
:
6772 case NAMED_OBJECT_FUNC
:
6773 return this->func_value()->location();
6775 case NAMED_OBJECT_FUNC_DECLARATION
:
6776 return this->func_declaration_value()->location();
6778 case NAMED_OBJECT_PACKAGE
:
6779 return this->package_value()->location();
6783 // Export a named object.
6786 Named_object::export_named_object(Export
* exp
) const
6788 switch (this->classification_
)
6791 case NAMED_OBJECT_UNINITIALIZED
:
6792 case NAMED_OBJECT_UNKNOWN
:
6795 case NAMED_OBJECT_ERRONEOUS
:
6798 case NAMED_OBJECT_CONST
:
6799 this->const_value()->export_const(exp
, this->name_
);
6802 case NAMED_OBJECT_TYPE
:
6803 this->type_value()->export_named_type(exp
, this->name_
);
6806 case NAMED_OBJECT_TYPE_DECLARATION
:
6807 error_at(this->type_declaration_value()->location(),
6808 "attempt to export %<%s%> which was declared but not defined",
6809 this->message_name().c_str());
6812 case NAMED_OBJECT_FUNC_DECLARATION
:
6813 this->func_declaration_value()->export_func(exp
, this->name_
);
6816 case NAMED_OBJECT_VAR
:
6817 this->var_value()->export_var(exp
, this->name_
);
6820 case NAMED_OBJECT_RESULT_VAR
:
6821 case NAMED_OBJECT_SINK
:
6824 case NAMED_OBJECT_FUNC
:
6825 this->func_value()->export_func(exp
, this->name_
);
6830 // Convert a variable to the backend representation.
6833 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
6835 if (this->classification_
== NAMED_OBJECT_VAR
)
6836 return this->var_value()->get_backend_variable(gogo
, function
,
6837 this->package_
, this->name_
);
6838 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
6839 return this->result_var_value()->get_backend_variable(gogo
, function
,
6846 // Return the external identifier for this object.
6849 Named_object::get_id(Gogo
* gogo
)
6851 go_assert(!this->is_variable() && !this->is_result_variable());
6852 std::string decl_name
;
6853 if (this->is_function_declaration()
6854 && !this->func_declaration_value()->asm_name().empty())
6855 decl_name
= this->func_declaration_value()->asm_name();
6856 else if (this->is_type()
6857 && Linemap::is_predeclared_location(this->type_value()->location()))
6859 // We don't need the package name for builtin types.
6860 decl_name
= Gogo::unpack_hidden_name(this->name_
);
6864 std::string package_name
;
6865 if (this->package_
== NULL
)
6866 package_name
= gogo
->package_name();
6868 package_name
= this->package_
->package_name();
6870 // Note that this will be misleading if this is an unexported
6871 // method generated for an embedded imported type. In that case
6872 // the unexported method should have the package name of the
6873 // package from which it is imported, but we are going to give
6874 // it our package name. Fixing this would require knowing the
6875 // package name, but we only know the package path. It might be
6876 // better to use package paths here anyhow. This doesn't affect
6877 // the assembler code, because we always set that name in
6878 // Function::get_or_make_decl anyhow. FIXME.
6880 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
6882 Function_type
* fntype
;
6883 if (this->is_function())
6884 fntype
= this->func_value()->type();
6885 else if (this->is_function_declaration())
6886 fntype
= this->func_declaration_value()->type();
6889 if (fntype
!= NULL
&& fntype
->is_method())
6891 decl_name
.push_back('.');
6892 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
6895 if (this->is_type())
6898 const Named_object
* in_function
= this->type_value()->in_function(&index
);
6899 if (in_function
!= NULL
)
6901 decl_name
+= '$' + Gogo::unpack_hidden_name(in_function
->name());
6905 snprintf(buf
, sizeof buf
, "%u", index
);
6914 // Get the backend representation for this named object.
6917 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
6918 std::vector
<Btype
*>& type_decls
,
6919 std::vector
<Bfunction
*>& func_decls
)
6921 switch (this->classification_
)
6923 case NAMED_OBJECT_CONST
:
6924 if (!Gogo::is_erroneous_name(this->name_
))
6925 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
6928 case NAMED_OBJECT_TYPE
:
6930 Named_type
* named_type
= this->u_
.type_value
;
6931 if (!Gogo::is_erroneous_name(this->name_
))
6932 type_decls
.push_back(named_type
->get_backend(gogo
));
6934 // We need to produce a type descriptor for every named
6935 // type, and for a pointer to every named type, since
6936 // other files or packages might refer to them. We need
6937 // to do this even for hidden types, because they might
6938 // still be returned by some function. Simply calling the
6939 // type_descriptor method is enough to create the type
6940 // descriptor, even though we don't do anything with it.
6941 if (this->package_
== NULL
)
6944 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
6945 named_type
->gc_symbol_pointer(gogo
);
6946 Type
* pn
= Type::make_pointer_type(named_type
);
6947 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
6948 pn
->gc_symbol_pointer(gogo
);
6953 case NAMED_OBJECT_TYPE_DECLARATION
:
6954 error("reference to undefined type %qs",
6955 this->message_name().c_str());
6958 case NAMED_OBJECT_VAR
:
6959 case NAMED_OBJECT_RESULT_VAR
:
6960 case NAMED_OBJECT_SINK
:
6963 case NAMED_OBJECT_FUNC
:
6965 Function
* func
= this->u_
.func_value
;
6966 if (!Gogo::is_erroneous_name(this->name_
))
6967 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
6969 if (func
->block() != NULL
)
6970 func
->build(gogo
, this);
6974 case NAMED_OBJECT_ERRONEOUS
:
6984 Bindings::Bindings(Bindings
* enclosing
)
6985 : enclosing_(enclosing
), named_objects_(), bindings_()
6992 Bindings::clear_file_scope(Gogo
* gogo
)
6994 Contour::iterator p
= this->bindings_
.begin();
6995 while (p
!= this->bindings_
.end())
6998 if (p
->second
->package() != NULL
)
7000 else if (p
->second
->is_package())
7002 else if (p
->second
->is_function()
7003 && !p
->second
->func_value()->type()->is_method()
7004 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
7013 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
7014 p
= this->bindings_
.erase(p
);
7019 // Look up a symbol.
7022 Bindings::lookup(const std::string
& name
) const
7024 Contour::const_iterator p
= this->bindings_
.find(name
);
7025 if (p
!= this->bindings_
.end())
7026 return p
->second
->resolve();
7027 else if (this->enclosing_
!= NULL
)
7028 return this->enclosing_
->lookup(name
);
7033 // Look up a symbol locally.
7036 Bindings::lookup_local(const std::string
& name
) const
7038 Contour::const_iterator p
= this->bindings_
.find(name
);
7039 if (p
== this->bindings_
.end())
7044 // Remove an object from a set of bindings. This is used for a
7045 // special case in thunks for functions which call recover.
7048 Bindings::remove_binding(Named_object
* no
)
7050 Contour::iterator pb
= this->bindings_
.find(no
->name());
7051 go_assert(pb
!= this->bindings_
.end());
7052 this->bindings_
.erase(pb
);
7053 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
7054 pn
!= this->named_objects_
.end();
7059 this->named_objects_
.erase(pn
);
7066 // Add a method to the list of objects. This is not added to the
7067 // lookup table. This is so that we have a single list of objects
7068 // declared at the top level, which we walk through when it's time to
7069 // convert to trees.
7072 Bindings::add_method(Named_object
* method
)
7074 this->named_objects_
.push_back(method
);
7077 // Add a generic Named_object to a Contour.
7080 Bindings::add_named_object_to_contour(Contour
* contour
,
7081 Named_object
* named_object
)
7083 go_assert(named_object
== named_object
->resolve());
7084 const std::string
& name(named_object
->name());
7085 go_assert(!Gogo::is_sink_name(name
));
7087 std::pair
<Contour::iterator
, bool> ins
=
7088 contour
->insert(std::make_pair(name
, named_object
));
7091 // The name was already there.
7092 if (named_object
->package() != NULL
7093 && ins
.first
->second
->package() == named_object
->package()
7094 && (ins
.first
->second
->classification()
7095 == named_object
->classification()))
7097 // This is a second import of the same object.
7098 return ins
.first
->second
;
7100 ins
.first
->second
= this->new_definition(ins
.first
->second
,
7102 return ins
.first
->second
;
7106 // Don't push declarations on the list. We push them on when
7107 // and if we find the definitions. That way we genericize the
7108 // functions in order.
7109 if (!named_object
->is_type_declaration()
7110 && !named_object
->is_function_declaration()
7111 && !named_object
->is_unknown())
7112 this->named_objects_
.push_back(named_object
);
7113 return named_object
;
7117 // We had an existing named object OLD_OBJECT, and we've seen a new
7118 // one NEW_OBJECT with the same name. FIXME: This does not free the
7119 // new object when we don't need it.
7122 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
7124 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
7128 switch (old_object
->classification())
7131 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
7134 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7137 case Named_object::NAMED_OBJECT_UNKNOWN
:
7139 Named_object
* real
= old_object
->unknown_value()->real_named_object();
7141 return this->new_definition(real
, new_object
);
7142 go_assert(!new_object
->is_unknown());
7143 old_object
->unknown_value()->set_real_named_object(new_object
);
7144 if (!new_object
->is_type_declaration()
7145 && !new_object
->is_function_declaration())
7146 this->named_objects_
.push_back(new_object
);
7150 case Named_object::NAMED_OBJECT_CONST
:
7153 case Named_object::NAMED_OBJECT_TYPE
:
7154 if (new_object
->is_type_declaration())
7158 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7159 if (new_object
->is_type_declaration())
7161 if (new_object
->is_type())
7163 old_object
->set_type_value(new_object
->type_value());
7164 new_object
->type_value()->set_named_object(old_object
);
7165 this->named_objects_
.push_back(old_object
);
7170 case Named_object::NAMED_OBJECT_VAR
:
7171 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7172 // We have already given an error in the parser for cases where
7173 // one parameter or result variable redeclares another one.
7174 if ((new_object
->is_variable()
7175 && new_object
->var_value()->is_parameter())
7176 || new_object
->is_result_variable())
7180 case Named_object::NAMED_OBJECT_SINK
:
7183 case Named_object::NAMED_OBJECT_FUNC
:
7184 if (new_object
->is_function_declaration())
7186 if (!new_object
->func_declaration_value()->asm_name().empty())
7187 sorry("__asm__ for function definitions");
7188 Function_type
* old_type
= old_object
->func_value()->type();
7189 Function_type
* new_type
=
7190 new_object
->func_declaration_value()->type();
7191 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7196 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7198 Function_type
* old_type
= old_object
->func_declaration_value()->type();
7199 if (new_object
->is_function_declaration())
7201 Function_type
* new_type
=
7202 new_object
->func_declaration_value()->type();
7203 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7206 if (new_object
->is_function())
7208 Function_type
* new_type
= new_object
->func_value()->type();
7209 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7211 if (!old_object
->func_declaration_value()->asm_name().empty())
7212 sorry("__asm__ for function definitions");
7213 old_object
->set_function_value(new_object
->func_value());
7214 this->named_objects_
.push_back(old_object
);
7221 case Named_object::NAMED_OBJECT_PACKAGE
:
7225 std::string n
= old_object
->message_name();
7227 error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
7229 error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
7232 inform(old_object
->location(), "previous definition of %qs was here",
7238 // Add a named type.
7241 Bindings::add_named_type(Named_type
* named_type
)
7243 return this->add_named_object(named_type
->named_object());
7249 Bindings::add_function(const std::string
& name
, const Package
* package
,
7252 return this->add_named_object(Named_object::make_function(name
, package
,
7256 // Add a function declaration.
7259 Bindings::add_function_declaration(const std::string
& name
,
7260 const Package
* package
,
7261 Function_type
* type
,
7264 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
7266 return this->add_named_object(no
);
7269 // Define a type which was previously declared.
7272 Bindings::define_type(Named_object
* no
, Named_type
* type
)
7274 no
->set_type_value(type
);
7275 this->named_objects_
.push_back(no
);
7278 // Mark all local variables as used. This is used for some types of
7282 Bindings::mark_locals_used()
7284 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
7285 p
!= this->named_objects_
.end();
7287 if ((*p
)->is_variable())
7288 (*p
)->var_value()->set_is_used();
7291 // Traverse bindings.
7294 Bindings::traverse(Traverse
* traverse
, bool is_global
)
7296 unsigned int traverse_mask
= traverse
->traverse_mask();
7298 // We don't use an iterator because we permit the traversal to add
7299 // new global objects.
7300 const unsigned int e_or_t
= (Traverse::traverse_expressions
7301 | Traverse::traverse_types
);
7302 const unsigned int e_or_t_or_s
= (e_or_t
7303 | Traverse::traverse_statements
);
7304 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
7306 Named_object
* p
= this->named_objects_
[i
];
7307 int t
= TRAVERSE_CONTINUE
;
7308 switch (p
->classification())
7310 case Named_object::NAMED_OBJECT_CONST
:
7311 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
7312 t
= traverse
->constant(p
, is_global
);
7313 if (t
== TRAVERSE_CONTINUE
7314 && (traverse_mask
& e_or_t
) != 0)
7316 Type
* tc
= p
->const_value()->type();
7318 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
7319 return TRAVERSE_EXIT
;
7320 t
= p
->const_value()->traverse_expression(traverse
);
7324 case Named_object::NAMED_OBJECT_VAR
:
7325 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7326 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
7327 t
= traverse
->variable(p
);
7328 if (t
== TRAVERSE_CONTINUE
7329 && (traverse_mask
& e_or_t
) != 0)
7331 if (p
->is_result_variable()
7332 || p
->var_value()->has_type())
7334 Type
* tv
= (p
->is_variable()
7335 ? p
->var_value()->type()
7336 : p
->result_var_value()->type());
7338 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
7339 return TRAVERSE_EXIT
;
7342 if (t
== TRAVERSE_CONTINUE
7343 && (traverse_mask
& e_or_t_or_s
) != 0
7344 && p
->is_variable())
7345 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
7348 case Named_object::NAMED_OBJECT_FUNC
:
7349 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
7350 t
= traverse
->function(p
);
7352 if (t
== TRAVERSE_CONTINUE
7354 & (Traverse::traverse_variables
7355 | Traverse::traverse_constants
7356 | Traverse::traverse_functions
7357 | Traverse::traverse_blocks
7358 | Traverse::traverse_statements
7359 | Traverse::traverse_expressions
7360 | Traverse::traverse_types
)) != 0)
7361 t
= p
->func_value()->traverse(traverse
);
7364 case Named_object::NAMED_OBJECT_PACKAGE
:
7365 // These are traversed in Gogo::traverse.
7366 go_assert(is_global
);
7369 case Named_object::NAMED_OBJECT_TYPE
:
7370 if ((traverse_mask
& e_or_t
) != 0)
7371 t
= Type::traverse(p
->type_value(), traverse
);
7374 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7375 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7376 case Named_object::NAMED_OBJECT_UNKNOWN
:
7377 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7380 case Named_object::NAMED_OBJECT_SINK
:
7385 if (t
== TRAVERSE_EXIT
)
7386 return TRAVERSE_EXIT
;
7389 // If we need to traverse types, check the function declarations,
7390 // which have types. Also check any methods of a type declaration.
7391 if ((traverse_mask
& e_or_t
) != 0)
7393 for (Bindings::const_declarations_iterator p
=
7394 this->begin_declarations();
7395 p
!= this->end_declarations();
7398 if (p
->second
->is_function_declaration())
7400 if (Type::traverse(p
->second
->func_declaration_value()->type(),
7403 return TRAVERSE_EXIT
;
7405 else if (p
->second
->is_type_declaration())
7407 const std::vector
<Named_object
*>* methods
=
7408 p
->second
->type_declaration_value()->methods();
7409 for (std::vector
<Named_object
*>::const_iterator pm
=
7411 pm
!= methods
->end();
7414 Named_object
* no
= *pm
;
7416 if (no
->is_function())
7417 t
= no
->func_value()->type();
7418 else if (no
->is_function_declaration())
7419 t
= no
->func_declaration_value()->type();
7422 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
7423 return TRAVERSE_EXIT
;
7429 return TRAVERSE_CONTINUE
;
7434 // Clear any references to this label.
7439 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
7440 p
!= this->refs_
.end();
7443 this->refs_
.clear();
7446 // Get the backend representation for a label.
7449 Label::get_backend_label(Translate_context
* context
)
7451 if (this->blabel_
== NULL
)
7453 Function
* function
= context
->function()->func_value();
7454 Bfunction
* bfunction
= function
->get_decl();
7455 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
7458 return this->blabel_
;
7461 // Return an expression for the address of this label.
7464 Label::get_addr(Translate_context
* context
, Location location
)
7466 Blabel
* label
= this->get_backend_label(context
);
7467 return context
->backend()->label_address(label
, location
);
7470 // Class Unnamed_label.
7472 // Get the backend representation for an unnamed label.
7475 Unnamed_label::get_blabel(Translate_context
* context
)
7477 if (this->blabel_
== NULL
)
7479 Function
* function
= context
->function()->func_value();
7480 Bfunction
* bfunction
= function
->get_decl();
7481 this->blabel_
= context
->backend()->label(bfunction
, "",
7484 return this->blabel_
;
7487 // Return a statement which defines this unnamed label.
7490 Unnamed_label::get_definition(Translate_context
* context
)
7492 Blabel
* blabel
= this->get_blabel(context
);
7493 return context
->backend()->label_definition_statement(blabel
);
7496 // Return a goto statement to this unnamed label.
7499 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
7501 Blabel
* blabel
= this->get_blabel(context
);
7502 return context
->backend()->goto_statement(blabel
, location
);
7507 Package::Package(const std::string
& pkgpath
,
7508 const std::string
& pkgpath_symbol
, Location location
)
7509 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
7510 package_name_(), bindings_(new Bindings(NULL
)), priority_(0),
7511 location_(location
), used_(false), is_imported_(false),
7512 uses_sink_alias_(false)
7514 go_assert(!pkgpath
.empty());
7518 // Set the package name.
7521 Package::set_package_name(const std::string
& package_name
, Location location
)
7523 go_assert(!package_name
.empty());
7524 if (this->package_name_
.empty())
7525 this->package_name_
= package_name
;
7526 else if (this->package_name_
!= package_name
)
7528 "saw two different packages with the same package path %s: %s, %s",
7529 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
7530 package_name
.c_str());
7533 // Return the pkgpath symbol, which is a prefix for symbols defined in
7537 Package::pkgpath_symbol() const
7539 if (this->pkgpath_symbol_
.empty())
7541 // In the general case, this is wrong, because the package might
7542 // have been compiled with -fprefix. However, it is what we
7543 // used to do, so it is no more wrong than we were before.
7544 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
7546 return this->pkgpath_symbol_
;
7549 // Set the package path symbol.
7552 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
7554 go_assert(!pkgpath_symbol
.empty());
7555 if (this->pkgpath_symbol_
.empty())
7556 this->pkgpath_symbol_
= pkgpath_symbol
;
7558 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
7561 // Set the priority. We may see multiple priorities for an imported
7562 // package; we want to use the largest one.
7565 Package::set_priority(int priority
)
7567 if (priority
> this->priority_
)
7568 this->priority_
= priority
;
7571 // Forget a given usage. If forgetting this usage means this package becomes
7572 // unused, report that error.
7575 Package::forget_usage(Expression
* usage
) const
7577 if (this->fake_uses_
.empty())
7580 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
7581 go_assert(p
!= this->fake_uses_
.end());
7582 this->fake_uses_
.erase(p
);
7584 if (this->fake_uses_
.empty())
7585 error_at(this->location(), "imported and not used: %s",
7586 Gogo::message_name(this->package_name()).c_str());
7589 // Clear the used field for the next file. If the only usages of this package
7590 // are possibly fake, keep the fake usages for lowering.
7593 Package::clear_used()
7595 if (this->used_
> this->fake_uses_
.size())
7596 this->fake_uses_
.clear();
7601 // Determine types of constants. Everything else in a package
7602 // (variables, function declarations) should already have a fixed
7603 // type. Constants may have abstract types.
7606 Package::determine_types()
7608 Bindings
* bindings
= this->bindings_
;
7609 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
7610 p
!= bindings
->end_definitions();
7613 if ((*p
)->is_const())
7614 (*p
)->const_value()->determine_type();
7622 Traverse::~Traverse()
7624 if (this->types_seen_
!= NULL
)
7625 delete this->types_seen_
;
7626 if (this->expressions_seen_
!= NULL
)
7627 delete this->expressions_seen_
;
7630 // Record that we are looking at a type, and return true if we have
7634 Traverse::remember_type(const Type
* type
)
7636 if (type
->is_error_type())
7638 go_assert((this->traverse_mask() & traverse_types
) != 0
7639 || (this->traverse_mask() & traverse_expressions
) != 0);
7640 // We mostly only have to remember named types. But it turns out
7641 // that an interface type can refer to itself without using a name
7642 // by relying on interface inheritance, as in
7643 // type I interface { F() interface{I} }
7644 if (type
->classification() != Type::TYPE_NAMED
7645 && type
->classification() != Type::TYPE_INTERFACE
)
7647 if (this->types_seen_
== NULL
)
7648 this->types_seen_
= new Types_seen();
7649 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
7653 // Record that we are looking at an expression, and return true if we
7654 // have already seen it.
7657 Traverse::remember_expression(const Expression
* expression
)
7659 go_assert((this->traverse_mask() & traverse_types
) != 0
7660 || (this->traverse_mask() & traverse_expressions
) != 0);
7661 if (this->expressions_seen_
== NULL
)
7662 this->expressions_seen_
= new Expressions_seen();
7663 std::pair
<Expressions_seen::iterator
, bool> ins
=
7664 this->expressions_seen_
->insert(expression
);
7668 // The default versions of these functions should never be called: the
7669 // traversal mask indicates which functions may be called.
7672 Traverse::variable(Named_object
*)
7678 Traverse::constant(Named_object
*, bool)
7684 Traverse::function(Named_object
*)
7690 Traverse::block(Block
*)
7696 Traverse::statement(Block
*, size_t*, Statement
*)
7702 Traverse::expression(Expression
**)
7708 Traverse::type(Type
*)
7713 // Class Statement_inserter.
7716 Statement_inserter::insert(Statement
* s
)
7718 if (this->block_
!= NULL
)
7720 go_assert(this->pindex_
!= NULL
);
7721 this->block_
->insert_statement_before(*this->pindex_
, s
);
7724 else if (this->var_
!= NULL
)
7725 this->var_
->add_preinit_statement(this->gogo_
, s
);
7727 go_assert(saw_errors());