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.
13 #include "go-optimize.h"
16 #include "statements.h"
17 #include "expressions.h"
27 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
32 globals_(new Bindings(NULL
)),
35 imported_unsafe_(false),
49 pkgpath_from_option_(false),
50 prefix_from_option_(false),
51 relative_import_path_(),
54 specific_type_functions_(),
55 specific_type_functions_are_written_(false),
56 named_types_are_converted_(false)
58 const Location loc
= Linemap::predeclared_location();
60 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
61 RUNTIME_TYPE_KIND_UINT8
);
62 this->add_named_type(uint8_type
);
63 this->add_named_type(Type::make_integer_type("uint16", true, 16,
64 RUNTIME_TYPE_KIND_UINT16
));
65 this->add_named_type(Type::make_integer_type("uint32", true, 32,
66 RUNTIME_TYPE_KIND_UINT32
));
67 this->add_named_type(Type::make_integer_type("uint64", true, 64,
68 RUNTIME_TYPE_KIND_UINT64
));
70 this->add_named_type(Type::make_integer_type("int8", false, 8,
71 RUNTIME_TYPE_KIND_INT8
));
72 this->add_named_type(Type::make_integer_type("int16", false, 16,
73 RUNTIME_TYPE_KIND_INT16
));
74 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
75 RUNTIME_TYPE_KIND_INT32
);
76 this->add_named_type(int32_type
);
77 this->add_named_type(Type::make_integer_type("int64", false, 64,
78 RUNTIME_TYPE_KIND_INT64
));
80 this->add_named_type(Type::make_float_type("float32", 32,
81 RUNTIME_TYPE_KIND_FLOAT32
));
82 this->add_named_type(Type::make_float_type("float64", 64,
83 RUNTIME_TYPE_KIND_FLOAT64
));
85 this->add_named_type(Type::make_complex_type("complex64", 64,
86 RUNTIME_TYPE_KIND_COMPLEX64
));
87 this->add_named_type(Type::make_complex_type("complex128", 128,
88 RUNTIME_TYPE_KIND_COMPLEX128
));
90 int int_type_size
= pointer_size
;
91 if (int_type_size
< 32)
93 this->add_named_type(Type::make_integer_type("uint", true,
95 RUNTIME_TYPE_KIND_UINT
));
96 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
97 RUNTIME_TYPE_KIND_INT
);
98 this->add_named_type(int_type
);
100 this->add_named_type(Type::make_integer_type("uintptr", true,
102 RUNTIME_TYPE_KIND_UINTPTR
));
104 // "byte" is an alias for "uint8".
105 uint8_type
->integer_type()->set_is_byte();
106 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
108 this->add_named_type(byte_type
->type_value());
110 // "rune" is an alias for "int32".
111 int32_type
->integer_type()->set_is_rune();
112 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
114 this->add_named_type(rune_type
->type_value());
116 this->add_named_type(Type::make_named_bool_type());
118 this->add_named_type(Type::make_named_string_type());
120 // "error" is interface { Error() string }.
122 Typed_identifier_list
*methods
= new Typed_identifier_list
;
123 Typed_identifier_list
*results
= new Typed_identifier_list
;
124 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
125 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
126 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
127 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
128 error_iface
->finalize_methods();
129 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
130 this->add_named_type(error_type
);
133 this->globals_
->add_constant(Typed_identifier("true",
134 Type::make_boolean_type(),
137 Expression::make_boolean(true, loc
),
139 this->globals_
->add_constant(Typed_identifier("false",
140 Type::make_boolean_type(),
143 Expression::make_boolean(false, loc
),
146 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
149 Expression::make_nil(loc
),
152 Type
* abstract_int_type
= Type::make_abstract_integer_type();
153 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
156 Expression::make_iota(),
159 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
160 new_type
->set_is_varargs();
161 new_type
->set_is_builtin();
162 Node::Escape_states
* new_escapes
=
163 new Node::Escape_states(1, Node::ESCAPE_NONE
);
164 new_type
->set_parameter_escape_states(new_escapes
);
165 new_type
->set_has_escape_info();
166 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
168 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
169 make_type
->set_is_varargs();
170 make_type
->set_is_builtin();
171 Node::Escape_states
* make_escapes
=
172 new Node::Escape_states(2, Node::ESCAPE_NONE
);
173 make_type
->set_parameter_escape_states(make_escapes
);
174 make_type
->set_has_escape_info();
175 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
177 Typed_identifier_list
* len_result
= new Typed_identifier_list();
178 len_result
->push_back(Typed_identifier("", int_type
, loc
));
179 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
181 len_type
->set_is_builtin();
182 Node::Escape_states
* len_escapes
=
183 new Node::Escape_states(1, Node::ESCAPE_NONE
);
184 len_type
->set_parameter_escape_states(len_escapes
);
185 len_type
->set_has_escape_info();
186 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
188 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
189 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
190 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
192 cap_type
->set_is_builtin();
193 Node::Escape_states
* cap_escapes
=
194 new Node::Escape_states(1, Node::ESCAPE_NONE
);
195 cap_type
->set_parameter_escape_states(cap_escapes
);
196 cap_type
->set_has_escape_info();
197 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
199 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
200 print_type
->set_is_varargs();
201 print_type
->set_is_builtin();
202 Node::Escape_states
* print_escapes
=
203 new Node::Escape_states(1, Node::ESCAPE_NONE
);
204 print_type
->set_parameter_escape_states(print_escapes
);
205 print_type
->set_has_escape_info();
206 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
208 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
209 print_type
->set_is_varargs();
210 print_type
->set_is_builtin();
211 print_type
->set_parameter_escape_states(print_escapes
);
212 print_type
->set_has_escape_info();
213 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
215 Type
*empty
= Type::make_empty_interface_type(loc
);
216 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
217 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
218 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
220 panic_type
->set_is_builtin();
221 Node::Escape_states
* panic_escapes
=
222 new Node::Escape_states(1, Node::ESCAPE_ARG
);
223 panic_type
->set_parameter_escape_states(panic_escapes
);
224 panic_type
->set_has_escape_info();
225 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
227 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
228 recover_result
->push_back(Typed_identifier("", empty
, loc
));
229 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
232 recover_type
->set_is_builtin();
233 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
235 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
236 close_type
->set_is_varargs();
237 close_type
->set_is_builtin();
238 Node::Escape_states
* close_escapes
=
239 new Node::Escape_states(1, Node::ESCAPE_NONE
);
240 close_type
->set_parameter_escape_states(close_escapes
);
241 close_type
->set_has_escape_info();
242 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
244 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
245 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
246 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
248 copy_type
->set_is_varargs();
249 copy_type
->set_is_builtin();
250 Node::Escape_states
* copy_escapes
=
251 new Node::Escape_states(2, Node::ESCAPE_NONE
);
252 copy_type
->set_parameter_escape_states(copy_escapes
);
253 copy_type
->set_has_escape_info();
254 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
256 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
257 append_type
->set_is_varargs();
258 append_type
->set_is_builtin();
259 Node::Escape_states
* append_escapes
= new Node::Escape_states
;
260 append_escapes
->push_back(Node::ESCAPE_ARG
);
261 append_escapes
->push_back(Node::ESCAPE_NONE
);
262 append_type
->set_parameter_escape_states(append_escapes
);
263 append_type
->set_has_escape_info();
264 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
266 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
267 complex_type
->set_is_varargs();
268 complex_type
->set_is_builtin();
269 Node::Escape_states
* complex_escapes
=
270 new Node::Escape_states(2, Node::ESCAPE_NONE
);
271 complex_type
->set_parameter_escape_states(complex_escapes
);
272 complex_type
->set_has_escape_info();
273 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
275 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
276 real_type
->set_is_varargs();
277 real_type
->set_is_builtin();
278 Node::Escape_states
* real_escapes
=
279 new Node::Escape_states(1, Node::ESCAPE_NONE
);
280 real_type
->set_parameter_escape_states(real_escapes
);
281 real_type
->set_has_escape_info();
282 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
284 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
285 imag_type
->set_is_varargs();
286 imag_type
->set_is_builtin();
287 Node::Escape_states
* imag_escapes
=
288 new Node::Escape_states(1, Node::ESCAPE_NONE
);
289 imag_type
->set_parameter_escape_states(imag_escapes
);
290 imag_type
->set_has_escape_info();
291 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
293 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
294 delete_type
->set_is_varargs();
295 delete_type
->set_is_builtin();
296 Node::Escape_states
* delete_escapes
=
297 new Node::Escape_states(2, Node::ESCAPE_NONE
);
298 delete_type
->set_parameter_escape_states(delete_escapes
);
299 delete_type
->set_has_escape_info();
300 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
303 // Convert a pkgpath into a string suitable for a symbol. Note that
304 // this transformation is convenient but imperfect. A -fgo-pkgpath
305 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
306 // possibly leading to link time errors.
309 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
311 std::string s
= pkgpath
;
312 for (size_t i
= 0; i
< s
.length(); ++i
)
315 if ((c
>= 'a' && c
<= 'z')
316 || (c
>= 'A' && c
<= 'Z')
317 || (c
>= '0' && c
<= '9'))
325 // Get the package path to use for type reflection data. This should
326 // ideally be unique across the entire link.
329 Gogo::pkgpath() const
331 go_assert(this->pkgpath_set_
);
332 return this->pkgpath_
;
335 // Set the package path from the -fgo-pkgpath command line option.
338 Gogo::set_pkgpath(const std::string
& arg
)
340 go_assert(!this->pkgpath_set_
);
341 this->pkgpath_
= arg
;
342 this->pkgpath_set_
= true;
343 this->pkgpath_from_option_
= true;
346 // Get the package path to use for symbol names.
349 Gogo::pkgpath_symbol() const
351 go_assert(this->pkgpath_set_
);
352 return this->pkgpath_symbol_
;
355 // Set the unique prefix to use to determine the package path, from
356 // the -fgo-prefix command line option.
359 Gogo::set_prefix(const std::string
& arg
)
361 go_assert(!this->prefix_from_option_
);
363 this->prefix_from_option_
= true;
366 // Munge name for use in an error message.
369 Gogo::message_name(const std::string
& name
)
371 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
374 // Get the package name.
377 Gogo::package_name() const
379 go_assert(this->package_
!= NULL
);
380 return this->package_
->package_name();
383 // Set the package name.
386 Gogo::set_package_name(const std::string
& package_name
,
389 if (this->package_
!= NULL
)
391 if (this->package_
->package_name() != package_name
)
392 error_at(location
, "expected package %<%s%>",
393 Gogo::message_name(this->package_
->package_name()).c_str());
397 // Now that we know the name of the package we are compiling, set
398 // the package path to use for reflect.Type.PkgPath and global
400 if (this->pkgpath_set_
)
401 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
404 if (!this->prefix_from_option_
&& package_name
== "main")
406 this->pkgpath_
= package_name
;
407 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
411 if (!this->prefix_from_option_
)
412 this->prefix_
= "go";
413 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
414 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
415 + Gogo::pkgpath_for_symbol(package_name
));
417 this->pkgpath_set_
= true;
420 this->package_
= this->register_package(this->pkgpath_
,
421 this->pkgpath_symbol_
, location
);
422 this->package_
->set_package_name(package_name
, location
);
424 if (this->is_main_package())
426 // Declare "main" as a function which takes no parameters and
428 Location uloc
= Linemap::unknown_location();
429 this->declare_function(Gogo::pack_hidden_name("main", false),
430 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
435 // Return whether this is the "main" package. This is not true if
436 // -fgo-pkgpath or -fgo-prefix was used.
439 Gogo::is_main_package() const
441 return (this->package_name() == "main"
442 && !this->pkgpath_from_option_
443 && !this->prefix_from_option_
);
449 Gogo::import_package(const std::string
& filename
,
450 const std::string
& local_name
,
451 bool is_local_name_exported
,
454 if (filename
.empty())
456 error_at(location
, "import path is empty");
460 const char *pf
= filename
.data();
461 const char *pend
= pf
+ filename
.length();
465 int adv
= Lex::fetch_char(pf
, &c
);
468 error_at(location
, "import path contains invalid UTF-8 sequence");
473 error_at(location
, "import path contains NUL");
476 if (c
< 0x20 || c
== 0x7f)
478 error_at(location
, "import path contains control character");
483 error_at(location
, "import path contains backslash; use slash");
486 if (Lex::is_unicode_space(c
))
488 error_at(location
, "import path contains space character");
491 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
493 error_at(location
, "import path contains invalid character '%c'", c
);
499 if (IS_ABSOLUTE_PATH(filename
.c_str()))
501 error_at(location
, "import path cannot be absolute path");
505 if (local_name
== "init")
506 error_at(location
, "cannot import package as init");
508 if (filename
== "unsafe")
510 this->import_unsafe(local_name
, is_local_name_exported
, location
);
514 Imports::const_iterator p
= this->imports_
.find(filename
);
515 if (p
!= this->imports_
.end())
517 Package
* package
= p
->second
;
518 package
->set_location(location
);
519 package
->set_is_imported();
520 std::string ln
= local_name
;
521 bool is_ln_exported
= is_local_name_exported
;
524 ln
= package
->package_name();
525 go_assert(!ln
.empty());
526 is_ln_exported
= Lex::is_exported_name(ln
);
530 Bindings
* bindings
= package
->bindings();
531 for (Bindings::const_declarations_iterator p
=
532 bindings
->begin_declarations();
533 p
!= bindings
->end_declarations();
535 this->add_dot_import_object(p
->second
);
538 package
->set_uses_sink_alias();
541 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
542 this->package_
->bindings()->add_package(ln
, package
);
547 Import::Stream
* stream
= Import::open_package(filename
, location
,
548 this->relative_import_path_
);
551 error_at(location
, "import file %qs not found", filename
.c_str());
555 Import
imp(stream
, location
);
556 imp
.register_builtin_types(this);
557 Package
* package
= imp
.import(this, local_name
, is_local_name_exported
);
560 if (package
->pkgpath() == this->pkgpath())
562 ("imported package uses same package path as package "
563 "being compiled (see -fgo-pkgpath option)"));
565 this->imports_
.insert(std::make_pair(filename
, package
));
566 package
->set_is_imported();
572 // Add an import control function for an imported package to the list.
575 Gogo::add_import_init_fn(const std::string
& package_name
,
576 const std::string
& init_name
, int prio
)
578 for (std::set
<Import_init
>::const_iterator p
=
579 this->imported_init_fns_
.begin();
580 p
!= this->imported_init_fns_
.end();
583 if (p
->init_name() == init_name
)
585 // If a test of package P1, built as part of package P1,
586 // imports package P2, and P2 imports P1 (perhaps
587 // indirectly), then we will see the same import name with
588 // different import priorities. That is OK, so don't give
589 // an error about it.
590 if (p
->package_name() != package_name
)
592 error("duplicate package initialization name %qs",
593 Gogo::message_name(init_name
).c_str());
594 inform(UNKNOWN_LOCATION
, "used by package %qs at priority %d",
595 Gogo::message_name(p
->package_name()).c_str(),
597 inform(UNKNOWN_LOCATION
, " and by package %qs at priority %d",
598 Gogo::message_name(package_name
).c_str(), prio
);
604 this->imported_init_fns_
.insert(Import_init(package_name
, init_name
,
608 // Return whether we are at the global binding level.
611 Gogo::in_global_scope() const
613 return this->functions_
.empty();
616 // Return the current binding contour.
619 Gogo::current_bindings()
621 if (!this->functions_
.empty())
622 return this->functions_
.back().blocks
.back()->bindings();
623 else if (this->package_
!= NULL
)
624 return this->package_
->bindings();
626 return this->globals_
;
630 Gogo::current_bindings() const
632 if (!this->functions_
.empty())
633 return this->functions_
.back().blocks
.back()->bindings();
634 else if (this->package_
!= NULL
)
635 return this->package_
->bindings();
637 return this->globals_
;
640 // Return the special variable used as the zero value of types.
643 Gogo::zero_value(Type
*type
)
645 if (this->zero_value_
== NULL
)
647 Location bloc
= Linemap::predeclared_location();
649 // We will change the type later, when we know the size.
650 Type
* byte_type
= this->lookup_global("byte")->type_value();
652 Expression
* zero
= Expression::make_integer_ul(0, NULL
, bloc
);
653 Type
* array_type
= Type::make_array_type(byte_type
, zero
);
655 Variable
* var
= new Variable(array_type
, NULL
, true, false, false, bloc
);
656 this->zero_value_
= Named_object::make_variable("go$zerovalue", NULL
,
660 // The zero value will be the maximum required size.
662 bool ok
= type
->backend_type_size(this, &size
);
664 go_assert(saw_errors());
667 if (size
> this->zero_value_size_
)
668 this->zero_value_size_
= size
;
671 ok
= type
->backend_type_align(this, &align
);
673 go_assert(saw_errors());
676 if (align
> this->zero_value_align_
)
677 this->zero_value_align_
= align
;
679 return this->zero_value_
;
682 // Return whether V is the zero value variable.
685 Gogo::is_zero_value(Variable
* v
) const
687 return this->zero_value_
!= NULL
&& this->zero_value_
->var_value() == v
;
690 // Return the backend variable for the special zero value, or NULL if
694 Gogo::backend_zero_value()
696 if (this->zero_value_
== NULL
)
699 Type
* byte_type
= this->lookup_global("byte")->type_value();
700 Btype
* bbtype_type
= byte_type
->get_backend(this);
702 Type
* int_type
= this->lookup_global("int")->type_value();
704 Expression
* e
= Expression::make_integer_int64(this->zero_value_size_
,
706 Linemap::unknown_location());
707 Translate_context
context(this, NULL
, NULL
, NULL
);
708 Bexpression
* blength
= e
->get_backend(&context
);
710 Btype
* barray_type
= this->backend()->array_type(bbtype_type
, blength
);
712 std::string zname
= this->zero_value_
->name();
714 this->backend()->implicit_variable(zname
, barray_type
, false,
715 true, true, this->zero_value_align_
);
716 this->backend()->implicit_variable_set_init(zvar
, zname
, barray_type
,
717 false, true, true, NULL
);
721 // Add statements to INIT_STMTS which run the initialization
722 // functions for imported packages. This is only used for the "main"
726 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
)
728 go_assert(this->is_main_package());
730 if (this->imported_init_fns_
.empty())
733 Location unknown_loc
= Linemap::unknown_location();
734 Function_type
* func_type
=
735 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
736 Btype
* fntype
= func_type
->get_backend_fntype(this);
738 // We must call them in increasing priority order.
739 std::vector
<Import_init
> v
;
740 for (std::set
<Import_init
>::const_iterator p
=
741 this->imported_init_fns_
.begin();
742 p
!= this->imported_init_fns_
.end();
745 std::sort(v
.begin(), v
.end());
747 // We build calls to the init functions, which take no arguments.
748 std::vector
<Bexpression
*> empty_args
;
749 for (std::vector
<Import_init
>::const_iterator p
= v
.begin();
753 std::string user_name
= p
->package_name() + ".init";
754 const std::string
& init_name(p
->init_name());
756 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
757 true, true, true, false,
759 Bexpression
* pfunc_code
=
760 this->backend()->function_code_expression(pfunc
, unknown_loc
);
761 Bexpression
* pfunc_call
=
762 this->backend()->call_expression(pfunc_code
, empty_args
,
764 init_stmts
.push_back(this->backend()->expression_statement(pfunc_call
));
768 // Register global variables with the garbage collector. We need to
769 // register all variables which can hold a pointer value. They become
770 // roots during the mark phase. We build a struct that is easy to
771 // hook into a list of roots.
773 // struct __go_gc_root_list
775 // struct __go_gc_root_list* __next;
776 // struct __go_gc_root
783 // The last entry in the roots array has a NULL decl field.
786 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
787 std::vector
<Bstatement
*>& init_stmts
)
792 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
793 Type
* uint_type
= Type::lookup_integer_type("uint");
794 Struct_type
* root_type
= Type::make_builtin_struct_type(2,
796 "__size", uint_type
);
798 Location builtin_loc
= Linemap::predeclared_location();
799 Expression
* length
= Expression::make_integer_ul(var_gc
.size(), NULL
,
802 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
803 Type
* ptdt
= Type::make_type_descriptor_ptr_type();
804 Struct_type
* root_list_type
=
805 Type::make_builtin_struct_type(2,
807 "__roots", root_array_type
);
809 // Build an initializer for the __roots array.
811 Expression_list
* roots_init
= new Expression_list();
814 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
818 Expression_list
* init
= new Expression_list();
820 Location no_loc
= (*p
)->location();
821 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
822 Expression
* decl_addr
=
823 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
824 init
->push_back(decl_addr
);
826 Expression
* decl_size
=
827 Expression::make_type_info(decl
->type(), Expression::TYPE_INFO_SIZE
);
828 init
->push_back(decl_size
);
830 Expression
* root_ctor
=
831 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
832 roots_init
->push_back(root_ctor
);
835 // The list ends with a NULL entry.
837 Expression_list
* null_init
= new Expression_list();
838 Expression
* nil
= Expression::make_nil(builtin_loc
);
839 null_init
->push_back(nil
);
841 Expression
*zero
= Expression::make_integer_ul(0, NULL
, builtin_loc
);
842 null_init
->push_back(zero
);
844 Expression
* null_root_ctor
=
845 Expression::make_struct_composite_literal(root_type
, null_init
,
847 roots_init
->push_back(null_root_ctor
);
849 // Build a constructor for the struct.
851 Expression_list
* root_list_init
= new Expression_list();
852 root_list_init
->push_back(nil
);
854 Expression
* roots_ctor
=
855 Expression::make_array_composite_literal(root_array_type
, roots_init
,
857 root_list_init
->push_back(roots_ctor
);
859 Expression
* root_list_ctor
=
860 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
863 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
865 root_addr
->unary_expression()->set_is_gc_root();
866 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
867 builtin_loc
, 1, root_addr
);
869 Translate_context
context(this, NULL
, NULL
, NULL
);
870 Bexpression
* bcall
= register_roots
->get_backend(&context
);
871 init_stmts
.push_back(this->backend()->expression_statement(bcall
));
874 // Get the name to use for the import control function. If there is a
875 // global function or variable, then we know that that name must be
876 // unique in the link, and we use it as the basis for our name.
879 Gogo::get_init_fn_name()
881 if (this->init_fn_name_
.empty())
883 go_assert(this->package_
!= NULL
);
884 if (this->is_main_package())
886 // Use a name which the runtime knows.
887 this->init_fn_name_
= "__go_init_main";
891 std::string s
= this->pkgpath_symbol();
892 s
.append("..import");
893 this->init_fn_name_
= s
;
897 return this->init_fn_name_
;
900 // Build the decl for the initialization function.
903 Gogo::initialization_function_decl()
905 std::string name
= this->get_init_fn_name();
906 Location loc
= this->package_
->location();
908 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
909 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
910 return Named_object::make_function(name
, NULL
, initfn
);
913 // Create the magic initialization function. CODE_STMT is the
914 // code that it needs to run.
917 Gogo::create_initialization_function(Named_object
* initfn
,
918 Bstatement
* code_stmt
)
920 // Make sure that we thought we needed an initialization function,
921 // as otherwise we will not have reported it in the export data.
922 go_assert(this->is_main_package() || this->need_init_fn_
);
925 initfn
= this->initialization_function_decl();
927 // Bind the initialization function code to a block.
928 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
929 Location pkg_loc
= this->package_
->location();
930 std::vector
<Bvariable
*> vars
;
931 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
933 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
935 go_assert(saw_errors());
941 // Search for references to VAR in any statements or called functions.
943 class Find_var
: public Traverse
946 // A hash table we use to avoid looping. The index is the name of a
947 // named object. We only look through objects defined in this
949 typedef Unordered_set(const void*) Seen_objects
;
951 Find_var(Named_object
* var
, Seen_objects
* seen_objects
)
952 : Traverse(traverse_expressions
),
953 var_(var
), seen_objects_(seen_objects
), found_(false)
956 // Whether the variable was found.
959 { return this->found_
; }
962 expression(Expression
**);
965 // The variable we are looking for.
967 // Names of objects we have already seen.
968 Seen_objects
* seen_objects_
;
969 // True if the variable was found.
973 // See if EXPR refers to VAR, looking through function calls and
974 // variable initializations.
977 Find_var::expression(Expression
** pexpr
)
979 Expression
* e
= *pexpr
;
981 Var_expression
* ve
= e
->var_expression();
984 Named_object
* v
= ve
->named_object();
988 return TRAVERSE_EXIT
;
991 if (v
->is_variable() && v
->package() == NULL
)
993 Expression
* init
= v
->var_value()->init();
996 std::pair
<Seen_objects::iterator
, bool> ins
=
997 this->seen_objects_
->insert(v
);
1000 // This is the first time we have seen this name.
1001 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1002 return TRAVERSE_EXIT
;
1008 // We traverse the code of any function or bound method we see. Note that
1009 // this means that we will traverse the code of a function or bound method
1010 // whose address is taken even if it is not called.
1011 Func_expression
* fe
= e
->func_expression();
1012 Bound_method_expression
* bme
= e
->bound_method_expression();
1013 if (fe
!= NULL
|| bme
!= NULL
)
1015 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1016 if (f
->is_function() && f
->package() == NULL
)
1018 std::pair
<Seen_objects::iterator
, bool> ins
=
1019 this->seen_objects_
->insert(f
);
1022 // This is the first time we have seen this name.
1023 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1024 return TRAVERSE_EXIT
;
1029 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1032 Temporary_statement
* ts
= tre
->statement();
1033 Expression
* init
= ts
->init();
1036 std::pair
<Seen_objects::iterator
, bool> ins
=
1037 this->seen_objects_
->insert(ts
);
1040 // This is the first time we have seen this temporary
1042 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1043 return TRAVERSE_EXIT
;
1048 return TRAVERSE_CONTINUE
;
1051 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1054 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1057 Find_var::Seen_objects seen_objects
;
1058 Find_var
find_var(var
, &seen_objects
);
1060 Expression::traverse(&expr
, &find_var
);
1061 if (preinit
!= NULL
)
1062 preinit
->traverse(&find_var
);
1065 Expression
* init
= dep
->var_value()->init();
1067 Expression::traverse(&init
, &find_var
);
1068 if (dep
->var_value()->has_pre_init())
1069 dep
->var_value()->preinit()->traverse(&find_var
);
1072 return find_var
.found();
1075 // Sort variable initializations. If the initialization expression
1076 // for variable A refers directly or indirectly to the initialization
1077 // expression for variable B, then we must initialize B before A.
1083 : var_(NULL
), init_(NULL
), dep_count_(0)
1086 Var_init(Named_object
* var
, Bstatement
* init
)
1087 : var_(var
), init_(init
), dep_count_(0)
1090 // Return the variable.
1093 { return this->var_
; }
1095 // Return the initialization expression.
1098 { return this->init_
; }
1100 // Return the number of remaining dependencies.
1103 { return this->dep_count_
; }
1105 // Increment the number of dependencies.
1108 { ++this->dep_count_
; }
1110 // Decrement the number of dependencies.
1113 { --this->dep_count_
; }
1116 // The variable being initialized.
1118 // The initialization statement.
1120 // The number of initializations this is dependent on. A variable
1121 // initialization should not be emitted if any of its dependencies
1122 // have not yet been resolved.
1126 // For comparing Var_init keys in a map.
1129 operator<(const Var_init
& v1
, const Var_init
& v2
)
1130 { return v1
.var()->name() < v2
.var()->name(); }
1132 typedef std::list
<Var_init
> Var_inits
;
1134 // Sort the variable initializations. The rule we follow is that we
1135 // emit them in the order they appear in the array, except that if the
1136 // initialization expression for a variable V1 depends upon another
1137 // variable V2 then we initialize V1 after V2.
1140 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1142 if (var_inits
->empty())
1145 typedef std::pair
<Named_object
*, Named_object
*> No_no
;
1146 typedef std::map
<No_no
, bool> Cache
;
1149 // A mapping from a variable initialization to a set of
1150 // variable initializations that depend on it.
1151 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1152 Init_deps init_deps
;
1153 bool init_loop
= false;
1154 for (Var_inits::iterator p1
= var_inits
->begin();
1155 p1
!= var_inits
->end();
1158 Named_object
* var
= p1
->var();
1159 Expression
* init
= var
->var_value()->init();
1160 Block
* preinit
= var
->var_value()->preinit();
1161 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1163 // Start walking through the list to see which variables VAR
1164 // needs to wait for.
1165 for (Var_inits::iterator p2
= var_inits
->begin();
1166 p2
!= var_inits
->end();
1169 if (var
== p2
->var())
1172 Named_object
* p2var
= p2
->var();
1173 No_no
key(var
, p2var
);
1174 std::pair
<Cache::iterator
, bool> ins
=
1175 cache
.insert(std::make_pair(key
, false));
1177 ins
.first
->second
= expression_requires(init
, preinit
, dep
, p2var
);
1178 if (ins
.first
->second
)
1180 // VAR depends on P2VAR.
1181 init_deps
[*p2
].insert(&(*p1
));
1182 p1
->add_dependency();
1184 // Check for cycles.
1185 key
= std::make_pair(p2var
, var
);
1186 ins
= cache
.insert(std::make_pair(key
, false));
1189 expression_requires(p2var
->var_value()->init(),
1190 p2var
->var_value()->preinit(),
1191 gogo
->var_depends_on(p2var
->var_value()),
1193 if (ins
.first
->second
)
1195 error_at(var
->location(),
1196 ("initialization expressions for %qs and "
1197 "%qs depend upon each other"),
1198 var
->message_name().c_str(),
1199 p2var
->message_name().c_str());
1200 inform(p2
->var()->location(), "%qs defined here",
1201 p2var
->message_name().c_str());
1209 // If there are no dependencies then the declaration order is sorted.
1210 if (!init_deps
.empty() && !init_loop
)
1212 // Otherwise, sort variable initializations by emitting all variables with
1213 // no dependencies in declaration order. VAR_INITS is already in
1214 // declaration order.
1216 while (!var_inits
->empty())
1218 Var_inits::iterator v1
;;
1219 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1221 if (v1
->dep_count() == 0)
1224 go_assert(v1
!= var_inits
->end());
1226 // V1 either has no dependencies or its dependencies have already
1227 // been emitted, add it to READY next. When V1 is emitted, remove
1228 // a dependency from each V that depends on V1.
1229 ready
.splice(ready
.end(), *var_inits
, v1
);
1231 Init_deps::iterator p1
= init_deps
.find(*v1
);
1232 if (p1
!= init_deps
.end())
1234 std::set
<Var_init
*> resolved
= p1
->second
;
1235 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1236 pv
!= resolved
.end();
1238 (*pv
)->remove_dependency();
1239 init_deps
.erase(p1
);
1242 var_inits
->swap(ready
);
1243 go_assert(init_deps
.empty());
1246 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1247 // check for a loop of VAR on itself. We only do this if
1248 // INIT is not NULL and there is no dependency; when INIT is
1249 // NULL, it means that PREINIT sets VAR, which we will
1250 // interpret as a loop.
1251 for (Var_inits::const_iterator p
= var_inits
->begin();
1252 p
!= var_inits
->end();
1255 Named_object
* var
= p
->var();
1256 Expression
* init
= var
->var_value()->init();
1257 Block
* preinit
= var
->var_value()->preinit();
1258 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1259 if (init
!= NULL
&& dep
== NULL
1260 && expression_requires(init
, preinit
, NULL
, var
))
1261 error_at(var
->location(),
1262 "initialization expression for %qs depends upon itself",
1263 var
->message_name().c_str());
1267 // Write out the global definitions.
1270 Gogo::write_globals()
1272 this->build_interface_method_tables();
1274 Bindings
* bindings
= this->current_bindings();
1276 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1277 p
!= bindings
->end_declarations();
1280 // If any function declarations needed a descriptor, make sure
1282 Named_object
* no
= p
->second
;
1283 if (no
->is_function_declaration())
1284 no
->func_declaration_value()->build_backend_descriptor(this);
1287 // Lists of globally declared types, variables, constants, and functions
1288 // that must be defined.
1289 std::vector
<Btype
*> type_decls
;
1290 std::vector
<Bvariable
*> var_decls
;
1291 std::vector
<Bexpression
*> const_decls
;
1292 std::vector
<Bfunction
*> func_decls
;
1294 // The init function declaration, if necessary.
1295 Named_object
* init_fndecl
= NULL
;
1297 std::vector
<Bstatement
*> init_stmts
;
1298 std::vector
<Bstatement
*> var_init_stmts
;
1300 if (this->is_main_package())
1301 this->init_imports(init_stmts
);
1303 // A list of variable initializations.
1304 Var_inits var_inits
;
1306 // A list of variables which need to be registered with the garbage
1308 size_t count_definitions
= bindings
->size_definitions();
1309 std::vector
<Named_object
*> var_gc
;
1310 var_gc
.reserve(count_definitions
);
1312 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1313 p
!= bindings
->end_definitions();
1316 Named_object
* no
= *p
;
1317 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1319 // There is nothing to do for a package.
1320 if (no
->is_package())
1323 // There is nothing to do for an object which was imported from
1324 // a different package into the global scope.
1325 if (no
->package() != NULL
)
1328 // Skip blank named functions and constants.
1329 if ((no
->is_function() && no
->func_value()->is_sink())
1330 || (no
->is_const() && no
->const_value()->is_sink()))
1333 // There is nothing useful we can output for constants which
1334 // have ideal or non-integral type.
1337 Type
* type
= no
->const_value()->type();
1339 type
= no
->const_value()->expr()->type();
1340 if (type
->is_abstract() || !type
->is_numeric_type())
1344 if (!no
->is_variable())
1345 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1348 Variable
* var
= no
->var_value();
1349 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1350 var_decls
.push_back(bvar
);
1352 // Check for a sink variable, which may be used to run an
1353 // initializer purely for its side effects.
1354 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1356 Bstatement
* var_init_stmt
= NULL
;
1357 if (!var
->has_pre_init())
1359 // If the backend representation of the variable initializer is
1360 // constant, we can just set the initial value using
1361 // global_var_set_init instead of during the init() function.
1362 // The initializer is constant if it is the zero-value of the
1363 // variable's type or if the initial value is an immutable value
1364 // that is not copied to the heap.
1365 bool is_constant_initializer
= false;
1366 if (var
->init() == NULL
)
1367 is_constant_initializer
= true;
1370 Type
* var_type
= var
->type();
1371 Expression
* init
= var
->init();
1372 Expression
* init_cast
=
1373 Expression::make_cast(var_type
, init
, var
->location());
1374 is_constant_initializer
=
1375 init_cast
->is_immutable() && !var_type
->has_pointer();
1378 // Non-constant variable initializations might need to create
1379 // temporary variables, which will need the initialization
1380 // function as context.
1381 if (!is_constant_initializer
&& init_fndecl
== NULL
)
1382 init_fndecl
= this->initialization_function_decl();
1383 Bexpression
* var_binit
= var
->get_init(this, init_fndecl
);
1385 if (var_binit
== NULL
)
1387 else if (is_constant_initializer
)
1389 if (expression_requires(var
->init(), NULL
,
1390 this->var_depends_on(var
), no
))
1391 error_at(no
->location(),
1392 "initialization expression for %qs depends "
1394 no
->message_name().c_str());
1395 this->backend()->global_variable_set_init(bvar
, var_binit
);
1399 this->backend()->expression_statement(var_binit
);
1402 Location loc
= var
->location();
1403 Bexpression
* var_expr
=
1404 this->backend()->var_expression(bvar
, loc
);
1406 this->backend()->assignment_statement(var_expr
, var_binit
,
1412 // We are going to create temporary variables which
1413 // means that we need an fndecl.
1414 if (init_fndecl
== NULL
)
1415 init_fndecl
= this->initialization_function_decl();
1417 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1418 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1421 if (var_init_stmt
!= NULL
)
1423 if (var
->init() == NULL
&& !var
->has_pre_init())
1424 var_init_stmts
.push_back(var_init_stmt
);
1426 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1428 else if (this->var_depends_on(var
) != NULL
)
1430 // This variable is initialized from something that is
1431 // not in its init or preinit. This variable needs to
1432 // participate in dependency analysis sorting, in case
1433 // some other variable depends on this one.
1434 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1435 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1436 Bstatement
* zero_stmt
=
1437 this->backend()->expression_statement(zero
);
1438 var_inits
.push_back(Var_init(no
, zero_stmt
));
1441 if (!is_sink
&& var
->type()->has_pointer())
1442 var_gc
.push_back(no
);
1446 // Register global variables with the garbage collector.
1447 this->register_gc_vars(var_gc
, init_stmts
);
1449 // Simple variable initializations, after all variables are
1451 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1453 // Complete variable initializations, first sorting them into a
1455 if (!var_inits
.empty())
1457 sort_var_inits(this, &var_inits
);
1458 for (Var_inits::const_iterator p
= var_inits
.begin();
1459 p
!= var_inits
.end();
1461 init_stmts
.push_back(p
->init());
1464 // After all the variables are initialized, call the init
1465 // functions if there are any. Init functions take no arguments, so
1466 // we pass in EMPTY_ARGS to call them.
1467 std::vector
<Bexpression
*> empty_args
;
1468 for (std::vector
<Named_object
*>::const_iterator p
=
1469 this->init_functions_
.begin();
1470 p
!= this->init_functions_
.end();
1473 Location func_loc
= (*p
)->location();
1474 Function
* func
= (*p
)->func_value();
1475 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1476 Bexpression
* func_code
=
1477 this->backend()->function_code_expression(initfn
, func_loc
);
1478 Bexpression
* call
= this->backend()->call_expression(func_code
,
1481 init_stmts
.push_back(this->backend()->expression_statement(call
));
1484 // Set up a magic function to do all the initialization actions.
1485 // This will be called if this package is imported.
1486 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1487 if (this->need_init_fn_
|| this->is_main_package())
1490 this->create_initialization_function(init_fndecl
, init_fncode
);
1491 if (init_fndecl
!= NULL
)
1492 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1495 // We should not have seen any new bindings created during the conversion.
1496 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1498 // Define all globally declared values.
1500 this->backend()->write_global_definitions(type_decls
, const_decls
,
1501 func_decls
, var_decls
);
1504 // Return the current block.
1507 Gogo::current_block()
1509 if (this->functions_
.empty())
1512 return this->functions_
.back().blocks
.back();
1515 // Look up a name in the current binding contour. If PFUNCTION is not
1516 // NULL, set it to the function in which the name is defined, or NULL
1517 // if the name is defined in global scope.
1520 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1522 if (pfunction
!= NULL
)
1525 if (Gogo::is_sink_name(name
))
1526 return Named_object::make_sink();
1528 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1529 p
!= this->functions_
.rend();
1532 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1535 if (pfunction
!= NULL
)
1536 *pfunction
= p
->function
;
1541 if (this->package_
!= NULL
)
1543 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1546 if (ret
->package() != NULL
)
1547 ret
->package()->note_usage();
1552 // We do not look in the global namespace. If we did, the global
1553 // namespace would effectively hide names which were defined in
1554 // package scope which we have not yet seen. Instead,
1555 // define_global_names is called after parsing is over to connect
1556 // undefined names at package scope with names defined at global
1562 // Look up a name in the current block, without searching enclosing
1566 Gogo::lookup_in_block(const std::string
& name
) const
1568 go_assert(!this->functions_
.empty());
1569 go_assert(!this->functions_
.back().blocks
.empty());
1570 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1573 // Look up a name in the global namespace.
1576 Gogo::lookup_global(const char* name
) const
1578 return this->globals_
->lookup(name
);
1581 // Add an imported package.
1584 Gogo::add_imported_package(const std::string
& real_name
,
1585 const std::string
& alias_arg
,
1586 bool is_alias_exported
,
1587 const std::string
& pkgpath
,
1588 const std::string
& pkgpath_symbol
,
1590 bool* padd_to_globals
)
1592 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1593 ret
->set_package_name(real_name
, location
);
1595 *padd_to_globals
= false;
1597 if (alias_arg
== ".")
1598 *padd_to_globals
= true;
1599 else if (alias_arg
== "_")
1600 ret
->set_uses_sink_alias();
1603 std::string alias
= alias_arg
;
1607 is_alias_exported
= Lex::is_exported_name(alias
);
1609 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1610 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1611 if (!no
->is_package())
1618 // Register a package. This package may or may not be imported. This
1619 // returns the Package structure for the package, creating if it
1620 // necessary. LOCATION is the location of the import statement that
1621 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1622 // for names in the package; it may be the empty string, in which case
1623 // we either get it later or make a guess when we need it.
1626 Gogo::register_package(const std::string
& pkgpath
,
1627 const std::string
& pkgpath_symbol
, Location location
)
1629 Package
* package
= NULL
;
1630 std::pair
<Packages::iterator
, bool> ins
=
1631 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1634 // We have seen this package name before.
1635 package
= ins
.first
->second
;
1636 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1637 if (!pkgpath_symbol
.empty())
1638 package
->set_pkgpath_symbol(pkgpath_symbol
);
1639 if (Linemap::is_unknown_location(package
->location()))
1640 package
->set_location(location
);
1644 // First time we have seen this package name.
1645 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1646 go_assert(ins
.first
->second
== NULL
);
1647 ins
.first
->second
= package
;
1653 // Start compiling a function.
1656 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1657 bool add_method_to_type
, Location location
)
1659 bool at_top_level
= this->functions_
.empty();
1661 Block
* block
= new Block(NULL
, location
);
1663 Named_object
* enclosing
= (at_top_level
1665 : this->functions_
.back().function
);
1667 Function
* function
= new Function(type
, enclosing
, block
, location
);
1669 if (type
->is_method())
1671 const Typed_identifier
* receiver
= type
->receiver();
1672 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1673 true, true, location
);
1674 std::string rname
= receiver
->name();
1675 if (rname
.empty() || Gogo::is_sink_name(rname
))
1677 // We need to give receivers a name since they wind up in
1678 // DECL_ARGUMENTS. FIXME.
1679 static unsigned int count
;
1681 snprintf(buf
, sizeof buf
, "r.%u", count
);
1685 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1688 const Typed_identifier_list
* parameters
= type
->parameters();
1689 bool is_varargs
= type
->is_varargs();
1690 if (parameters
!= NULL
)
1692 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1693 p
!= parameters
->end();
1696 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1698 if (is_varargs
&& p
+ 1 == parameters
->end())
1699 param
->set_is_varargs_parameter();
1701 std::string pname
= p
->name();
1702 if (pname
.empty() || Gogo::is_sink_name(pname
))
1704 // We need to give parameters a name since they wind up
1705 // in DECL_ARGUMENTS. FIXME.
1706 static unsigned int count
;
1708 snprintf(buf
, sizeof buf
, "p.%u", count
);
1712 block
->bindings()->add_variable(pname
, NULL
, param
);
1716 function
->create_result_variables(this);
1718 const std::string
* pname
;
1719 std::string nested_name
;
1720 bool is_init
= false;
1721 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1723 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1724 || (type
->results() != NULL
&& !type
->results()->empty()))
1726 "func init must have no arguments and no return values");
1727 // There can be multiple "init" functions, so give them each a
1729 static int init_count
;
1731 snprintf(buf
, sizeof buf
, ".$init%d", init_count
);
1734 pname
= &nested_name
;
1737 else if (!name
.empty())
1741 // Invent a name for a nested function.
1742 static int nested_count
;
1744 snprintf(buf
, sizeof buf
, ".$nested%d", nested_count
);
1747 pname
= &nested_name
;
1751 if (Gogo::is_sink_name(*pname
))
1753 static int sink_count
;
1755 snprintf(buf
, sizeof buf
, ".$sink%d", sink_count
);
1757 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1758 ret
->func_value()->set_is_sink();
1760 else if (!type
->is_method())
1762 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1763 if (!ret
->is_function() || ret
->func_value() != function
)
1765 // Redefinition error. Invent a name to avoid knockon
1767 static int redefinition_count
;
1769 snprintf(buf
, sizeof buf
, ".$redefined%d", redefinition_count
);
1770 ++redefinition_count
;
1771 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1776 if (!add_method_to_type
)
1777 ret
= Named_object::make_function(name
, NULL
, function
);
1780 go_assert(at_top_level
);
1781 Type
* rtype
= type
->receiver()->type();
1783 // We want to look through the pointer created by the
1784 // parser, without getting an error if the type is not yet
1786 if (rtype
->classification() == Type::TYPE_POINTER
)
1787 rtype
= rtype
->points_to();
1789 if (rtype
->is_error_type())
1790 ret
= Named_object::make_function(name
, NULL
, function
);
1791 else if (rtype
->named_type() != NULL
)
1793 ret
= rtype
->named_type()->add_method(name
, function
);
1794 if (!ret
->is_function())
1796 // Redefinition error.
1797 ret
= Named_object::make_function(name
, NULL
, function
);
1800 else if (rtype
->forward_declaration_type() != NULL
)
1802 Named_object
* type_no
=
1803 rtype
->forward_declaration_type()->named_object();
1804 if (type_no
->is_unknown())
1806 // If we are seeing methods it really must be a
1807 // type. Declare it as such. An alternative would
1808 // be to support lists of methods for unknown
1809 // expressions. Either way the error messages if
1810 // this is not a type are going to get confusing.
1811 Named_object
* declared
=
1812 this->declare_package_type(type_no
->name(),
1813 type_no
->location());
1815 == type_no
->unknown_value()->real_named_object());
1817 ret
= rtype
->forward_declaration_type()->add_method(name
,
1823 this->package_
->bindings()->add_method(ret
);
1826 this->functions_
.resize(this->functions_
.size() + 1);
1827 Open_function
& of(this->functions_
.back());
1829 of
.blocks
.push_back(block
);
1833 this->init_functions_
.push_back(ret
);
1834 this->need_init_fn_
= true;
1840 // Finish compiling a function.
1843 Gogo::finish_function(Location location
)
1845 this->finish_block(location
);
1846 go_assert(this->functions_
.back().blocks
.empty());
1847 this->functions_
.pop_back();
1850 // Return the current function.
1853 Gogo::current_function() const
1855 go_assert(!this->functions_
.empty());
1856 return this->functions_
.back().function
;
1859 // Start a new block.
1862 Gogo::start_block(Location location
)
1864 go_assert(!this->functions_
.empty());
1865 Block
* block
= new Block(this->current_block(), location
);
1866 this->functions_
.back().blocks
.push_back(block
);
1872 Gogo::finish_block(Location location
)
1874 go_assert(!this->functions_
.empty());
1875 go_assert(!this->functions_
.back().blocks
.empty());
1876 Block
* block
= this->functions_
.back().blocks
.back();
1877 this->functions_
.back().blocks
.pop_back();
1878 block
->set_end_location(location
);
1882 // Add an erroneous name.
1885 Gogo::add_erroneous_name(const std::string
& name
)
1887 return this->package_
->bindings()->add_erroneous_name(name
);
1890 // Add an unknown name.
1893 Gogo::add_unknown_name(const std::string
& name
, Location location
)
1895 return this->package_
->bindings()->add_unknown_name(name
, location
);
1898 // Declare a function.
1901 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
1904 if (!type
->is_method())
1905 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
1909 // We don't bother to add this to the list of global
1911 Type
* rtype
= type
->receiver()->type();
1913 // We want to look through the pointer created by the
1914 // parser, without getting an error if the type is not yet
1916 if (rtype
->classification() == Type::TYPE_POINTER
)
1917 rtype
= rtype
->points_to();
1919 if (rtype
->is_error_type())
1921 else if (rtype
->named_type() != NULL
)
1922 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
1924 else if (rtype
->forward_declaration_type() != NULL
)
1926 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
1927 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
1934 // Add a label definition.
1937 Gogo::add_label_definition(const std::string
& label_name
,
1940 go_assert(!this->functions_
.empty());
1941 Function
* func
= this->functions_
.back().function
->func_value();
1942 Label
* label
= func
->add_label_definition(this, label_name
, location
);
1943 this->add_statement(Statement::make_label_statement(label
, location
));
1947 // Add a label reference.
1950 Gogo::add_label_reference(const std::string
& label_name
,
1951 Location location
, bool issue_goto_errors
)
1953 go_assert(!this->functions_
.empty());
1954 Function
* func
= this->functions_
.back().function
->func_value();
1955 return func
->add_label_reference(this, label_name
, location
,
1959 // Add a function to the call graph.
1962 Gogo::add_call_node(Named_object
* function
)
1964 Node
* call
= this->lookup_call_node(function
);
1967 call
= Node::make_call(function
);
1968 this->call_graph_
.insert(call
);
1969 this->named_call_nodes_
[function
] = call
;
1974 // Find the call node that represents FUNCTION. Return NULL if it does not
1978 Gogo::lookup_call_node(Named_object
* function
) const
1980 Named_escape_nodes::const_iterator p
= this->named_call_nodes_
.find(function
);
1981 if (p
== this->named_call_nodes_
.end())
1986 // Add a connection node for OBJECT.
1989 Gogo::add_connection_node(Named_object
* object
)
1991 Node
* connection
= this->lookup_connection_node(object
);
1992 if (connection
== NULL
)
1994 connection
= Node::make_connection(object
, Node::ESCAPE_NONE
);
1996 // Each global variable is a part of the global connection graph.
1997 if (object
->is_variable()
1998 && object
->var_value()->is_global())
2000 connection
->connection_node()->set_escape_state(Node::ESCAPE_GLOBAL
);
2001 this->global_connections_
.insert(connection
);
2004 // Each function declaration or definition is the root of its own
2005 // connection graph. This means closures will have their own
2006 // connection graph that objects in the enclosing function might
2008 if (object
->is_function() || object
->is_function_declaration())
2009 this->connection_roots_
.insert(connection
);
2010 this->named_connection_nodes_
[object
] = connection
;
2015 // Find the connection node for OBJECT. Return NULL if it does not exist.
2018 Gogo::lookup_connection_node(Named_object
* object
) const
2020 Named_escape_nodes::const_iterator p
=
2021 this->named_connection_nodes_
.find(object
);
2022 if (p
== this->named_connection_nodes_
.end())
2027 // Return the current binding state.
2030 Gogo::bindings_snapshot(Location location
)
2032 return new Bindings_snapshot(this->current_block(), location
);
2038 Gogo::add_statement(Statement
* statement
)
2040 go_assert(!this->functions_
.empty()
2041 && !this->functions_
.back().blocks
.empty());
2042 this->functions_
.back().blocks
.back()->add_statement(statement
);
2048 Gogo::add_block(Block
* block
, Location location
)
2050 go_assert(!this->functions_
.empty()
2051 && !this->functions_
.back().blocks
.empty());
2052 Statement
* statement
= Statement::make_block_statement(block
, location
);
2053 this->functions_
.back().blocks
.back()->add_statement(statement
);
2059 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2062 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2068 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2070 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2072 if (!this->in_global_scope() && no
->is_type())
2074 Named_object
* f
= this->functions_
.back().function
;
2076 if (f
->is_function())
2077 index
= f
->func_value()->new_local_type_index();
2080 no
->type_value()->set_in_function(f
, index
);
2084 // Add a named type.
2087 Gogo::add_named_type(Named_type
* type
)
2089 go_assert(this->in_global_scope());
2090 this->current_bindings()->add_named_type(type
);
2096 Gogo::declare_type(const std::string
& name
, Location location
)
2098 Bindings
* bindings
= this->current_bindings();
2099 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2100 if (!this->in_global_scope() && no
->is_type_declaration())
2102 Named_object
* f
= this->functions_
.back().function
;
2104 if (f
->is_function())
2105 index
= f
->func_value()->new_local_type_index();
2108 no
->type_declaration_value()->set_in_function(f
, index
);
2113 // Declare a type at the package level.
2116 Gogo::declare_package_type(const std::string
& name
, Location location
)
2118 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2121 // Declare a function at the package level.
2124 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2127 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2131 // Define a type which was already declared.
2134 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2136 this->current_bindings()->define_type(no
, type
);
2142 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2144 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2147 // In a function the middle-end wants to see a DECL_EXPR node.
2149 && no
->is_variable()
2150 && !no
->var_value()->is_parameter()
2151 && !this->functions_
.empty())
2152 this->add_statement(Statement::make_variable_declaration(no
));
2157 // Add a sink--a reference to the blank identifier _.
2162 return Named_object::make_sink();
2165 // Add a named object for a dot import.
2168 Gogo::add_dot_import_object(Named_object
* no
)
2170 // If the name already exists, then it was defined in some file seen
2171 // earlier. If the earlier name is just a declaration, don't add
2172 // this name, because that will cause the previous declaration to
2173 // merge to this imported name, which should not happen. Just add
2174 // this name to the list of file block names to get appropriate
2175 // errors if we see a later definition.
2176 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2177 if (e
!= NULL
&& e
->package() == NULL
)
2179 if (e
->is_unknown())
2181 if (e
->package() == NULL
2182 && (e
->is_type_declaration()
2183 || e
->is_function_declaration()
2184 || e
->is_unknown()))
2186 this->add_file_block_name(no
->name(), no
->location());
2191 this->current_bindings()->add_named_object(no
);
2194 // Mark all local variables used. This is used when some types of
2195 // parse error occur.
2198 Gogo::mark_locals_used()
2200 for (Open_functions::iterator pf
= this->functions_
.begin();
2201 pf
!= this->functions_
.end();
2204 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2205 pb
!= pf
->blocks
.end();
2207 (*pb
)->bindings()->mark_locals_used();
2211 // Record that we've seen an interface type.
2214 Gogo::record_interface_type(Interface_type
* itype
)
2216 this->interface_types_
.push_back(itype
);
2219 // Return an erroneous name that indicates that an error has already
2223 Gogo::erroneous_name()
2225 static int erroneous_count
;
2227 snprintf(name
, sizeof name
, "$erroneous%d", erroneous_count
);
2232 // Return whether a name is an erroneous name.
2235 Gogo::is_erroneous_name(const std::string
& name
)
2237 return name
.compare(0, 10, "$erroneous") == 0;
2240 // Return a name for a thunk object.
2245 static int thunk_count
;
2246 char thunk_name
[50];
2247 snprintf(thunk_name
, sizeof thunk_name
, "$thunk%d", thunk_count
);
2252 // Return whether a function is a thunk.
2255 Gogo::is_thunk(const Named_object
* no
)
2257 return no
->name().compare(0, 6, "$thunk") == 0;
2260 // Define the global names. We do this only after parsing all the
2261 // input files, because the program might define the global names
2265 Gogo::define_global_names()
2267 for (Bindings::const_declarations_iterator p
=
2268 this->globals_
->begin_declarations();
2269 p
!= this->globals_
->end_declarations();
2272 Named_object
* global_no
= p
->second
;
2273 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2274 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2278 if (no
->is_type_declaration())
2280 if (global_no
->is_type())
2282 if (no
->type_declaration_value()->has_methods())
2283 error_at(no
->location(),
2284 "may not define methods for global type");
2285 no
->set_type_value(global_no
->type_value());
2289 error_at(no
->location(), "expected type");
2290 Type
* errtype
= Type::make_error_type();
2292 Named_object::make_type("erroneous_type", NULL
, errtype
,
2293 Linemap::predeclared_location());
2294 no
->set_type_value(err
->type_value());
2297 else if (no
->is_unknown())
2298 no
->unknown_value()->set_real_named_object(global_no
);
2301 // Give an error if any name is defined in both the package block
2302 // and the file block. For example, this can happen if one file
2303 // imports "fmt" and another file defines a global variable fmt.
2304 for (Bindings::const_declarations_iterator p
=
2305 this->package_
->bindings()->begin_declarations();
2306 p
!= this->package_
->bindings()->end_declarations();
2309 if (p
->second
->is_unknown()
2310 && p
->second
->unknown_value()->real_named_object() == NULL
)
2312 // No point in warning about an undefined name, as we will
2313 // get other errors later anyhow.
2316 File_block_names::const_iterator pf
=
2317 this->file_block_names_
.find(p
->second
->name());
2318 if (pf
!= this->file_block_names_
.end())
2320 std::string n
= p
->second
->message_name();
2321 error_at(p
->second
->location(),
2322 "%qs defined as both imported name and global name",
2324 inform(pf
->second
, "%qs imported here", n
.c_str());
2327 // No package scope identifier may be named "init".
2328 if (!p
->second
->is_function()
2329 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2331 error_at(p
->second
->location(),
2332 "cannot declare init - must be func");
2337 // Clear out names in file scope.
2340 Gogo::clear_file_scope()
2342 this->package_
->bindings()->clear_file_scope(this);
2344 // Warn about packages which were imported but not used.
2345 bool quiet
= saw_errors();
2346 for (Packages::iterator p
= this->packages_
.begin();
2347 p
!= this->packages_
.end();
2350 Package
* package
= p
->second
;
2351 if (package
!= this->package_
2352 && package
->is_imported()
2354 && !package
->uses_sink_alias()
2356 error_at(package
->location(), "imported and not used: %s",
2357 Gogo::message_name(package
->package_name()).c_str());
2358 package
->clear_is_imported();
2359 package
->clear_uses_sink_alias();
2360 package
->clear_used();
2364 // Queue up a type specific function for later writing. These are
2365 // written out in write_specific_type_functions, called after the
2366 // parse tree is lowered.
2369 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
,
2370 const std::string
& hash_name
,
2371 Function_type
* hash_fntype
,
2372 const std::string
& equal_name
,
2373 Function_type
* equal_fntype
)
2375 go_assert(!this->specific_type_functions_are_written_
);
2376 go_assert(!this->in_global_scope());
2377 Specific_type_function
* tsf
= new Specific_type_function(type
, name
,
2382 this->specific_type_functions_
.push_back(tsf
);
2385 // Look for types which need specific hash or equality functions.
2387 class Specific_type_functions
: public Traverse
2390 Specific_type_functions(Gogo
* gogo
)
2391 : Traverse(traverse_types
),
2403 Specific_type_functions::type(Type
* t
)
2405 Named_object
* hash_fn
;
2406 Named_object
* equal_fn
;
2407 switch (t
->classification())
2409 case Type::TYPE_NAMED
:
2411 Named_type
* nt
= t
->named_type();
2412 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2413 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2415 // If this is a struct type, we don't want to make functions
2416 // for the unnamed struct.
2417 Type
* rt
= nt
->real_type();
2418 if (rt
->struct_type() == NULL
)
2420 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2421 return TRAVERSE_EXIT
;
2425 // If this type is defined in another package, then we don't
2426 // need to worry about the unexported fields.
2427 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2428 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2429 for (Struct_field_list::const_iterator p
= fields
->begin();
2433 if (is_defined_elsewhere
2434 && Gogo::is_hidden_name(p
->field_name()))
2436 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2437 return TRAVERSE_EXIT
;
2441 return TRAVERSE_SKIP_COMPONENTS
;
2444 case Type::TYPE_STRUCT
:
2445 case Type::TYPE_ARRAY
:
2446 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2447 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2454 return TRAVERSE_CONTINUE
;
2457 // Write out type specific functions.
2460 Gogo::write_specific_type_functions()
2462 Specific_type_functions
stf(this);
2463 this->traverse(&stf
);
2465 while (!this->specific_type_functions_
.empty())
2467 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2468 this->specific_type_functions_
.pop_back();
2469 tsf
->type
->write_specific_type_functions(this, tsf
->name
,
2476 this->specific_type_functions_are_written_
= true;
2479 // Traverse the tree.
2482 Gogo::traverse(Traverse
* traverse
)
2484 // Traverse the current package first for consistency. The other
2485 // packages will only contain imported types, constants, and
2487 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2489 for (Packages::const_iterator p
= this->packages_
.begin();
2490 p
!= this->packages_
.end();
2493 if (p
->second
!= this->package_
)
2495 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2501 // Add a type to verify. This is used for types of sink variables, in
2502 // order to give appropriate error messages.
2505 Gogo::add_type_to_verify(Type
* type
)
2507 this->verify_types_
.push_back(type
);
2510 // Traversal class used to verify types.
2512 class Verify_types
: public Traverse
2516 : Traverse(traverse_types
)
2523 // Verify that a type is correct.
2526 Verify_types::type(Type
* t
)
2529 return TRAVERSE_SKIP_COMPONENTS
;
2530 return TRAVERSE_CONTINUE
;
2533 // Verify that all types are correct.
2536 Gogo::verify_types()
2538 Verify_types traverse
;
2539 this->traverse(&traverse
);
2541 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2542 p
!= this->verify_types_
.end();
2545 this->verify_types_
.clear();
2548 // Traversal class used to lower parse tree.
2550 class Lower_parse_tree
: public Traverse
2553 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2554 : Traverse(traverse_variables
2555 | traverse_constants
2556 | traverse_functions
2557 | traverse_statements
2558 | traverse_expressions
),
2559 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2563 set_inserter(const Statement_inserter
* inserter
)
2564 { this->inserter_
= *inserter
; }
2567 variable(Named_object
*);
2570 constant(Named_object
*, bool);
2573 function(Named_object
*);
2576 statement(Block
*, size_t* pindex
, Statement
*);
2579 expression(Expression
**);
2584 // The function we are traversing.
2585 Named_object
* function_
;
2586 // Value to use for the predeclared constant iota.
2588 // Current statement inserter for use by expressions.
2589 Statement_inserter inserter_
;
2595 Lower_parse_tree::variable(Named_object
* no
)
2597 if (!no
->is_variable())
2598 return TRAVERSE_CONTINUE
;
2600 if (no
->is_variable() && no
->var_value()->is_global())
2602 // Global variables can have loops in their initialization
2603 // expressions. This is handled in lower_init_expression.
2604 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2606 return TRAVERSE_CONTINUE
;
2609 // This is a local variable. We are going to return
2610 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2611 // initialization expression when we reach the variable declaration
2612 // statement. However, that means that we need to traverse the type
2614 if (no
->var_value()->has_type())
2616 Type
* type
= no
->var_value()->type();
2619 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2620 return TRAVERSE_EXIT
;
2623 go_assert(!no
->var_value()->has_pre_init());
2625 return TRAVERSE_SKIP_COMPONENTS
;
2628 // Lower constants. We handle constants specially so that we can set
2629 // the right value for the predeclared constant iota. This works in
2630 // conjunction with the way we lower Const_expression objects.
2633 Lower_parse_tree::constant(Named_object
* no
, bool)
2635 Named_constant
* nc
= no
->const_value();
2637 // Don't get into trouble if the constant's initializer expression
2638 // refers to the constant itself.
2640 return TRAVERSE_CONTINUE
;
2643 go_assert(this->iota_value_
== -1);
2644 this->iota_value_
= nc
->iota_value();
2645 nc
->traverse_expression(this);
2646 this->iota_value_
= -1;
2648 nc
->clear_lowering();
2650 // We will traverse the expression a second time, but that will be
2653 return TRAVERSE_CONTINUE
;
2656 // Lower the body of a function, and set the closure type. Record the
2657 // function while lowering it, so that we can pass it down when
2658 // lowering an expression.
2661 Lower_parse_tree::function(Named_object
* no
)
2663 no
->func_value()->set_closure_type();
2665 go_assert(this->function_
== NULL
);
2666 this->function_
= no
;
2667 int t
= no
->func_value()->traverse(this);
2668 this->function_
= NULL
;
2670 if (t
== TRAVERSE_EXIT
)
2672 return TRAVERSE_SKIP_COMPONENTS
;
2675 // Lower statement parse trees.
2678 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2680 // Because we explicitly traverse the statement's contents
2681 // ourselves, we want to skip block statements here. There is
2682 // nothing to lower in a block statement.
2683 if (sorig
->is_block_statement())
2684 return TRAVERSE_CONTINUE
;
2686 Statement_inserter
hold_inserter(this->inserter_
);
2687 this->inserter_
= Statement_inserter(block
, pindex
);
2689 // Lower the expressions first.
2690 int t
= sorig
->traverse_contents(this);
2691 if (t
== TRAVERSE_EXIT
)
2693 this->inserter_
= hold_inserter
;
2697 // Keep lowering until nothing changes.
2698 Statement
* s
= sorig
;
2701 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2706 t
= s
->traverse_contents(this);
2707 if (t
== TRAVERSE_EXIT
)
2709 this->inserter_
= hold_inserter
;
2715 block
->replace_statement(*pindex
, s
);
2717 this->inserter_
= hold_inserter
;
2718 return TRAVERSE_SKIP_COMPONENTS
;
2721 // Lower expression parse trees.
2724 Lower_parse_tree::expression(Expression
** pexpr
)
2726 // We have to lower all subexpressions first, so that we can get
2727 // their type if necessary. This is awkward, because we don't have
2728 // a postorder traversal pass.
2729 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2730 return TRAVERSE_EXIT
;
2731 // Keep lowering until nothing changes.
2734 Expression
* e
= *pexpr
;
2735 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2736 &this->inserter_
, this->iota_value_
);
2739 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2740 return TRAVERSE_EXIT
;
2743 return TRAVERSE_SKIP_COMPONENTS
;
2746 // Lower the parse tree. This is called after the parse is complete,
2747 // when all names should be resolved.
2750 Gogo::lower_parse_tree()
2752 Lower_parse_tree
lower_parse_tree(this, NULL
);
2753 this->traverse(&lower_parse_tree
);
2759 Gogo::lower_block(Named_object
* function
, Block
* block
)
2761 Lower_parse_tree
lower_parse_tree(this, function
);
2762 block
->traverse(&lower_parse_tree
);
2765 // Lower an expression. INSERTER may be NULL, in which case the
2766 // expression had better not need to create any temporaries.
2769 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2772 Lower_parse_tree
lower_parse_tree(this, function
);
2773 if (inserter
!= NULL
)
2774 lower_parse_tree
.set_inserter(inserter
);
2775 lower_parse_tree
.expression(pexpr
);
2778 // Lower a constant. This is called when lowering a reference to a
2779 // constant. We have to make sure that the constant has already been
2783 Gogo::lower_constant(Named_object
* no
)
2785 go_assert(no
->is_const());
2786 Lower_parse_tree
lower(this, NULL
);
2787 lower
.constant(no
, false);
2790 // Traverse the tree to create function descriptors as needed.
2792 class Create_function_descriptors
: public Traverse
2795 Create_function_descriptors(Gogo
* gogo
)
2796 : Traverse(traverse_functions
| traverse_expressions
),
2801 function(Named_object
*);
2804 expression(Expression
**);
2810 // Create a descriptor for every top-level exported function.
2813 Create_function_descriptors::function(Named_object
* no
)
2815 if (no
->is_function()
2816 && no
->func_value()->enclosing() == NULL
2817 && !no
->func_value()->is_method()
2818 && !Gogo::is_hidden_name(no
->name())
2819 && !Gogo::is_thunk(no
))
2820 no
->func_value()->descriptor(this->gogo_
, no
);
2822 return TRAVERSE_CONTINUE
;
2825 // If we see a function referenced in any way other than calling it,
2826 // create a descriptor for it.
2829 Create_function_descriptors::expression(Expression
** pexpr
)
2831 Expression
* expr
= *pexpr
;
2833 Func_expression
* fe
= expr
->func_expression();
2836 // We would not get here for a call to this function, so this is
2837 // a reference to a function other than calling it. We need a
2839 if (fe
->closure() != NULL
)
2840 return TRAVERSE_CONTINUE
;
2841 Named_object
* no
= fe
->named_object();
2842 if (no
->is_function() && !no
->func_value()->is_method())
2843 no
->func_value()->descriptor(this->gogo_
, no
);
2844 else if (no
->is_function_declaration()
2845 && !no
->func_declaration_value()->type()->is_method()
2846 && !Linemap::is_predeclared_location(no
->location()))
2847 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
2848 return TRAVERSE_CONTINUE
;
2851 Bound_method_expression
* bme
= expr
->bound_method_expression();
2854 // We would not get here for a call to this method, so this is a
2855 // method value. We need to create a thunk.
2856 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
2858 return TRAVERSE_CONTINUE
;
2861 Interface_field_reference_expression
* ifre
=
2862 expr
->interface_field_reference_expression();
2865 // We would not get here for a call to this interface method, so
2866 // this is a method value. We need to create a thunk.
2867 Interface_type
* type
= ifre
->expr()->type()->interface_type();
2869 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
2871 return TRAVERSE_CONTINUE
;
2874 Call_expression
* ce
= expr
->call_expression();
2877 Expression
* fn
= ce
->fn();
2878 if (fn
->func_expression() != NULL
2879 || fn
->bound_method_expression() != NULL
2880 || fn
->interface_field_reference_expression() != NULL
)
2882 // Traverse the arguments but not the function.
2883 Expression_list
* args
= ce
->args();
2886 if (args
->traverse(this) == TRAVERSE_EXIT
)
2887 return TRAVERSE_EXIT
;
2889 return TRAVERSE_SKIP_COMPONENTS
;
2893 return TRAVERSE_CONTINUE
;
2896 // Create function descriptors as needed. We need a function
2897 // descriptor for all exported functions and for all functions that
2898 // are referenced without being called.
2901 Gogo::create_function_descriptors()
2903 // Create a function descriptor for any exported function that is
2904 // declared in this package. This is so that we have a descriptor
2905 // for functions written in assembly. Gather the descriptors first
2906 // so that we don't add declarations while looping over them.
2907 std::vector
<Named_object
*> fndecls
;
2908 Bindings
* b
= this->package_
->bindings();
2909 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
2910 p
!= b
->end_declarations();
2913 Named_object
* no
= p
->second
;
2914 if (no
->is_function_declaration()
2915 && !no
->func_declaration_value()->type()->is_method()
2916 && !Linemap::is_predeclared_location(no
->location())
2917 && !Gogo::is_hidden_name(no
->name()))
2918 fndecls
.push_back(no
);
2920 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
2923 (*p
)->func_declaration_value()->descriptor(this, *p
);
2926 Create_function_descriptors
cfd(this);
2927 this->traverse(&cfd
);
2930 // Look for interface types to finalize methods of inherited
2933 class Finalize_methods
: public Traverse
2936 Finalize_methods(Gogo
* gogo
)
2937 : Traverse(traverse_types
),
2948 // Finalize the methods of an interface type.
2951 Finalize_methods::type(Type
* t
)
2953 // Check the classification so that we don't finalize the methods
2954 // twice for a named interface type.
2955 switch (t
->classification())
2957 case Type::TYPE_INTERFACE
:
2958 t
->interface_type()->finalize_methods();
2961 case Type::TYPE_NAMED
:
2963 // We have to finalize the methods of the real type first.
2964 // But if the real type is a struct type, then we only want to
2965 // finalize the methods of the field types, not of the struct
2966 // type itself. We don't want to add methods to the struct,
2967 // since it has a name.
2968 Named_type
* nt
= t
->named_type();
2969 Type
* rt
= nt
->real_type();
2970 if (rt
->classification() != Type::TYPE_STRUCT
)
2972 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2973 return TRAVERSE_EXIT
;
2977 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2978 return TRAVERSE_EXIT
;
2981 nt
->finalize_methods(this->gogo_
);
2983 // If this type is defined in a different package, then finalize the
2984 // types of all the methods, since we won't see them otherwise.
2985 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
2987 const Methods
* methods
= nt
->methods();
2988 for (Methods::const_iterator p
= methods
->begin();
2989 p
!= methods
->end();
2992 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
2993 return TRAVERSE_EXIT
;
2997 // Finalize the types of all methods that are declared but not
2998 // defined, since we won't see the declarations otherwise.
2999 if (nt
->named_object()->package() == NULL
3000 && nt
->local_methods() != NULL
)
3002 const Bindings
* methods
= nt
->local_methods();
3003 for (Bindings::const_declarations_iterator p
=
3004 methods
->begin_declarations();
3005 p
!= methods
->end_declarations();
3008 if (p
->second
->is_function_declaration())
3010 Type
* mt
= p
->second
->func_declaration_value()->type();
3011 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3012 return TRAVERSE_EXIT
;
3017 return TRAVERSE_SKIP_COMPONENTS
;
3020 case Type::TYPE_STRUCT
:
3021 // Traverse the field types first in case there is an embedded
3022 // field with methods that the struct should inherit.
3023 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3024 return TRAVERSE_EXIT
;
3025 t
->struct_type()->finalize_methods(this->gogo_
);
3026 return TRAVERSE_SKIP_COMPONENTS
;
3032 return TRAVERSE_CONTINUE
;
3035 // Finalize method lists and build stub methods for types.
3038 Gogo::finalize_methods()
3040 Finalize_methods
finalize(this);
3041 this->traverse(&finalize
);
3044 // Set types for unspecified variables and constants.
3047 Gogo::determine_types()
3049 Bindings
* bindings
= this->current_bindings();
3050 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3051 p
!= bindings
->end_definitions();
3054 if ((*p
)->is_function())
3055 (*p
)->func_value()->determine_types();
3056 else if ((*p
)->is_variable())
3057 (*p
)->var_value()->determine_type();
3058 else if ((*p
)->is_const())
3059 (*p
)->const_value()->determine_type();
3061 // See if a variable requires us to build an initialization
3062 // function. We know that we will see all global variables
3064 if (!this->need_init_fn_
&& (*p
)->is_variable())
3066 Variable
* variable
= (*p
)->var_value();
3068 // If this is a global variable which requires runtime
3069 // initialization, we need an initialization function.
3070 if (!variable
->is_global())
3072 else if (variable
->init() == NULL
)
3074 else if (variable
->type()->interface_type() != NULL
)
3075 this->need_init_fn_
= true;
3076 else if (variable
->init()->is_constant())
3078 else if (!variable
->init()->is_composite_literal())
3079 this->need_init_fn_
= true;
3080 else if (variable
->init()->is_nonconstant_composite_literal())
3081 this->need_init_fn_
= true;
3083 // If this is a global variable which holds a pointer value,
3084 // then we need an initialization function to register it as a
3086 if (variable
->is_global() && variable
->type()->has_pointer())
3087 this->need_init_fn_
= true;
3091 // Determine the types of constants in packages.
3092 for (Packages::const_iterator p
= this->packages_
.begin();
3093 p
!= this->packages_
.end();
3095 p
->second
->determine_types();
3098 // Traversal class used for type checking.
3100 class Check_types_traverse
: public Traverse
3103 Check_types_traverse(Gogo
* gogo
)
3104 : Traverse(traverse_variables
3105 | traverse_constants
3106 | traverse_functions
3107 | traverse_statements
3108 | traverse_expressions
),
3113 variable(Named_object
*);
3116 constant(Named_object
*, bool);
3119 function(Named_object
*);
3122 statement(Block
*, size_t* pindex
, Statement
*);
3125 expression(Expression
**);
3132 // Check that a variable initializer has the right type.
3135 Check_types_traverse::variable(Named_object
* named_object
)
3137 if (named_object
->is_variable())
3139 Variable
* var
= named_object
->var_value();
3141 // Give error if variable type is not defined.
3142 var
->type()->base();
3144 Expression
* init
= var
->init();
3147 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3150 error_at(var
->location(), "incompatible type in initialization");
3152 error_at(var
->location(),
3153 "incompatible type in initialization (%s)",
3157 else if (!var
->is_used()
3158 && !var
->is_global()
3159 && !var
->is_parameter()
3160 && !var
->is_receiver()
3161 && !var
->type()->is_error()
3162 && (init
== NULL
|| !init
->is_error_expression())
3163 && !Lex::is_invalid_identifier(named_object
->name()))
3164 error_at(var
->location(), "%qs declared and not used",
3165 named_object
->message_name().c_str());
3167 return TRAVERSE_CONTINUE
;
3170 // Check that a constant initializer has the right type.
3173 Check_types_traverse::constant(Named_object
* named_object
, bool)
3175 Named_constant
* constant
= named_object
->const_value();
3176 Type
* ctype
= constant
->type();
3177 if (ctype
->integer_type() == NULL
3178 && ctype
->float_type() == NULL
3179 && ctype
->complex_type() == NULL
3180 && !ctype
->is_boolean_type()
3181 && !ctype
->is_string_type())
3183 if (ctype
->is_nil_type())
3184 error_at(constant
->location(), "const initializer cannot be nil");
3185 else if (!ctype
->is_error())
3186 error_at(constant
->location(), "invalid constant type");
3187 constant
->set_error();
3189 else if (!constant
->expr()->is_constant())
3191 error_at(constant
->expr()->location(), "expression is not constant");
3192 constant
->set_error();
3194 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3197 error_at(constant
->location(),
3198 "initialization expression has wrong type");
3199 constant
->set_error();
3201 return TRAVERSE_CONTINUE
;
3204 // There are no types to check in a function, but this is where we
3205 // issue warnings about labels which are defined but not referenced.
3208 Check_types_traverse::function(Named_object
* no
)
3210 no
->func_value()->check_labels();
3211 return TRAVERSE_CONTINUE
;
3214 // Check that types are valid in a statement.
3217 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3219 s
->check_types(this->gogo_
);
3220 return TRAVERSE_CONTINUE
;
3223 // Check that types are valid in an expression.
3226 Check_types_traverse::expression(Expression
** expr
)
3228 (*expr
)->check_types(this->gogo_
);
3229 return TRAVERSE_CONTINUE
;
3232 // Check that types are valid.
3237 Check_types_traverse
traverse(this);
3238 this->traverse(&traverse
);
3241 // Check the types in a single block.
3244 Gogo::check_types_in_block(Block
* block
)
3246 Check_types_traverse
traverse(this);
3247 block
->traverse(&traverse
);
3250 // A traversal class used to find a single shortcut operator within an
3253 class Find_shortcut
: public Traverse
3257 : Traverse(traverse_blocks
3258 | traverse_statements
3259 | traverse_expressions
),
3263 // A pointer to the expression which was found, or NULL if none was
3267 { return this->found_
; }
3272 { return TRAVERSE_SKIP_COMPONENTS
; }
3275 statement(Block
*, size_t*, Statement
*)
3276 { return TRAVERSE_SKIP_COMPONENTS
; }
3279 expression(Expression
**);
3282 Expression
** found_
;
3285 // Find a shortcut expression.
3288 Find_shortcut::expression(Expression
** pexpr
)
3290 Expression
* expr
= *pexpr
;
3291 Binary_expression
* be
= expr
->binary_expression();
3293 return TRAVERSE_CONTINUE
;
3294 Operator op
= be
->op();
3295 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3296 return TRAVERSE_CONTINUE
;
3297 go_assert(this->found_
== NULL
);
3298 this->found_
= pexpr
;
3299 return TRAVERSE_EXIT
;
3302 // A traversal class used to turn shortcut operators into explicit if
3305 class Shortcuts
: public Traverse
3308 Shortcuts(Gogo
* gogo
)
3309 : Traverse(traverse_variables
3310 | traverse_statements
),
3316 variable(Named_object
*);
3319 statement(Block
*, size_t*, Statement
*);
3322 // Convert a shortcut operator.
3324 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3330 // Remove shortcut operators in a single statement.
3333 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3335 // FIXME: This approach doesn't work for switch statements, because
3336 // we add the new statements before the whole switch when we need to
3337 // instead add them just before the switch expression. The right
3338 // fix is probably to lower switch statements with nonconstant cases
3339 // to a series of conditionals.
3340 if (s
->switch_statement() != NULL
)
3341 return TRAVERSE_CONTINUE
;
3345 Find_shortcut find_shortcut
;
3347 // If S is a variable declaration, then ordinary traversal won't
3348 // do anything. We want to explicitly traverse the
3349 // initialization expression if there is one.
3350 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3351 Expression
* init
= NULL
;
3353 s
->traverse_contents(&find_shortcut
);
3356 init
= vds
->var()->var_value()->init();
3358 return TRAVERSE_CONTINUE
;
3359 init
->traverse(&init
, &find_shortcut
);
3361 Expression
** pshortcut
= find_shortcut
.found();
3362 if (pshortcut
== NULL
)
3363 return TRAVERSE_CONTINUE
;
3365 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3366 block
->insert_statement_before(*pindex
, snew
);
3369 if (pshortcut
== &init
)
3370 vds
->var()->var_value()->set_init(init
);
3374 // Remove shortcut operators in the initializer of a global variable.
3377 Shortcuts::variable(Named_object
* no
)
3379 if (no
->is_result_variable())
3380 return TRAVERSE_CONTINUE
;
3381 Variable
* var
= no
->var_value();
3382 Expression
* init
= var
->init();
3383 if (!var
->is_global() || init
== NULL
)
3384 return TRAVERSE_CONTINUE
;
3388 Find_shortcut find_shortcut
;
3389 init
->traverse(&init
, &find_shortcut
);
3390 Expression
** pshortcut
= find_shortcut
.found();
3391 if (pshortcut
== NULL
)
3392 return TRAVERSE_CONTINUE
;
3394 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3395 var
->add_preinit_statement(this->gogo_
, snew
);
3396 if (pshortcut
== &init
)
3397 var
->set_init(init
);
3401 // Given an expression which uses a shortcut operator, return a
3402 // statement which implements it, and update *PSHORTCUT accordingly.
3405 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3407 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3408 Expression
* left
= shortcut
->left();
3409 Expression
* right
= shortcut
->right();
3410 Location loc
= shortcut
->location();
3412 Block
* retblock
= new Block(enclosing
, loc
);
3413 retblock
->set_end_location(loc
);
3415 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3417 retblock
->add_statement(ts
);
3419 Block
* block
= new Block(retblock
, loc
);
3420 block
->set_end_location(loc
);
3421 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
3422 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
3423 block
->add_statement(assign
);
3425 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
3426 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
3427 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
3429 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
3431 retblock
->add_statement(if_statement
);
3433 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
3437 // Now convert any shortcut operators in LEFT and RIGHT.
3438 Shortcuts
shortcuts(this->gogo_
);
3439 retblock
->traverse(&shortcuts
);
3441 return Statement::make_block_statement(retblock
, loc
);
3444 // Turn shortcut operators into explicit if statements. Doing this
3445 // considerably simplifies the order of evaluation rules.
3448 Gogo::remove_shortcuts()
3450 Shortcuts
shortcuts(this);
3451 this->traverse(&shortcuts
);
3454 // A traversal class which finds all the expressions which must be
3455 // evaluated in order within a statement or larger expression. This
3456 // is used to implement the rules about order of evaluation.
3458 class Find_eval_ordering
: public Traverse
3461 typedef std::vector
<Expression
**> Expression_pointers
;
3464 Find_eval_ordering()
3465 : Traverse(traverse_blocks
3466 | traverse_statements
3467 | traverse_expressions
),
3473 { return this->exprs_
.size(); }
3475 typedef Expression_pointers::const_iterator const_iterator
;
3479 { return this->exprs_
.begin(); }
3483 { return this->exprs_
.end(); }
3488 { return TRAVERSE_SKIP_COMPONENTS
; }
3491 statement(Block
*, size_t*, Statement
*)
3492 { return TRAVERSE_SKIP_COMPONENTS
; }
3495 expression(Expression
**);
3498 // A list of pointers to expressions with side-effects.
3499 Expression_pointers exprs_
;
3502 // If an expression must be evaluated in order, put it on the list.
3505 Find_eval_ordering::expression(Expression
** expression_pointer
)
3507 // We have to look at subexpressions before this one.
3508 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3509 return TRAVERSE_EXIT
;
3510 if ((*expression_pointer
)->must_eval_in_order())
3511 this->exprs_
.push_back(expression_pointer
);
3512 return TRAVERSE_SKIP_COMPONENTS
;
3515 // A traversal class for ordering evaluations.
3517 class Order_eval
: public Traverse
3520 Order_eval(Gogo
* gogo
)
3521 : Traverse(traverse_variables
3522 | traverse_statements
),
3527 variable(Named_object
*);
3530 statement(Block
*, size_t*, Statement
*);
3537 // Implement the order of evaluation rules for a statement.
3540 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3542 // FIXME: This approach doesn't work for switch statements, because
3543 // we add the new statements before the whole switch when we need to
3544 // instead add them just before the switch expression. The right
3545 // fix is probably to lower switch statements with nonconstant cases
3546 // to a series of conditionals.
3547 if (s
->switch_statement() != NULL
)
3548 return TRAVERSE_CONTINUE
;
3550 Find_eval_ordering find_eval_ordering
;
3552 // If S is a variable declaration, then ordinary traversal won't do
3553 // anything. We want to explicitly traverse the initialization
3554 // expression if there is one.
3555 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3556 Expression
* init
= NULL
;
3557 Expression
* orig_init
= NULL
;
3559 s
->traverse_contents(&find_eval_ordering
);
3562 init
= vds
->var()->var_value()->init();
3564 return TRAVERSE_CONTINUE
;
3567 // It might seem that this could be
3568 // init->traverse_subexpressions. Unfortunately that can fail
3571 // newvar, err := call(arg())
3572 // Here newvar will have an init of call result 0 of
3573 // call(arg()). If we only traverse subexpressions, we will
3574 // only find arg(), and we won't bother to move anything out.
3575 // Then we get to the assignment to err, we will traverse the
3576 // whole statement, and this time we will find both call() and
3577 // arg(), and so we will move them out. This will cause them to
3578 // be put into temporary variables before the assignment to err
3579 // but after the declaration of newvar. To avoid that problem,
3580 // we traverse the entire expression here.
3581 Expression::traverse(&init
, &find_eval_ordering
);
3584 size_t c
= find_eval_ordering
.size();
3586 return TRAVERSE_CONTINUE
;
3588 // If there is only one expression with a side-effect, we can
3589 // usually leave it in place.
3592 switch (s
->classification())
3594 case Statement::STATEMENT_ASSIGNMENT
:
3595 // For an assignment statement, we need to evaluate an
3596 // expression on the right hand side before we evaluate any
3597 // index expression on the left hand side, so for that case
3598 // we always move the expression. Otherwise we mishandle
3599 // m[0] = len(m) where m is a map.
3602 case Statement::STATEMENT_EXPRESSION
:
3604 // If this is a call statement that doesn't return any
3605 // values, it will not have been counted as a value to
3606 // move. We need to move any subexpressions in case they
3607 // are themselves call statements that require passing a
3609 Expression
* expr
= s
->expression_statement()->expr();
3610 if (expr
->call_expression() != NULL
3611 && expr
->call_expression()->result_count() == 0)
3613 return TRAVERSE_CONTINUE
;
3617 // We can leave the expression in place.
3618 return TRAVERSE_CONTINUE
;
3622 bool is_thunk
= s
->thunk_statement() != NULL
;
3623 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3624 p
!= find_eval_ordering
.end();
3627 Expression
** pexpr
= *p
;
3629 // The last expression in a thunk will be the call passed to go
3630 // or defer, which we must not evaluate early.
3631 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3634 Location loc
= (*pexpr
)->location();
3636 if ((*pexpr
)->call_expression() == NULL
3637 || (*pexpr
)->call_expression()->result_count() < 2)
3639 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3642 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3646 // A call expression which returns multiple results needs to
3647 // be handled specially. We can't create a temporary
3648 // because there is no type to give it. Any actual uses of
3649 // the values will be done via Call_result_expressions.
3650 s
= Statement::make_statement(*pexpr
, true);
3653 block
->insert_statement_before(*pindex
, s
);
3657 if (init
!= orig_init
)
3658 vds
->var()->var_value()->set_init(init
);
3660 return TRAVERSE_CONTINUE
;
3663 // Implement the order of evaluation rules for the initializer of a
3667 Order_eval::variable(Named_object
* no
)
3669 if (no
->is_result_variable())
3670 return TRAVERSE_CONTINUE
;
3671 Variable
* var
= no
->var_value();
3672 Expression
* init
= var
->init();
3673 if (!var
->is_global() || init
== NULL
)
3674 return TRAVERSE_CONTINUE
;
3676 Find_eval_ordering find_eval_ordering
;
3677 Expression::traverse(&init
, &find_eval_ordering
);
3679 if (find_eval_ordering
.size() <= 1)
3681 // If there is only one expression with a side-effect, we can
3682 // leave it in place.
3683 return TRAVERSE_SKIP_COMPONENTS
;
3686 Expression
* orig_init
= init
;
3688 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3689 p
!= find_eval_ordering
.end();
3692 Expression
** pexpr
= *p
;
3693 Location loc
= (*pexpr
)->location();
3695 if ((*pexpr
)->call_expression() == NULL
3696 || (*pexpr
)->call_expression()->result_count() < 2)
3698 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3701 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3705 // A call expression which returns multiple results needs to
3706 // be handled specially.
3707 s
= Statement::make_statement(*pexpr
, true);
3709 var
->add_preinit_statement(this->gogo_
, s
);
3712 if (init
!= orig_init
)
3713 var
->set_init(init
);
3715 return TRAVERSE_SKIP_COMPONENTS
;
3718 // Use temporary variables to implement the order of evaluation rules.
3721 Gogo::order_evaluations()
3723 Order_eval
order_eval(this);
3724 this->traverse(&order_eval
);
3727 // Traversal to flatten parse tree after order of evaluation rules are applied.
3729 class Flatten
: public Traverse
3732 Flatten(Gogo
* gogo
, Named_object
* function
)
3733 : Traverse(traverse_variables
3734 | traverse_functions
3735 | traverse_statements
3736 | traverse_expressions
),
3737 gogo_(gogo
), function_(function
), inserter_()
3741 set_inserter(const Statement_inserter
* inserter
)
3742 { this->inserter_
= *inserter
; }
3745 variable(Named_object
*);
3748 function(Named_object
*);
3751 statement(Block
*, size_t* pindex
, Statement
*);
3754 expression(Expression
**);
3759 // The function we are traversing.
3760 Named_object
* function_
;
3761 // Current statement inserter for use by expressions.
3762 Statement_inserter inserter_
;
3765 // Flatten variables.
3768 Flatten::variable(Named_object
* no
)
3770 if (!no
->is_variable())
3771 return TRAVERSE_CONTINUE
;
3773 if (no
->is_variable() && no
->var_value()->is_global())
3775 // Global variables can have loops in their initialization
3776 // expressions. This is handled in flatten_init_expression.
3777 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
3779 return TRAVERSE_CONTINUE
;
3782 go_assert(!no
->var_value()->has_pre_init());
3784 return TRAVERSE_SKIP_COMPONENTS
;
3787 // Flatten the body of a function. Record the function while flattening it,
3788 // so that we can pass it down when flattening an expression.
3791 Flatten::function(Named_object
* no
)
3793 go_assert(this->function_
== NULL
);
3794 this->function_
= no
;
3795 int t
= no
->func_value()->traverse(this);
3796 this->function_
= NULL
;
3798 if (t
== TRAVERSE_EXIT
)
3800 return TRAVERSE_SKIP_COMPONENTS
;
3803 // Flatten statement parse trees.
3806 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3808 // Because we explicitly traverse the statement's contents
3809 // ourselves, we want to skip block statements here. There is
3810 // nothing to flatten in a block statement.
3811 if (sorig
->is_block_statement())
3812 return TRAVERSE_CONTINUE
;
3814 Statement_inserter
hold_inserter(this->inserter_
);
3815 this->inserter_
= Statement_inserter(block
, pindex
);
3817 // Flatten the expressions first.
3818 int t
= sorig
->traverse_contents(this);
3819 if (t
== TRAVERSE_EXIT
)
3821 this->inserter_
= hold_inserter
;
3825 // Keep flattening until nothing changes.
3826 Statement
* s
= sorig
;
3829 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
3834 t
= s
->traverse_contents(this);
3835 if (t
== TRAVERSE_EXIT
)
3837 this->inserter_
= hold_inserter
;
3843 block
->replace_statement(*pindex
, s
);
3845 this->inserter_
= hold_inserter
;
3846 return TRAVERSE_SKIP_COMPONENTS
;
3849 // Flatten expression parse trees.
3852 Flatten::expression(Expression
** pexpr
)
3854 // Keep flattening until nothing changes.
3857 Expression
* e
= *pexpr
;
3858 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3859 return TRAVERSE_EXIT
;
3861 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
3867 return TRAVERSE_SKIP_COMPONENTS
;
3873 Gogo::flatten_block(Named_object
* function
, Block
* block
)
3875 Flatten
flatten(this, function
);
3876 block
->traverse(&flatten
);
3879 // Flatten an expression. INSERTER may be NULL, in which case the
3880 // expression had better not need to create any temporaries.
3883 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
3886 Flatten
flatten(this, function
);
3887 if (inserter
!= NULL
)
3888 flatten
.set_inserter(inserter
);
3889 flatten
.expression(pexpr
);
3895 Flatten
flatten(this, NULL
);
3896 this->traverse(&flatten
);
3899 // Traversal to convert calls to the predeclared recover function to
3900 // pass in an argument indicating whether it can recover from a panic
3903 class Convert_recover
: public Traverse
3906 Convert_recover(Named_object
* arg
)
3907 : Traverse(traverse_expressions
),
3913 expression(Expression
**);
3916 // The argument to pass to the function.
3920 // Convert calls to recover.
3923 Convert_recover::expression(Expression
** pp
)
3925 Call_expression
* ce
= (*pp
)->call_expression();
3926 if (ce
!= NULL
&& ce
->is_recover_call())
3927 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
3929 return TRAVERSE_CONTINUE
;
3932 // Traversal for build_recover_thunks.
3934 class Build_recover_thunks
: public Traverse
3937 Build_recover_thunks(Gogo
* gogo
)
3938 : Traverse(traverse_functions
),
3943 function(Named_object
*);
3947 can_recover_arg(Location
);
3953 // If this function calls recover, turn it into a thunk.
3956 Build_recover_thunks::function(Named_object
* orig_no
)
3958 Function
* orig_func
= orig_no
->func_value();
3959 if (!orig_func
->calls_recover()
3960 || orig_func
->is_recover_thunk()
3961 || orig_func
->has_recover_thunk())
3962 return TRAVERSE_CONTINUE
;
3964 Gogo
* gogo
= this->gogo_
;
3965 Location location
= orig_func
->location();
3970 Function_type
* orig_fntype
= orig_func
->type();
3971 Typed_identifier_list
* new_params
= new Typed_identifier_list();
3972 std::string receiver_name
;
3973 if (orig_fntype
->is_method())
3975 const Typed_identifier
* receiver
= orig_fntype
->receiver();
3976 snprintf(buf
, sizeof buf
, "rt.%u", count
);
3978 receiver_name
= buf
;
3979 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
3980 receiver
->location()));
3982 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
3983 if (orig_params
!= NULL
&& !orig_params
->empty())
3985 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
3986 p
!= orig_params
->end();
3989 snprintf(buf
, sizeof buf
, "pt.%u", count
);
3991 new_params
->push_back(Typed_identifier(buf
, p
->type(),
3995 snprintf(buf
, sizeof buf
, "pr.%u", count
);
3997 std::string can_recover_name
= buf
;
3998 new_params
->push_back(Typed_identifier(can_recover_name
,
3999 Type::lookup_bool_type(),
4000 orig_fntype
->location()));
4002 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4003 Typed_identifier_list
* new_results
;
4004 if (orig_results
== NULL
|| orig_results
->empty())
4008 new_results
= new Typed_identifier_list();
4009 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4010 p
!= orig_results
->end();
4012 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4015 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4017 orig_fntype
->location());
4018 if (orig_fntype
->is_varargs())
4019 new_fntype
->set_is_varargs();
4021 std::string name
= orig_no
->name();
4022 if (orig_fntype
->is_method())
4023 name
+= "$" + orig_fntype
->receiver()->type()->mangled_name(gogo
);
4025 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4027 Function
*new_func
= new_no
->func_value();
4028 if (orig_func
->enclosing() != NULL
)
4029 new_func
->set_enclosing(orig_func
->enclosing());
4031 // We build the code for the original function attached to the new
4032 // function, and then swap the original and new function bodies.
4033 // This means that existing references to the original function will
4034 // then refer to the new function. That makes this code a little
4035 // confusing, in that the reference to NEW_NO really refers to the
4036 // other function, not the one we are building.
4038 Expression
* closure
= NULL
;
4039 if (orig_func
->needs_closure())
4041 // For the new function we are creating, declare a new parameter
4042 // variable NEW_CLOSURE_NO and set it to be the closure variable
4043 // of the function. This will be set to the closure value
4044 // passed in by the caller. Then pass a reference to this
4045 // variable as the closure value when calling the original
4046 // function. In other words, simply pass the closure value
4047 // through the thunk we are creating.
4048 Named_object
* orig_closure_no
= orig_func
->closure_var();
4049 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4050 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4051 false, false, location
);
4052 new_var
->set_is_closure();
4053 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4055 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4057 new_func
->set_closure_var(new_closure_no
);
4058 closure
= Expression::make_var_reference(new_closure_no
, location
);
4061 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4063 Expression_list
* args
= new Expression_list();
4064 if (new_params
!= NULL
)
4066 // Note that we skip the last parameter, which is the boolean
4067 // indicating whether recover can succed.
4068 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4069 p
+ 1 != new_params
->end();
4072 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4073 go_assert(p_no
!= NULL
4074 && p_no
->is_variable()
4075 && p_no
->var_value()->is_parameter());
4076 args
->push_back(Expression::make_var_reference(p_no
, location
));
4079 args
->push_back(this->can_recover_arg(location
));
4081 gogo
->start_block(location
);
4083 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4085 // Any varargs call has already been lowered.
4086 call
->set_varargs_are_lowered();
4088 Statement
* s
= Statement::make_return_from_call(call
, location
);
4089 s
->determine_types();
4090 gogo
->add_statement(s
);
4092 Block
* b
= gogo
->finish_block(location
);
4094 gogo
->add_block(b
, location
);
4096 // Lower the call in case it returns multiple results.
4097 gogo
->lower_block(new_no
, b
);
4099 gogo
->finish_function(location
);
4101 // Swap the function bodies and types.
4102 new_func
->swap_for_recover(orig_func
);
4103 orig_func
->set_is_recover_thunk();
4104 new_func
->set_calls_recover();
4105 new_func
->set_has_recover_thunk();
4107 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4108 Bindings
* new_bindings
= new_func
->block()->bindings();
4109 if (orig_fntype
->is_method())
4111 // We changed the receiver to be a regular parameter. We have
4112 // to update the binding accordingly in both functions.
4113 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4114 go_assert(orig_rec_no
!= NULL
4115 && orig_rec_no
->is_variable()
4116 && !orig_rec_no
->var_value()->is_receiver());
4117 orig_rec_no
->var_value()->set_is_receiver();
4119 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4120 if (new_receiver_name
.empty())
4122 // Find the receiver. It was named "r.NNN" in
4123 // Gogo::start_function.
4124 for (Bindings::const_definitions_iterator p
=
4125 new_bindings
->begin_definitions();
4126 p
!= new_bindings
->end_definitions();
4129 const std::string
& pname((*p
)->name());
4130 if (pname
[0] == 'r' && pname
[1] == '.')
4132 new_receiver_name
= pname
;
4136 go_assert(!new_receiver_name
.empty());
4138 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4139 if (new_rec_no
== NULL
)
4140 go_assert(saw_errors());
4143 go_assert(new_rec_no
->is_variable()
4144 && new_rec_no
->var_value()->is_receiver());
4145 new_rec_no
->var_value()->set_is_not_receiver();
4149 // Because we flipped blocks but not types, the can_recover
4150 // parameter appears in the (now) old bindings as a parameter.
4151 // Change it to a local variable, whereupon it will be discarded.
4152 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4153 go_assert(can_recover_no
!= NULL
4154 && can_recover_no
->is_variable()
4155 && can_recover_no
->var_value()->is_parameter());
4156 orig_bindings
->remove_binding(can_recover_no
);
4158 // Add the can_recover argument to the (now) new bindings, and
4159 // attach it to any recover statements.
4160 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4161 false, true, false, location
);
4162 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4164 Convert_recover
convert_recover(can_recover_no
);
4165 new_func
->traverse(&convert_recover
);
4167 // Update the function pointers in any named results.
4168 new_func
->update_result_variables();
4169 orig_func
->update_result_variables();
4171 return TRAVERSE_CONTINUE
;
4174 // Return the expression to pass for the .can_recover parameter to the
4175 // new function. This indicates whether a call to recover may return
4176 // non-nil. The expression is
4177 // __go_can_recover(__builtin_return_address()).
4180 Build_recover_thunks::can_recover_arg(Location location
)
4182 static Named_object
* builtin_return_address
;
4183 if (builtin_return_address
== NULL
)
4185 const Location bloc
= Linemap::predeclared_location();
4187 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4188 Type
* uint_type
= Type::lookup_integer_type("uint");
4189 param_types
->push_back(Typed_identifier("l", uint_type
, bloc
));
4191 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4192 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4193 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4195 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4196 return_types
, bloc
);
4197 builtin_return_address
=
4198 Named_object::make_function_declaration("__builtin_return_address",
4199 NULL
, fntype
, bloc
);
4200 const char* n
= "__builtin_return_address";
4201 builtin_return_address
->func_declaration_value()->set_asm_name(n
);
4204 static Named_object
* can_recover
;
4205 if (can_recover
== NULL
)
4207 const Location bloc
= Linemap::predeclared_location();
4208 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4209 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4210 param_types
->push_back(Typed_identifier("a", voidptr_type
, bloc
));
4211 Type
* boolean_type
= Type::lookup_bool_type();
4212 Typed_identifier_list
* results
= new Typed_identifier_list();
4213 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4214 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4216 can_recover
= Named_object::make_function_declaration("__go_can_recover",
4219 can_recover
->func_declaration_value()->set_asm_name("__go_can_recover");
4222 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4225 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4226 Expression_list
*args
= new Expression_list();
4227 args
->push_back(zexpr
);
4229 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4231 args
= new Expression_list();
4232 args
->push_back(call
);
4234 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4235 return Expression::make_call(fn
, args
, false, location
);
4238 // Build thunks for functions which call recover. We build a new
4239 // function with an extra parameter, which is whether a call to
4240 // recover can succeed. We then move the body of this function to
4241 // that one. We then turn this function into a thunk which calls the
4242 // new one, passing the value of
4243 // __go_can_recover(__builtin_return_address()). The function will be
4244 // marked as not splitting the stack. This will cooperate with the
4245 // implementation of defer to make recover do the right thing.
4248 Gogo::build_recover_thunks()
4250 Build_recover_thunks
build_recover_thunks(this);
4251 this->traverse(&build_recover_thunks
);
4254 // Build a call to the runtime error function.
4257 Gogo::runtime_error(int code
, Location location
)
4259 Type
* int32_type
= Type::lookup_integer_type("int32");
4260 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4262 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4265 // Look for named types to see whether we need to create an interface
4268 class Build_method_tables
: public Traverse
4271 Build_method_tables(Gogo
* gogo
,
4272 const std::vector
<Interface_type
*>& interfaces
)
4273 : Traverse(traverse_types
),
4274 gogo_(gogo
), interfaces_(interfaces
)
4283 // A list of locally defined interfaces which have hidden methods.
4284 const std::vector
<Interface_type
*>& interfaces_
;
4287 // Build all required interface method tables for types. We need to
4288 // ensure that we have an interface method table for every interface
4289 // which has a hidden method, for every named type which implements
4290 // that interface. Normally we can just build interface method tables
4291 // as we need them. However, in some cases we can require an
4292 // interface method table for an interface defined in a different
4293 // package for a type defined in that package. If that interface and
4294 // type both use a hidden method, that is OK. However, we will not be
4295 // able to build that interface method table when we need it, because
4296 // the type's hidden method will be static. So we have to build it
4297 // here, and just refer it from other packages as needed.
4300 Gogo::build_interface_method_tables()
4305 std::vector
<Interface_type
*> hidden_interfaces
;
4306 hidden_interfaces
.reserve(this->interface_types_
.size());
4307 for (std::vector
<Interface_type
*>::const_iterator pi
=
4308 this->interface_types_
.begin();
4309 pi
!= this->interface_types_
.end();
4312 const Typed_identifier_list
* methods
= (*pi
)->methods();
4313 if (methods
== NULL
)
4315 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4316 pm
!= methods
->end();
4319 if (Gogo::is_hidden_name(pm
->name()))
4321 hidden_interfaces
.push_back(*pi
);
4327 if (!hidden_interfaces
.empty())
4329 // Now traverse the tree looking for all named types.
4330 Build_method_tables
bmt(this, hidden_interfaces
);
4331 this->traverse(&bmt
);
4334 // We no longer need the list of interfaces.
4336 this->interface_types_
.clear();
4339 // This is called for each type. For a named type, for each of the
4340 // interfaces with hidden methods that it implements, create the
4344 Build_method_tables::type(Type
* type
)
4346 Named_type
* nt
= type
->named_type();
4347 Struct_type
* st
= type
->struct_type();
4348 if (nt
!= NULL
|| st
!= NULL
)
4350 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4351 for (std::vector
<Interface_type
*>::const_iterator p
=
4352 this->interfaces_
.begin();
4353 p
!= this->interfaces_
.end();
4356 // We ask whether a pointer to the named type implements the
4357 // interface, because a pointer can implement more methods
4361 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4364 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4365 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4370 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4373 st
->interface_method_table(*p
, false)->get_backend(&context
);
4374 st
->interface_method_table(*p
, true)->get_backend(&context
);
4379 return TRAVERSE_CONTINUE
;
4382 // Return an expression which allocates memory to hold values of type TYPE.
4385 Gogo::allocate_memory(Type
* type
, Location location
)
4387 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4389 Expression::make_type_info(type
, Expression::TYPE_INFO_SIZE
);
4390 return Runtime::make_call(Runtime::NEW
, location
, 2, td
, size
);
4393 // Traversal class used to check for return statements.
4395 class Check_return_statements_traverse
: public Traverse
4398 Check_return_statements_traverse()
4399 : Traverse(traverse_functions
)
4403 function(Named_object
*);
4406 // Check that a function has a return statement if it needs one.
4409 Check_return_statements_traverse::function(Named_object
* no
)
4411 Function
* func
= no
->func_value();
4412 const Function_type
* fntype
= func
->type();
4413 const Typed_identifier_list
* results
= fntype
->results();
4415 // We only need a return statement if there is a return value.
4416 if (results
== NULL
|| results
->empty())
4417 return TRAVERSE_CONTINUE
;
4419 if (func
->block()->may_fall_through())
4420 error_at(func
->block()->end_location(),
4421 "missing return at end of function");
4423 return TRAVERSE_CONTINUE
;
4426 // Check return statements.
4429 Gogo::check_return_statements()
4431 Check_return_statements_traverse traverse
;
4432 this->traverse(&traverse
);
4435 // Work out the package priority. It is one more than the maximum
4436 // priority of an imported package.
4439 Gogo::package_priority() const
4442 for (Packages::const_iterator p
= this->packages_
.begin();
4443 p
!= this->packages_
.end();
4445 if (p
->second
->priority() > priority
)
4446 priority
= p
->second
->priority();
4447 return priority
+ 1;
4450 // Export identifiers as requested.
4455 // For now we always stream to a section. Later we may want to
4456 // support streaming to a separate file.
4457 Stream_to_section stream
;
4459 // Write out either the prefix or pkgpath depending on how we were
4462 std::string pkgpath
;
4463 if (this->pkgpath_from_option_
)
4464 pkgpath
= this->pkgpath_
;
4465 else if (this->prefix_from_option_
)
4466 prefix
= this->prefix_
;
4467 else if (this->is_main_package())
4472 Export
exp(&stream
);
4473 exp
.register_builtin_types(this);
4474 exp
.export_globals(this->package_name(),
4477 this->package_priority(),
4480 (this->need_init_fn_
&& !this->is_main_package()
4481 ? this->get_init_fn_name()
4483 this->imported_init_fns_
,
4484 this->package_
->bindings());
4487 // Find the blocks in order to convert named types defined in blocks.
4489 class Convert_named_types
: public Traverse
4492 Convert_named_types(Gogo
* gogo
)
4493 : Traverse(traverse_blocks
),
4499 block(Block
* block
);
4506 Convert_named_types::block(Block
* block
)
4508 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
4509 return TRAVERSE_CONTINUE
;
4512 // Convert all named types to the backend representation. Since named
4513 // types can refer to other types, this needs to be done in the right
4514 // sequence, which is handled by Named_type::convert. Here we arrange
4515 // to call that for each named type.
4518 Gogo::convert_named_types()
4520 this->convert_named_types_in_bindings(this->globals_
);
4521 for (Packages::iterator p
= this->packages_
.begin();
4522 p
!= this->packages_
.end();
4525 Package
* package
= p
->second
;
4526 this->convert_named_types_in_bindings(package
->bindings());
4529 Convert_named_types
cnt(this);
4530 this->traverse(&cnt
);
4532 // Make all the builtin named types used for type descriptors, and
4533 // then convert them. They will only be written out if they are
4535 Type::make_type_descriptor_type();
4536 Type::make_type_descriptor_ptr_type();
4537 Function_type::make_function_type_descriptor_type();
4538 Pointer_type::make_pointer_type_descriptor_type();
4539 Struct_type::make_struct_type_descriptor_type();
4540 Array_type::make_array_type_descriptor_type();
4541 Array_type::make_slice_type_descriptor_type();
4542 Map_type::make_map_type_descriptor_type();
4543 Map_type::make_map_descriptor_type();
4544 Channel_type::make_chan_type_descriptor_type();
4545 Interface_type::make_interface_type_descriptor_type();
4546 Expression::make_func_descriptor_type();
4547 Type::convert_builtin_named_types(this);
4549 Runtime::convert_types(this);
4551 this->named_types_are_converted_
= true;
4554 // Convert all names types in a set of bindings.
4557 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
4559 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
4560 p
!= bindings
->end_definitions();
4563 if ((*p
)->is_type())
4564 (*p
)->type_value()->convert(this);
4570 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
4572 : type_(type
), enclosing_(enclosing
), results_(NULL
),
4573 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
4574 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
4575 is_sink_(false), results_are_named_(false), nointerface_(false),
4576 is_unnamed_type_stub_method_(false), calls_recover_(false),
4577 is_recover_thunk_(false), has_recover_thunk_(false),
4578 calls_defer_retaddr_(false), is_type_specific_function_(false),
4579 in_unique_section_(false)
4583 // Create the named result variables.
4586 Function::create_result_variables(Gogo
* gogo
)
4588 const Typed_identifier_list
* results
= this->type_
->results();
4589 if (results
== NULL
|| results
->empty())
4592 if (!results
->front().name().empty())
4593 this->results_are_named_
= true;
4595 this->results_
= new Results();
4596 this->results_
->reserve(results
->size());
4598 Block
* block
= this->block_
;
4600 for (Typed_identifier_list::const_iterator p
= results
->begin();
4601 p
!= results
->end();
4604 std::string name
= p
->name();
4605 if (name
.empty() || Gogo::is_sink_name(name
))
4607 static int result_counter
;
4609 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
4611 name
= gogo
->pack_hidden_name(buf
, false);
4613 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
4615 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
4616 if (no
->is_result_variable())
4617 this->results_
->push_back(no
);
4620 static int dummy_result_count
;
4622 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
4623 ++dummy_result_count
;
4624 name
= gogo
->pack_hidden_name(buf
, false);
4625 no
= block
->bindings()->add_result_variable(name
, result
);
4626 go_assert(no
->is_result_variable());
4627 this->results_
->push_back(no
);
4632 // Update the named result variables when cloning a function which
4636 Function::update_result_variables()
4638 if (this->results_
== NULL
)
4641 for (Results::iterator p
= this->results_
->begin();
4642 p
!= this->results_
->end();
4644 (*p
)->result_var_value()->set_function(this);
4647 // Return the closure variable, creating it if necessary.
4650 Function::closure_var()
4652 if (this->closure_var_
== NULL
)
4654 go_assert(this->descriptor_
== NULL
);
4655 // We don't know the type of the variable yet. We add fields as
4657 Location loc
= this->type_
->location();
4658 Struct_field_list
* sfl
= new Struct_field_list
;
4659 Type
* struct_type
= Type::make_struct_type(sfl
, loc
);
4660 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
4661 NULL
, false, false, false, loc
);
4663 var
->set_is_closure();
4664 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
4665 // Note that the new variable is not in any binding contour.
4667 return this->closure_var_
;
4670 // Set the type of the closure variable.
4673 Function::set_closure_type()
4675 if (this->closure_var_
== NULL
)
4677 Named_object
* closure
= this->closure_var_
;
4678 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
4680 // The first field of a closure is always a pointer to the function
4682 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4683 st
->push_field(Struct_field(Typed_identifier(".$f", voidptr_type
,
4686 unsigned int index
= 1;
4687 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
4688 p
!= this->closure_fields_
.end();
4691 Named_object
* no
= p
->first
;
4693 snprintf(buf
, sizeof buf
, "%u", index
);
4694 std::string n
= no
->name() + buf
;
4696 if (no
->is_variable())
4697 var_type
= no
->var_value()->type();
4699 var_type
= no
->result_var_value()->type();
4700 Type
* field_type
= Type::make_pointer_type(var_type
);
4701 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
4705 // Return whether this function is a method.
4708 Function::is_method() const
4710 return this->type_
->is_method();
4713 // Add a label definition.
4716 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
4719 Label
* lnull
= NULL
;
4720 std::pair
<Labels::iterator
, bool> ins
=
4721 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4723 if (label_name
== "_")
4725 label
= Label::create_dummy_label();
4727 ins
.first
->second
= label
;
4729 else if (ins
.second
)
4731 // This is a new label.
4732 label
= new Label(label_name
);
4733 ins
.first
->second
= label
;
4737 // The label was already in the hash table.
4738 label
= ins
.first
->second
;
4739 if (label
->is_defined())
4741 error_at(location
, "label %qs already defined",
4742 Gogo::message_name(label_name
).c_str());
4743 inform(label
->location(), "previous definition of %qs was here",
4744 Gogo::message_name(label_name
).c_str());
4745 return new Label(label_name
);
4749 label
->define(location
, gogo
->bindings_snapshot(location
));
4751 // Issue any errors appropriate for any previous goto's to this
4753 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
4754 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
4757 (*p
)->check_goto_to(gogo
->current_block());
4758 label
->clear_refs();
4763 // Add a reference to a label.
4766 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
4767 Location location
, bool issue_goto_errors
)
4769 Label
* lnull
= NULL
;
4770 std::pair
<Labels::iterator
, bool> ins
=
4771 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4775 // The label was already in the hash table.
4776 label
= ins
.first
->second
;
4780 go_assert(ins
.first
->second
== NULL
);
4781 label
= new Label(label_name
);
4782 ins
.first
->second
= label
;
4785 label
->set_is_used();
4787 if (issue_goto_errors
)
4789 Bindings_snapshot
* snapshot
= label
->snapshot();
4790 if (snapshot
!= NULL
)
4791 snapshot
->check_goto_from(gogo
->current_block(), location
);
4793 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
4799 // Warn about labels that are defined but not used.
4802 Function::check_labels() const
4804 for (Labels::const_iterator p
= this->labels_
.begin();
4805 p
!= this->labels_
.end();
4808 Label
* label
= p
->second
;
4809 if (!label
->is_used())
4810 error_at(label
->location(), "label %qs defined and not used",
4811 Gogo::message_name(label
->name()).c_str());
4815 // Swap one function with another. This is used when building the
4816 // thunk we use to call a function which calls recover. It may not
4817 // work for any other case.
4820 Function::swap_for_recover(Function
*x
)
4822 go_assert(this->enclosing_
== x
->enclosing_
);
4823 std::swap(this->results_
, x
->results_
);
4824 std::swap(this->closure_var_
, x
->closure_var_
);
4825 std::swap(this->block_
, x
->block_
);
4826 go_assert(this->location_
== x
->location_
);
4827 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
4828 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
4831 // Traverse the tree.
4834 Function::traverse(Traverse
* traverse
)
4836 unsigned int traverse_mask
= traverse
->traverse_mask();
4839 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
4842 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
4843 return TRAVERSE_EXIT
;
4846 // FIXME: We should check traverse_functions here if nested
4847 // functions are stored in block bindings.
4848 if (this->block_
!= NULL
4850 & (Traverse::traverse_variables
4851 | Traverse::traverse_constants
4852 | Traverse::traverse_blocks
4853 | Traverse::traverse_statements
4854 | Traverse::traverse_expressions
4855 | Traverse::traverse_types
)) != 0)
4857 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
4858 return TRAVERSE_EXIT
;
4861 return TRAVERSE_CONTINUE
;
4864 // Work out types for unspecified variables and constants.
4867 Function::determine_types()
4869 if (this->block_
!= NULL
)
4870 this->block_
->determine_types();
4873 // Return the function descriptor, the value you get when you refer to
4874 // the function in Go code without calling it.
4877 Function::descriptor(Gogo
*, Named_object
* no
)
4879 go_assert(!this->is_method());
4880 go_assert(this->closure_var_
== NULL
);
4881 if (this->descriptor_
== NULL
)
4882 this->descriptor_
= Expression::make_func_descriptor(no
);
4883 return this->descriptor_
;
4886 // Get a pointer to the variable representing the defer stack for this
4887 // function, making it if necessary. The value of the variable is set
4888 // by the runtime routines to true if the function is returning,
4889 // rather than panicing through. A pointer to this variable is used
4890 // as a marker for the functions on the defer stack associated with
4891 // this function. A function-specific variable permits inlining a
4892 // function which uses defer.
4895 Function::defer_stack(Location location
)
4897 if (this->defer_stack_
== NULL
)
4899 Type
* t
= Type::lookup_bool_type();
4900 Expression
* n
= Expression::make_boolean(false, location
);
4901 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
4902 this->defer_stack_
->set_is_address_taken();
4904 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
4906 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
4909 // Export the function.
4912 Function::export_func(Export
* exp
, const std::string
& name
) const
4914 Function::export_func_with_type(exp
, name
, this->type_
);
4917 // Export a function with a type.
4920 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
4921 const Function_type
* fntype
)
4923 exp
->write_c_string("func ");
4925 if (fntype
->is_method())
4927 exp
->write_c_string("(");
4928 const Typed_identifier
* receiver
= fntype
->receiver();
4929 exp
->write_name(receiver
->name());
4931 if (fntype
->has_escape_info())
4933 exp
->write_c_string(" ");
4934 exp
->write_escape(fntype
->receiver_escape_state());
4937 exp
->write_c_string(" ");
4938 exp
->write_type(receiver
->type());
4939 exp
->write_c_string(") ");
4942 exp
->write_string(name
);
4944 exp
->write_c_string(" (");
4945 const Typed_identifier_list
* parameters
= fntype
->parameters();
4946 if (parameters
!= NULL
)
4949 bool is_varargs
= fntype
->is_varargs();
4951 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
4952 p
!= parameters
->end();
4958 exp
->write_c_string(", ");
4959 exp
->write_name(p
->name());
4961 if (fntype
->has_escape_info())
4963 exp
->write_c_string(" ");
4964 exp
->write_escape(fntype
->parameter_escape_states()->at(i
));
4967 exp
->write_c_string(" ");
4968 if (!is_varargs
|| p
+ 1 != parameters
->end())
4969 exp
->write_type(p
->type());
4972 exp
->write_c_string("...");
4973 exp
->write_type(p
->type()->array_type()->element_type());
4977 exp
->write_c_string(")");
4979 const Typed_identifier_list
* results
= fntype
->results();
4980 if (results
!= NULL
)
4982 if (results
->size() == 1 && results
->begin()->name().empty())
4984 exp
->write_c_string(" ");
4985 exp
->write_type(results
->begin()->type());
4989 exp
->write_c_string(" (");
4991 for (Typed_identifier_list::const_iterator p
= results
->begin();
4992 p
!= results
->end();
4998 exp
->write_c_string(", ");
4999 exp
->write_name(p
->name());
5000 exp
->write_c_string(" ");
5001 exp
->write_type(p
->type());
5003 exp
->write_c_string(")");
5006 exp
->write_c_string(";\n");
5009 // Import a function.
5012 Function::import_func(Import
* imp
, std::string
* pname
,
5013 Typed_identifier
** preceiver
,
5014 Node::Escapement_lattice
* rcvr_escape
,
5015 Typed_identifier_list
** pparameters
,
5016 Node::Escape_states
** pparam_escapes
,
5017 Typed_identifier_list
** presults
,
5018 bool* is_varargs
, bool* has_escape_info
)
5020 *has_escape_info
= false;
5022 imp
->require_c_string("func ");
5025 *rcvr_escape
= Node::ESCAPE_NONE
;
5026 if (imp
->peek_char() == '(')
5028 imp
->require_c_string("(");
5029 std::string name
= imp
->read_name();
5031 if (imp
->match_c_string(" <escape")){
5032 *has_escape_info
= true;
5033 imp
->require_c_string(" ");
5034 *rcvr_escape
= imp
->read_escape_info();
5037 imp
->require_c_string(" ");
5038 Type
* rtype
= imp
->read_type();
5039 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5040 imp
->require_c_string(") ");
5043 *pname
= imp
->read_identifier();
5045 Typed_identifier_list
* parameters
;
5046 Node::Escape_states
* param_escapes
;
5047 *is_varargs
= false;
5048 imp
->require_c_string(" (");
5049 if (imp
->peek_char() == ')')
5052 param_escapes
= NULL
;
5056 parameters
= new Typed_identifier_list();
5057 param_escapes
= new Node::Escape_states();
5060 std::string name
= imp
->read_name();
5061 if (imp
->match_c_string(" <escape")){
5062 *has_escape_info
= true;
5063 imp
->require_c_string(" ");
5064 param_escapes
->push_back(imp
->read_escape_info());
5067 imp
->require_c_string(" ");
5069 if (imp
->match_c_string("..."))
5075 Type
* ptype
= imp
->read_type();
5077 ptype
= Type::make_array_type(ptype
, NULL
);
5078 parameters
->push_back(Typed_identifier(name
, ptype
,
5080 if (imp
->peek_char() != ',')
5082 go_assert(!*is_varargs
);
5083 imp
->require_c_string(", ");
5086 imp
->require_c_string(")");
5087 *pparameters
= parameters
;
5088 *pparam_escapes
= param_escapes
;
5090 Typed_identifier_list
* results
;
5091 if (imp
->peek_char() != ' ')
5095 results
= new Typed_identifier_list();
5096 imp
->require_c_string(" ");
5097 if (imp
->peek_char() != '(')
5099 Type
* rtype
= imp
->read_type();
5100 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5104 imp
->require_c_string("(");
5107 std::string name
= imp
->read_name();
5108 imp
->require_c_string(" ");
5109 Type
* rtype
= imp
->read_type();
5110 results
->push_back(Typed_identifier(name
, rtype
,
5112 if (imp
->peek_char() != ',')
5114 imp
->require_c_string(", ");
5116 imp
->require_c_string(")");
5119 imp
->require_c_string(";\n");
5120 *presults
= results
;
5123 // Get the backend representation.
5126 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5128 if (this->fndecl_
== NULL
)
5130 std::string asm_name
;
5131 bool is_visible
= false;
5132 if (no
->package() != NULL
)
5134 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5136 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5137 && !this->type_
->is_method())
5139 else if (no
->name() == gogo
->get_init_fn_name())
5142 asm_name
= no
->name();
5144 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5145 && gogo
->is_main_package())
5147 // Methods have to be public even if they are hidden because
5148 // they can be pulled into type descriptors when using
5149 // anonymous fields.
5150 else if (!Gogo::is_hidden_name(no
->name())
5151 || this->type_
->is_method())
5153 if (!this->is_unnamed_type_stub_method_
)
5155 std::string pkgpath
= gogo
->pkgpath_symbol();
5156 if (this->type_
->is_method()
5157 && Gogo::is_hidden_name(no
->name())
5158 && Gogo::hidden_name_pkgpath(no
->name()) != gogo
->pkgpath())
5160 // This is a method we created for an unexported
5161 // method of an imported embedded type. We need to
5162 // use the pkgpath of the imported package to avoid
5163 // a possible name collision. See bug478 for a test
5165 pkgpath
= Gogo::hidden_name_pkgpath(no
->name());
5166 pkgpath
= Gogo::pkgpath_for_symbol(pkgpath
);
5170 asm_name
.append(1, '.');
5171 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5172 if (this->type_
->is_method())
5174 asm_name
.append(1, '.');
5175 Type
* rtype
= this->type_
->receiver()->type();
5176 asm_name
.append(rtype
->mangled_name(gogo
));
5180 // If a function calls the predeclared recover function, we
5181 // can't inline it, because recover behaves differently in a
5182 // function passed directly to defer. If this is a recover
5183 // thunk that we built to test whether a function can be
5184 // recovered, we can't inline it, because that will mess up
5185 // our return address comparison.
5186 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5188 // If a function calls __go_set_defer_retaddr, then mark it as
5189 // uninlinable. This prevents the GCC backend from splitting
5190 // the function; splitting the function is a bad idea because we
5191 // want the return address label to be in the same function as
5193 if (this->calls_defer_retaddr_
)
5194 is_inlinable
= false;
5196 // If this is a thunk created to call a function which calls
5197 // the predeclared recover function, we need to disable
5198 // stack splitting for the thunk.
5199 bool disable_split_stack
= this->is_recover_thunk_
;
5201 // This should go into a unique section if that has been
5202 // requested elsewhere, or if this is a nointerface function.
5203 // We want to put a nointerface function into a unique section
5204 // because there is a good chance that the linker garbage
5205 // collection can discard it.
5206 bool in_unique_section
= this->in_unique_section_
|| this->nointerface_
;
5208 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5210 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5211 is_visible
, false, is_inlinable
,
5212 disable_split_stack
, in_unique_section
,
5215 return this->fndecl_
;
5218 // Get the backend representation.
5221 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5223 if (this->fndecl_
== NULL
)
5225 // Let Go code use an asm declaration to pick up a builtin
5227 if (!this->asm_name_
.empty())
5229 Bfunction
* builtin_decl
=
5230 gogo
->backend()->lookup_builtin(this->asm_name_
);
5231 if (builtin_decl
!= NULL
)
5233 this->fndecl_
= builtin_decl
;
5234 return this->fndecl_
;
5238 std::string asm_name
;
5239 if (this->asm_name_
.empty())
5241 asm_name
= (no
->package() == NULL
5242 ? gogo
->pkgpath_symbol()
5243 : no
->package()->pkgpath_symbol());
5244 asm_name
.append(1, '.');
5245 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5246 if (this->fntype_
->is_method())
5248 asm_name
.append(1, '.');
5249 Type
* rtype
= this->fntype_
->receiver()->type();
5250 asm_name
.append(rtype
->mangled_name(gogo
));
5254 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5256 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5257 true, true, true, false, false,
5261 return this->fndecl_
;
5264 // Build the descriptor for a function declaration. This won't
5265 // necessarily happen if the package has just a declaration for the
5266 // function and no other reference to it, but we may still need the
5267 // descriptor for references from other packages.
5269 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5271 if (this->descriptor_
!= NULL
)
5273 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5274 this->descriptor_
->get_backend(&context
);
5278 // Return the function's decl after it has been built.
5281 Function::get_decl() const
5283 go_assert(this->fndecl_
!= NULL
);
5284 return this->fndecl_
;
5287 // Build the backend representation for the function code.
5290 Function::build(Gogo
* gogo
, Named_object
* named_function
)
5292 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5294 // A list of parameter variables for this function.
5295 std::vector
<Bvariable
*> param_vars
;
5297 // Variables that need to be declared for this function and their
5299 std::vector
<Bvariable
*> vars
;
5300 std::vector
<Bexpression
*> var_inits
;
5301 for (Bindings::const_definitions_iterator p
=
5302 this->block_
->bindings()->begin_definitions();
5303 p
!= this->block_
->bindings()->end_definitions();
5306 Location loc
= (*p
)->location();
5307 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
5309 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5310 Bvariable
* parm_bvar
= bvar
;
5312 // We always pass the receiver to a method as a pointer. If
5313 // the receiver is declared as a non-pointer type, then we
5314 // copy the value into a local variable.
5315 if ((*p
)->var_value()->is_receiver()
5316 && (*p
)->var_value()->type()->points_to() == NULL
)
5318 std::string name
= (*p
)->name() + ".pointer";
5319 Type
* var_type
= (*p
)->var_value()->type();
5320 Variable
* parm_var
=
5321 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
5323 Named_object
* parm_no
=
5324 Named_object::make_variable(name
, NULL
, parm_var
);
5325 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5327 vars
.push_back(bvar
);
5328 Expression
* parm_ref
=
5329 Expression::make_var_reference(parm_no
, loc
);
5330 parm_ref
= Expression::make_unary(OPERATOR_MULT
, parm_ref
, loc
);
5331 if ((*p
)->var_value()->is_in_heap())
5332 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
5333 var_inits
.push_back(parm_ref
->get_backend(&context
));
5335 else if ((*p
)->var_value()->is_in_heap())
5337 // If we take the address of a parameter, then we need
5338 // to copy it into the heap.
5339 std::string parm_name
= (*p
)->name() + ".param";
5340 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
5341 false, true, false, loc
);
5342 Named_object
* parm_no
=
5343 Named_object::make_variable(parm_name
, NULL
, parm_var
);
5344 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5346 vars
.push_back(bvar
);
5347 Expression
* var_ref
=
5348 Expression::make_var_reference(parm_no
, loc
);
5349 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
5350 var_inits
.push_back(var_ref
->get_backend(&context
));
5352 param_vars
.push_back(parm_bvar
);
5354 else if ((*p
)->is_result_variable())
5356 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5358 Type
* type
= (*p
)->result_var_value()->type();
5360 if (!(*p
)->result_var_value()->is_in_heap())
5362 Btype
* btype
= type
->get_backend(gogo
);
5363 init
= gogo
->backend()->zero_expression(btype
);
5366 init
= Expression::make_allocation(type
,
5367 loc
)->get_backend(&context
);
5369 vars
.push_back(bvar
);
5370 var_inits
.push_back(init
);
5373 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
5375 go_assert(saw_errors());
5379 // If we need a closure variable, make sure to create it.
5380 // It gets installed in the function as a side effect of creation.
5381 if (this->closure_var_
!= NULL
)
5383 go_assert(this->closure_var_
->var_value()->is_closure());
5384 this->closure_var_
->get_backend_variable(gogo
, named_function
);
5387 if (this->block_
!= NULL
)
5389 // Declare variables if necessary.
5390 Bblock
* var_decls
= NULL
;
5392 Bstatement
* defer_init
= NULL
;
5393 if (!vars
.empty() || this->defer_stack_
!= NULL
)
5396 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
5397 this->block_
->start_location(),
5398 this->block_
->end_location());
5400 if (this->defer_stack_
!= NULL
)
5402 Translate_context
dcontext(gogo
, named_function
, this->block_
,
5404 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
5408 // Build the backend representation for all the statements in the
5410 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5411 Bblock
* code_block
= this->block_
->get_backend(&context
);
5413 // Initialize variables if necessary.
5414 std::vector
<Bstatement
*> init
;
5415 go_assert(vars
.size() == var_inits
.size());
5416 for (size_t i
= 0; i
< vars
.size(); ++i
)
5418 Bstatement
* init_stmt
=
5419 gogo
->backend()->init_statement(vars
[i
], var_inits
[i
]);
5420 init
.push_back(init_stmt
);
5422 if (defer_init
!= NULL
)
5423 init
.push_back(defer_init
);
5424 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
5426 // Initialize all variables before executing this code block.
5427 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
5428 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
5430 // If we have a defer stack, initialize it at the start of a
5432 Bstatement
* except
= NULL
;
5433 Bstatement
* fini
= NULL
;
5434 if (defer_init
!= NULL
)
5436 // Clean up the defer stack when we leave the function.
5437 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
5439 // Wrap the code for this function in an exception handler to handle
5442 gogo
->backend()->exception_handler_statement(code_stmt
,
5447 // Stick the code into the block we built for the receiver, if
5449 if (var_decls
!= NULL
)
5451 std::vector
<Bstatement
*> code_stmt_list(1, code_stmt
);
5452 gogo
->backend()->block_add_statements(var_decls
, code_stmt_list
);
5453 code_stmt
= gogo
->backend()->block_statement(var_decls
);
5456 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
5458 go_assert(saw_errors());
5463 // If we created a descriptor for the function, make sure we emit it.
5464 if (this->descriptor_
!= NULL
)
5466 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5467 this->descriptor_
->get_backend(&context
);
5471 // Build the wrappers around function code needed if the function has
5472 // any defer statements. This sets *EXCEPT to an exception handler
5473 // and *FINI to a finally handler.
5476 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
5477 Bstatement
** except
, Bstatement
** fini
)
5479 Location end_loc
= this->block_
->end_location();
5481 // Add an exception handler. This is used if a panic occurs. Its
5482 // purpose is to stop the stack unwinding if a deferred function
5483 // calls recover. There are more details in
5484 // libgo/runtime/go-unwind.c.
5486 std::vector
<Bstatement
*> stmts
;
5487 Expression
* call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5488 this->defer_stack(end_loc
));
5489 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5490 Bexpression
* defer
= call
->get_backend(&context
);
5491 stmts
.push_back(gogo
->backend()->expression_statement(defer
));
5493 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5494 if (ret_bstmt
!= NULL
)
5495 stmts
.push_back(ret_bstmt
);
5497 go_assert(*except
== NULL
);
5498 *except
= gogo
->backend()->statement_list(stmts
);
5500 call
= Runtime::make_call(Runtime::CHECK_DEFER
, end_loc
, 1,
5501 this->defer_stack(end_loc
));
5502 defer
= call
->get_backend(&context
);
5504 call
= Runtime::make_call(Runtime::UNDEFER
, end_loc
, 1,
5505 this->defer_stack(end_loc
));
5506 Bexpression
* undefer
= call
->get_backend(&context
);
5507 Bstatement
* function_defer
=
5508 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
5510 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
5511 if (this->type_
->results() != NULL
5512 && !this->type_
->results()->empty()
5513 && !this->type_
->results()->front().name().empty())
5515 // If the result variables are named, and we are returning from
5516 // this function rather than panicing through it, we need to
5517 // return them again, because they might have been changed by a
5518 // defer function. The runtime routines set the defer_stack
5519 // variable to true if we are returning from this function.
5521 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5522 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
5524 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
5526 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
5527 Bexpression
* bref
= ref
->get_backend(&context
);
5528 ret
= gogo
->backend()->conditional_expression(NULL
, bref
, ret
, NULL
,
5530 stmts
.push_back(gogo
->backend()->expression_statement(ret
));
5533 go_assert(*fini
== NULL
);
5534 *fini
= gogo
->backend()->statement_list(stmts
);
5537 // Return the statement that assigns values to this function's result struct.
5540 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
5541 Location location
) const
5543 const Typed_identifier_list
* results
= this->type_
->results();
5544 if (results
== NULL
|| results
->empty())
5547 go_assert(this->results_
!= NULL
);
5548 if (this->results_
->size() != results
->size())
5550 go_assert(saw_errors());
5551 return gogo
->backend()->error_statement();
5554 std::vector
<Bexpression
*> vals(results
->size());
5555 for (size_t i
= 0; i
< vals
.size(); ++i
)
5557 Named_object
* no
= (*this->results_
)[i
];
5558 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
5559 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
5560 if (no
->result_var_value()->is_in_heap())
5562 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
5563 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
5567 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
5572 Block::Block(Block
* enclosing
, Location location
)
5573 : enclosing_(enclosing
), statements_(),
5574 bindings_(new Bindings(enclosing
== NULL
5576 : enclosing
->bindings())),
5577 start_location_(location
),
5578 end_location_(UNKNOWN_LOCATION
)
5582 // Add a statement to a block.
5585 Block::add_statement(Statement
* statement
)
5587 this->statements_
.push_back(statement
);
5590 // Add a statement to the front of a block. This is slow but is only
5591 // used for reference counts of parameters.
5594 Block::add_statement_at_front(Statement
* statement
)
5596 this->statements_
.insert(this->statements_
.begin(), statement
);
5599 // Replace a statement in a block.
5602 Block::replace_statement(size_t index
, Statement
* s
)
5604 go_assert(index
< this->statements_
.size());
5605 this->statements_
[index
] = s
;
5608 // Add a statement before another statement.
5611 Block::insert_statement_before(size_t index
, Statement
* s
)
5613 go_assert(index
< this->statements_
.size());
5614 this->statements_
.insert(this->statements_
.begin() + index
, s
);
5617 // Add a statement after another statement.
5620 Block::insert_statement_after(size_t index
, Statement
* s
)
5622 go_assert(index
< this->statements_
.size());
5623 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
5626 // Traverse the tree.
5629 Block::traverse(Traverse
* traverse
)
5631 unsigned int traverse_mask
= traverse
->traverse_mask();
5633 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
5635 int t
= traverse
->block(this);
5636 if (t
== TRAVERSE_EXIT
)
5637 return TRAVERSE_EXIT
;
5638 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
5639 return TRAVERSE_CONTINUE
;
5643 & (Traverse::traverse_variables
5644 | Traverse::traverse_constants
5645 | Traverse::traverse_expressions
5646 | Traverse::traverse_types
)) != 0)
5648 const unsigned int e_or_t
= (Traverse::traverse_expressions
5649 | Traverse::traverse_types
);
5650 const unsigned int e_or_t_or_s
= (e_or_t
5651 | Traverse::traverse_statements
);
5652 for (Bindings::const_definitions_iterator pb
=
5653 this->bindings_
->begin_definitions();
5654 pb
!= this->bindings_
->end_definitions();
5657 int t
= TRAVERSE_CONTINUE
;
5658 switch ((*pb
)->classification())
5660 case Named_object::NAMED_OBJECT_CONST
:
5661 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
5662 t
= traverse
->constant(*pb
, false);
5663 if (t
== TRAVERSE_CONTINUE
5664 && (traverse_mask
& e_or_t
) != 0)
5666 Type
* tc
= (*pb
)->const_value()->type();
5668 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
5669 return TRAVERSE_EXIT
;
5670 t
= (*pb
)->const_value()->traverse_expression(traverse
);
5674 case Named_object::NAMED_OBJECT_VAR
:
5675 case Named_object::NAMED_OBJECT_RESULT_VAR
:
5676 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
5677 t
= traverse
->variable(*pb
);
5678 if (t
== TRAVERSE_CONTINUE
5679 && (traverse_mask
& e_or_t
) != 0)
5681 if ((*pb
)->is_result_variable()
5682 || (*pb
)->var_value()->has_type())
5684 Type
* tv
= ((*pb
)->is_variable()
5685 ? (*pb
)->var_value()->type()
5686 : (*pb
)->result_var_value()->type());
5688 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
5689 return TRAVERSE_EXIT
;
5692 if (t
== TRAVERSE_CONTINUE
5693 && (traverse_mask
& e_or_t_or_s
) != 0
5694 && (*pb
)->is_variable())
5695 t
= (*pb
)->var_value()->traverse_expression(traverse
,
5699 case Named_object::NAMED_OBJECT_FUNC
:
5700 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
5703 case Named_object::NAMED_OBJECT_TYPE
:
5704 if ((traverse_mask
& e_or_t
) != 0)
5705 t
= Type::traverse((*pb
)->type_value(), traverse
);
5708 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
5709 case Named_object::NAMED_OBJECT_UNKNOWN
:
5710 case Named_object::NAMED_OBJECT_ERRONEOUS
:
5713 case Named_object::NAMED_OBJECT_PACKAGE
:
5714 case Named_object::NAMED_OBJECT_SINK
:
5721 if (t
== TRAVERSE_EXIT
)
5722 return TRAVERSE_EXIT
;
5726 // No point in checking traverse_mask here--if we got here we always
5727 // want to walk the statements. The traversal can insert new
5728 // statements before or after the current statement. Inserting
5729 // statements before the current statement requires updating I via
5730 // the pointer; those statements will not be traversed. Any new
5731 // statements inserted after the current statement will be traversed
5733 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
5735 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
5736 return TRAVERSE_EXIT
;
5739 return TRAVERSE_CONTINUE
;
5742 // Work out types for unspecified variables and constants.
5745 Block::determine_types()
5747 for (Bindings::const_definitions_iterator pb
=
5748 this->bindings_
->begin_definitions();
5749 pb
!= this->bindings_
->end_definitions();
5752 if ((*pb
)->is_variable())
5753 (*pb
)->var_value()->determine_type();
5754 else if ((*pb
)->is_const())
5755 (*pb
)->const_value()->determine_type();
5758 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
5759 ps
!= this->statements_
.end();
5761 (*ps
)->determine_types();
5764 // Return true if the statements in this block may fall through.
5767 Block::may_fall_through() const
5769 if (this->statements_
.empty())
5771 return this->statements_
.back()->may_fall_through();
5774 // Convert a block to the backend representation.
5777 Block::get_backend(Translate_context
* context
)
5779 Gogo
* gogo
= context
->gogo();
5780 Named_object
* function
= context
->function();
5781 std::vector
<Bvariable
*> vars
;
5782 vars
.reserve(this->bindings_
->size_definitions());
5783 for (Bindings::const_definitions_iterator pv
=
5784 this->bindings_
->begin_definitions();
5785 pv
!= this->bindings_
->end_definitions();
5788 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
5789 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
5792 go_assert(function
!= NULL
);
5793 Bfunction
* bfunction
=
5794 function
->func_value()->get_or_make_decl(gogo
, function
);
5795 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
5796 vars
, this->start_location_
,
5797 this->end_location_
);
5799 Translate_context
subcontext(gogo
, function
, this, ret
);
5800 std::vector
<Bstatement
*> bstatements
;
5801 bstatements
.reserve(this->statements_
.size());
5802 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
5803 p
!= this->statements_
.end();
5805 bstatements
.push_back((*p
)->get_backend(&subcontext
));
5807 context
->backend()->block_add_statements(ret
, bstatements
);
5812 // Class Bindings_snapshot.
5814 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
5815 : block_(b
), counts_(), location_(location
)
5819 this->counts_
.push_back(b
->bindings()->size_definitions());
5824 // Report errors appropriate for a goto from B to this.
5827 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
5830 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
5832 this->check_goto_defs(loc
, this->block_
,
5833 this->block_
->bindings()->size_definitions(),
5837 // Report errors appropriate for a goto from this to B.
5840 Bindings_snapshot::check_goto_to(const Block
* b
)
5843 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
5845 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
5846 b
->bindings()->size_definitions());
5849 // Report errors appropriate for a goto at LOC from BFROM to BTO.
5850 // Return true if all is well, false if we reported an error. If this
5851 // returns true, it sets *PINDEX to the number of blocks BTO is above
5855 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
5856 const Block
* bto
, size_t* pindex
)
5858 // It is an error if BTO is not either BFROM or above BFROM.
5860 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
5864 error_at(loc
, "goto jumps into block");
5865 inform(bto
->start_location(), "goto target block starts here");
5873 // Report errors appropriate for a goto at LOC ending at BLOCK, where
5874 // CFROM is the number of names defined at the point of the goto and
5875 // CTO is the number of names defined at the point of the label.
5878 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
5879 size_t cfrom
, size_t cto
)
5883 Bindings::const_definitions_iterator p
=
5884 block
->bindings()->begin_definitions();
5885 for (size_t i
= 0; i
< cfrom
; ++i
)
5887 go_assert(p
!= block
->bindings()->end_definitions());
5890 go_assert(p
!= block
->bindings()->end_definitions());
5892 std::string n
= (*p
)->message_name();
5893 error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
5894 inform((*p
)->location(), "%qs defined here", n
.c_str());
5898 // Class Function_declaration.
5900 // Return the function descriptor.
5903 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
5905 go_assert(!this->fntype_
->is_method());
5906 if (this->descriptor_
== NULL
)
5907 this->descriptor_
= Expression::make_func_descriptor(no
);
5908 return this->descriptor_
;
5913 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
5914 bool is_parameter
, bool is_receiver
,
5916 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
5917 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
5918 is_closure_(false), is_receiver_(is_receiver
),
5919 is_varargs_parameter_(false), is_used_(false),
5920 is_address_taken_(false), is_non_escaping_address_taken_(false),
5921 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
5922 type_from_init_tuple_(false), type_from_range_index_(false),
5923 type_from_range_value_(false), type_from_chan_element_(false),
5924 is_type_switch_var_(false), determined_type_(false),
5925 in_unique_section_(false), escapes_(true)
5927 go_assert(type
!= NULL
|| init
!= NULL
);
5928 go_assert(!is_parameter
|| init
== NULL
);
5931 // Traverse the initializer expression.
5934 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
5936 if (this->preinit_
!= NULL
)
5938 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
5939 return TRAVERSE_EXIT
;
5941 if (this->init_
!= NULL
5943 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
5946 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
5947 return TRAVERSE_EXIT
;
5949 return TRAVERSE_CONTINUE
;
5952 // Lower the initialization expression after parsing is complete.
5955 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
5956 Statement_inserter
* inserter
)
5958 Named_object
* dep
= gogo
->var_depends_on(this);
5959 if (dep
!= NULL
&& dep
->is_variable())
5960 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
5962 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
5966 // We will give an error elsewhere, this is just to prevent
5967 // an infinite loop.
5972 Statement_inserter global_inserter
;
5973 if (this->is_global_
)
5975 global_inserter
= Statement_inserter(gogo
, this);
5976 inserter
= &global_inserter
;
5979 gogo
->lower_expression(function
, inserter
, &this->init_
);
5981 this->seen_
= false;
5983 this->init_is_lowered_
= true;
5987 // Flatten the initialization expression after ordering evaluations.
5990 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
5991 Statement_inserter
* inserter
)
5993 Named_object
* dep
= gogo
->var_depends_on(this);
5994 if (dep
!= NULL
&& dep
->is_variable())
5995 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
5997 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
6001 // We will give an error elsewhere, this is just to prevent
6002 // an infinite loop.
6007 Statement_inserter global_inserter
;
6008 if (this->is_global_
)
6010 global_inserter
= Statement_inserter(gogo
, this);
6011 inserter
= &global_inserter
;
6014 gogo
->flatten_expression(function
, inserter
, &this->init_
);
6016 // If an interface conversion is needed, we need a temporary
6018 if (this->type_
!= NULL
6019 && !Type::are_identical(this->type_
, this->init_
->type(), false,
6021 && this->init_
->type()->interface_type() != NULL
6022 && !this->init_
->is_variable())
6024 Temporary_statement
* temp
=
6025 Statement::make_temporary(NULL
, this->init_
, this->location_
);
6026 inserter
->insert(temp
);
6027 this->init_
= Expression::make_temporary_reference(temp
,
6031 this->seen_
= false;
6032 this->init_is_flattened_
= true;
6036 // Get the preinit block.
6039 Variable::preinit_block(Gogo
* gogo
)
6041 go_assert(this->is_global_
);
6042 if (this->preinit_
== NULL
)
6043 this->preinit_
= new Block(NULL
, this->location());
6045 // If a global variable has a preinitialization statement, then we
6046 // need to have an initialization function.
6047 gogo
->set_need_init_fn();
6049 return this->preinit_
;
6052 // Add a statement to be run before the initialization expression.
6055 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
6057 Block
* b
= this->preinit_block(gogo
);
6058 b
->add_statement(s
);
6059 b
->set_end_location(s
->location());
6062 // Whether this variable has a type.
6065 Variable::has_type() const
6067 if (this->type_
== NULL
)
6070 // A variable created in a type switch case nil does not actually
6071 // have a type yet. It will be changed to use the initializer's
6072 // type in determine_type.
6073 if (this->is_type_switch_var_
6074 && this->type_
->is_nil_constant_as_type())
6080 // In an assignment which sets a variable to a tuple of EXPR, return
6081 // the type of the first element of the tuple.
6084 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
6086 if (expr
->map_index_expression() != NULL
)
6088 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
6090 return Type::make_error_type();
6091 return mt
->val_type();
6093 else if (expr
->receive_expression() != NULL
)
6095 Expression
* channel
= expr
->receive_expression()->channel();
6096 Type
* channel_type
= channel
->type();
6097 if (channel_type
->channel_type() == NULL
)
6098 return Type::make_error_type();
6099 return channel_type
->channel_type()->element_type();
6104 error_at(this->location(), "invalid tuple definition");
6105 return Type::make_error_type();
6109 // Given EXPR used in a range clause, return either the index type or
6110 // the value type of the range, depending upon GET_INDEX_TYPE.
6113 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
6114 bool report_error
) const
6116 Type
* t
= expr
->type();
6117 if (t
->array_type() != NULL
6118 || (t
->points_to() != NULL
6119 && t
->points_to()->array_type() != NULL
6120 && !t
->points_to()->is_slice_type()))
6123 return Type::lookup_integer_type("int");
6125 return t
->deref()->array_type()->element_type();
6127 else if (t
->is_string_type())
6130 return Type::lookup_integer_type("int");
6132 return Type::lookup_integer_type("int32");
6134 else if (t
->map_type() != NULL
)
6137 return t
->map_type()->key_type();
6139 return t
->map_type()->val_type();
6141 else if (t
->channel_type() != NULL
)
6144 return t
->channel_type()->element_type();
6148 error_at(this->location(),
6149 "invalid definition of value variable for channel range");
6150 return Type::make_error_type();
6156 error_at(this->location(), "invalid type for range clause");
6157 return Type::make_error_type();
6161 // EXPR should be a channel. Return the channel's element type.
6164 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
6166 Type
* t
= expr
->type();
6167 if (t
->channel_type() != NULL
)
6168 return t
->channel_type()->element_type();
6172 error_at(this->location(), "expected channel");
6173 return Type::make_error_type();
6177 // Return the type of the Variable. This may be called before
6178 // Variable::determine_type is called, which means that we may need to
6179 // get the type from the initializer. FIXME: If we combine lowering
6180 // with type determination, then this should be unnecessary.
6185 // A variable in a type switch with a nil case will have the wrong
6186 // type here. This gets fixed up in determine_type, below.
6187 Type
* type
= this->type_
;
6188 Expression
* init
= this->init_
;
6189 if (this->is_type_switch_var_
6191 && this->type_
->is_nil_constant_as_type())
6193 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6194 go_assert(tge
!= NULL
);
6201 if (this->type_
== NULL
|| !this->type_
->is_error_type())
6203 error_at(this->location_
, "variable initializer refers to itself");
6204 this->type_
= Type::make_error_type();
6213 else if (this->type_from_init_tuple_
)
6214 type
= this->type_from_tuple(init
, false);
6215 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6216 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
6217 else if (this->type_from_chan_element_
)
6218 type
= this->type_from_chan_element(init
, false);
6221 go_assert(init
!= NULL
);
6222 type
= init
->type();
6223 go_assert(type
!= NULL
);
6225 // Variables should not have abstract types.
6226 if (type
->is_abstract())
6227 type
= type
->make_non_abstract_type();
6229 if (type
->is_void_type())
6230 type
= Type::make_error_type();
6233 this->seen_
= false;
6238 // Fetch the type from a const pointer, in which case it should have
6239 // been set already.
6242 Variable::type() const
6244 go_assert(this->type_
!= NULL
);
6248 // Set the type if necessary.
6251 Variable::determine_type()
6253 if (this->determined_type_
)
6255 this->determined_type_
= true;
6257 if (this->preinit_
!= NULL
)
6258 this->preinit_
->determine_types();
6260 // A variable in a type switch with a nil case will have the wrong
6261 // type here. It will have an initializer which is a type guard.
6262 // We want to initialize it to the value without the type guard, and
6263 // use the type of that value as well.
6264 if (this->is_type_switch_var_
6265 && this->type_
!= NULL
6266 && this->type_
->is_nil_constant_as_type())
6268 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6269 go_assert(tge
!= NULL
);
6271 this->init_
= tge
->expr();
6274 if (this->init_
== NULL
)
6275 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
6276 else if (this->type_from_init_tuple_
)
6278 Expression
*init
= this->init_
;
6279 init
->determine_type_no_context();
6280 this->type_
= this->type_from_tuple(init
, true);
6283 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6285 Expression
* init
= this->init_
;
6286 init
->determine_type_no_context();
6287 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
6291 else if (this->type_from_chan_element_
)
6293 Expression
* init
= this->init_
;
6294 init
->determine_type_no_context();
6295 this->type_
= this->type_from_chan_element(init
, true);
6300 Type_context
context(this->type_
, false);
6301 this->init_
->determine_type(&context
);
6302 if (this->type_
== NULL
)
6304 Type
* type
= this->init_
->type();
6305 go_assert(type
!= NULL
);
6306 if (type
->is_abstract())
6307 type
= type
->make_non_abstract_type();
6309 if (type
->is_void_type())
6311 error_at(this->location_
, "variable has no type");
6312 type
= Type::make_error_type();
6314 else if (type
->is_nil_type())
6316 error_at(this->location_
, "variable defined to nil type");
6317 type
= Type::make_error_type();
6319 else if (type
->is_call_multiple_result_type())
6321 error_at(this->location_
,
6322 "single variable set to multiple-value function call");
6323 type
= Type::make_error_type();
6331 // Get the initial value of a variable. This does not
6332 // consider whether the variable is in the heap--it returns the
6333 // initial value as though it were always stored in the stack.
6336 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
6338 go_assert(this->preinit_
== NULL
);
6339 Location loc
= this->location();
6340 if (this->init_
== NULL
)
6342 go_assert(!this->is_parameter_
);
6343 if (this->is_global_
|| this->is_in_heap())
6345 Btype
* btype
= this->type()->get_backend(gogo
);
6346 return gogo
->backend()->zero_expression(btype
);
6350 Translate_context
context(gogo
, function
, NULL
, NULL
);
6351 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
6352 return init
->get_backend(&context
);
6356 // Get the initial value of a variable when a block is required.
6357 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6360 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
6361 Bvariable
* var_decl
)
6363 go_assert(this->preinit_
!= NULL
);
6365 // We want to add the variable assignment to the end of the preinit
6368 Translate_context
context(gogo
, function
, NULL
, NULL
);
6369 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
6371 // It's possible to have pre-init statements without an initializer
6372 // if the pre-init statements set the variable.
6373 Bstatement
* decl_init
= NULL
;
6374 if (this->init_
!= NULL
)
6376 if (var_decl
== NULL
)
6378 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
6379 decl_init
= gogo
->backend()->expression_statement(init_bexpr
);
6383 Location loc
= this->location();
6384 Expression
* val_expr
=
6385 Expression::make_cast(this->type(), this->init_
, loc
);
6386 Bexpression
* val
= val_expr
->get_backend(&context
);
6387 Bexpression
* var_ref
= gogo
->backend()->var_expression(var_decl
, loc
);
6388 decl_init
= gogo
->backend()->assignment_statement(var_ref
, val
, loc
);
6391 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
6392 if (decl_init
!= NULL
)
6393 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
6397 // Export the variable
6400 Variable::export_var(Export
* exp
, const std::string
& name
) const
6402 go_assert(this->is_global_
);
6403 exp
->write_c_string("var ");
6404 exp
->write_string(name
);
6405 exp
->write_c_string(" ");
6406 exp
->write_type(this->type());
6407 exp
->write_c_string(";\n");
6410 // Import a variable.
6413 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
6415 imp
->require_c_string("var ");
6416 *pname
= imp
->read_identifier();
6417 imp
->require_c_string(" ");
6418 *ptype
= imp
->read_type();
6419 imp
->require_c_string(";\n");
6422 // Convert a variable to the backend representation.
6425 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6426 const Package
* package
, const std::string
& name
)
6428 if (this->backend_
== NULL
)
6430 Backend
* backend
= gogo
->backend();
6431 Type
* type
= this->type_
;
6432 if (type
->is_error_type()
6433 || (type
->is_undefined()
6434 && (!this->is_global_
|| package
== NULL
)))
6435 this->backend_
= backend
->error_variable();
6438 bool is_parameter
= this->is_parameter_
;
6439 if (this->is_receiver_
&& type
->points_to() == NULL
)
6440 is_parameter
= false;
6441 if (this->is_in_heap())
6443 is_parameter
= false;
6444 type
= Type::make_pointer_type(type
);
6447 std::string n
= Gogo::unpack_hidden_name(name
);
6448 Btype
* btype
= type
->get_backend(gogo
);
6451 if (gogo
->is_zero_value(this))
6452 bvar
= gogo
->backend_zero_value();
6453 else if (this->is_global_
)
6454 bvar
= backend
->global_variable((package
== NULL
6455 ? gogo
->package_name()
6456 : package
->package_name()),
6458 ? gogo
->pkgpath_symbol()
6459 : package
->pkgpath_symbol()),
6463 Gogo::is_hidden_name(name
),
6464 this->in_unique_section_
,
6466 else if (function
== NULL
)
6468 go_assert(saw_errors());
6469 bvar
= backend
->error_variable();
6473 Bfunction
* bfunction
= function
->func_value()->get_decl();
6474 bool is_address_taken
= (this->is_non_escaping_address_taken_
6475 && !this->is_in_heap());
6476 if (this->is_closure())
6477 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
6479 else if (is_parameter
)
6480 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
6484 bvar
= backend
->local_variable(bfunction
, n
, btype
,
6488 this->backend_
= bvar
;
6491 return this->backend_
;
6494 // Class Result_variable.
6496 // Convert a result variable to the backend representation.
6499 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6500 const std::string
& name
)
6502 if (this->backend_
== NULL
)
6504 Backend
* backend
= gogo
->backend();
6505 Type
* type
= this->type_
;
6506 if (type
->is_error())
6507 this->backend_
= backend
->error_variable();
6510 if (this->is_in_heap())
6511 type
= Type::make_pointer_type(type
);
6512 Btype
* btype
= type
->get_backend(gogo
);
6513 Bfunction
* bfunction
= function
->func_value()->get_decl();
6514 std::string n
= Gogo::unpack_hidden_name(name
);
6515 bool is_address_taken
= (this->is_non_escaping_address_taken_
6516 && !this->is_in_heap());
6517 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
6522 return this->backend_
;
6525 // Class Named_constant.
6527 // Traverse the initializer expression.
6530 Named_constant::traverse_expression(Traverse
* traverse
)
6532 return Expression::traverse(&this->expr_
, traverse
);
6535 // Determine the type of the constant.
6538 Named_constant::determine_type()
6540 if (this->type_
!= NULL
)
6542 Type_context
context(this->type_
, false);
6543 this->expr_
->determine_type(&context
);
6547 // A constant may have an abstract type.
6548 Type_context
context(NULL
, true);
6549 this->expr_
->determine_type(&context
);
6550 this->type_
= this->expr_
->type();
6551 go_assert(this->type_
!= NULL
);
6555 // Indicate that we found and reported an error for this constant.
6558 Named_constant::set_error()
6560 this->type_
= Type::make_error_type();
6561 this->expr_
= Expression::make_error(this->location_
);
6564 // Export a constant.
6567 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
6569 exp
->write_c_string("const ");
6570 exp
->write_string(name
);
6571 exp
->write_c_string(" ");
6572 if (!this->type_
->is_abstract())
6574 exp
->write_type(this->type_
);
6575 exp
->write_c_string(" ");
6577 exp
->write_c_string("= ");
6578 this->expr()->export_expression(exp
);
6579 exp
->write_c_string(";\n");
6582 // Import a constant.
6585 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
6588 imp
->require_c_string("const ");
6589 *pname
= imp
->read_identifier();
6590 imp
->require_c_string(" ");
6591 if (imp
->peek_char() == '=')
6595 *ptype
= imp
->read_type();
6596 imp
->require_c_string(" ");
6598 imp
->require_c_string("= ");
6599 *pexpr
= Expression::import_expression(imp
);
6600 imp
->require_c_string(";\n");
6603 // Get the backend representation.
6606 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
6608 if (this->bconst_
== NULL
)
6610 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
6611 Type
* type
= this->type();
6612 Location loc
= this->location();
6614 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
6615 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
6616 if (type
!= NULL
&& type
->is_numeric_type())
6618 Btype
* btype
= type
->get_backend(gogo
);
6619 std::string name
= const_no
->get_id(gogo
);
6621 gogo
->backend()->named_constant_expression(btype
, name
,
6624 this->bconst_
= const_decl
;
6626 return this->bconst_
;
6632 Type_declaration::add_method(const std::string
& name
, Function
* function
)
6634 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
6635 this->methods_
.push_back(ret
);
6639 // Add a method declaration.
6642 Type_declaration::add_method_declaration(const std::string
& name
,
6644 Function_type
* type
,
6647 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
6649 this->methods_
.push_back(ret
);
6653 // Return whether any methods ere defined.
6656 Type_declaration::has_methods() const
6658 return !this->methods_
.empty();
6661 // Define methods for the real type.
6664 Type_declaration::define_methods(Named_type
* nt
)
6666 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
6667 p
!= this->methods_
.end();
6669 nt
->add_existing_method(*p
);
6672 // We are using the type. Return true if we should issue a warning.
6675 Type_declaration::using_type()
6677 bool ret
= !this->issued_warning_
;
6678 this->issued_warning_
= true;
6682 // Class Unknown_name.
6684 // Set the real named object.
6687 Unknown_name::set_real_named_object(Named_object
* no
)
6689 go_assert(this->real_named_object_
== NULL
);
6690 go_assert(!no
->is_unknown());
6691 this->real_named_object_
= no
;
6694 // Class Named_object.
6696 Named_object::Named_object(const std::string
& name
,
6697 const Package
* package
,
6698 Classification classification
)
6699 : name_(name
), package_(package
), classification_(classification
)
6701 if (Gogo::is_sink_name(name
))
6702 go_assert(classification
== NAMED_OBJECT_SINK
);
6705 // Make an unknown name. This is used by the parser. The name must
6706 // be resolved later. Unknown names are only added in the current
6710 Named_object::make_unknown_name(const std::string
& name
,
6713 Named_object
* named_object
= new Named_object(name
, NULL
,
6714 NAMED_OBJECT_UNKNOWN
);
6715 Unknown_name
* value
= new Unknown_name(location
);
6716 named_object
->u_
.unknown_value
= value
;
6717 return named_object
;
6723 Named_object::make_constant(const Typed_identifier
& tid
,
6724 const Package
* package
, Expression
* expr
,
6727 Named_object
* named_object
= new Named_object(tid
.name(), package
,
6728 NAMED_OBJECT_CONST
);
6729 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
6732 named_object
->u_
.const_value
= named_constant
;
6733 return named_object
;
6736 // Make a named type.
6739 Named_object::make_type(const std::string
& name
, const Package
* package
,
6740 Type
* type
, Location location
)
6742 Named_object
* named_object
= new Named_object(name
, package
,
6744 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
6745 named_object
->u_
.type_value
= named_type
;
6746 return named_object
;
6749 // Make a type declaration.
6752 Named_object::make_type_declaration(const std::string
& name
,
6753 const Package
* package
,
6756 Named_object
* named_object
= new Named_object(name
, package
,
6757 NAMED_OBJECT_TYPE_DECLARATION
);
6758 Type_declaration
* type_declaration
= new Type_declaration(location
);
6759 named_object
->u_
.type_declaration
= type_declaration
;
6760 return named_object
;
6766 Named_object::make_variable(const std::string
& name
, const Package
* package
,
6769 Named_object
* named_object
= new Named_object(name
, package
,
6771 named_object
->u_
.var_value
= variable
;
6772 return named_object
;
6775 // Make a result variable.
6778 Named_object::make_result_variable(const std::string
& name
,
6779 Result_variable
* result
)
6781 Named_object
* named_object
= new Named_object(name
, NULL
,
6782 NAMED_OBJECT_RESULT_VAR
);
6783 named_object
->u_
.result_var_value
= result
;
6784 return named_object
;
6787 // Make a sink. This is used for the special blank identifier _.
6790 Named_object::make_sink()
6792 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
6795 // Make a named function.
6798 Named_object::make_function(const std::string
& name
, const Package
* package
,
6801 Named_object
* named_object
= new Named_object(name
, package
,
6803 named_object
->u_
.func_value
= function
;
6804 return named_object
;
6807 // Make a function declaration.
6810 Named_object::make_function_declaration(const std::string
& name
,
6811 const Package
* package
,
6812 Function_type
* fntype
,
6815 Named_object
* named_object
= new Named_object(name
, package
,
6816 NAMED_OBJECT_FUNC_DECLARATION
);
6817 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
6818 named_object
->u_
.func_declaration_value
= func_decl
;
6819 return named_object
;
6825 Named_object::make_package(const std::string
& alias
, Package
* package
)
6827 Named_object
* named_object
= new Named_object(alias
, NULL
,
6828 NAMED_OBJECT_PACKAGE
);
6829 named_object
->u_
.package_value
= package
;
6830 return named_object
;
6833 // Return the name to use in an error message.
6836 Named_object::message_name() const
6838 if (this->package_
== NULL
)
6839 return Gogo::message_name(this->name_
);
6841 if (this->package_
->has_package_name())
6842 ret
= this->package_
->package_name();
6844 ret
= this->package_
->pkgpath();
6845 ret
= Gogo::message_name(ret
);
6847 ret
+= Gogo::message_name(this->name_
);
6851 // Set the type when a declaration is defined.
6854 Named_object::set_type_value(Named_type
* named_type
)
6856 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
6857 Type_declaration
* td
= this->u_
.type_declaration
;
6858 td
->define_methods(named_type
);
6860 Named_object
* in_function
= td
->in_function(&index
);
6861 if (in_function
!= NULL
)
6862 named_type
->set_in_function(in_function
, index
);
6864 this->classification_
= NAMED_OBJECT_TYPE
;
6865 this->u_
.type_value
= named_type
;
6868 // Define a function which was previously declared.
6871 Named_object::set_function_value(Function
* function
)
6873 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
6874 if (this->func_declaration_value()->has_descriptor())
6876 Expression
* descriptor
=
6877 this->func_declaration_value()->descriptor(NULL
, NULL
);
6878 function
->set_descriptor(descriptor
);
6880 this->classification_
= NAMED_OBJECT_FUNC
;
6881 // FIXME: We should free the old value.
6882 this->u_
.func_value
= function
;
6885 // Declare an unknown object as a type declaration.
6888 Named_object::declare_as_type()
6890 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
6891 Unknown_name
* unk
= this->u_
.unknown_value
;
6892 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
6893 this->u_
.type_declaration
= new Type_declaration(unk
->location());
6897 // Return the location of a named object.
6900 Named_object::location() const
6902 switch (this->classification_
)
6905 case NAMED_OBJECT_UNINITIALIZED
:
6908 case NAMED_OBJECT_ERRONEOUS
:
6909 return Linemap::unknown_location();
6911 case NAMED_OBJECT_UNKNOWN
:
6912 return this->unknown_value()->location();
6914 case NAMED_OBJECT_CONST
:
6915 return this->const_value()->location();
6917 case NAMED_OBJECT_TYPE
:
6918 return this->type_value()->location();
6920 case NAMED_OBJECT_TYPE_DECLARATION
:
6921 return this->type_declaration_value()->location();
6923 case NAMED_OBJECT_VAR
:
6924 return this->var_value()->location();
6926 case NAMED_OBJECT_RESULT_VAR
:
6927 return this->result_var_value()->location();
6929 case NAMED_OBJECT_SINK
:
6932 case NAMED_OBJECT_FUNC
:
6933 return this->func_value()->location();
6935 case NAMED_OBJECT_FUNC_DECLARATION
:
6936 return this->func_declaration_value()->location();
6938 case NAMED_OBJECT_PACKAGE
:
6939 return this->package_value()->location();
6943 // Export a named object.
6946 Named_object::export_named_object(Export
* exp
) const
6948 switch (this->classification_
)
6951 case NAMED_OBJECT_UNINITIALIZED
:
6952 case NAMED_OBJECT_UNKNOWN
:
6955 case NAMED_OBJECT_ERRONEOUS
:
6958 case NAMED_OBJECT_CONST
:
6959 this->const_value()->export_const(exp
, this->name_
);
6962 case NAMED_OBJECT_TYPE
:
6963 this->type_value()->export_named_type(exp
, this->name_
);
6966 case NAMED_OBJECT_TYPE_DECLARATION
:
6967 error_at(this->type_declaration_value()->location(),
6968 "attempt to export %<%s%> which was declared but not defined",
6969 this->message_name().c_str());
6972 case NAMED_OBJECT_FUNC_DECLARATION
:
6973 this->func_declaration_value()->export_func(exp
, this->name_
);
6976 case NAMED_OBJECT_VAR
:
6977 this->var_value()->export_var(exp
, this->name_
);
6980 case NAMED_OBJECT_RESULT_VAR
:
6981 case NAMED_OBJECT_SINK
:
6984 case NAMED_OBJECT_FUNC
:
6985 this->func_value()->export_func(exp
, this->name_
);
6990 // Convert a variable to the backend representation.
6993 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
6995 if (this->classification_
== NAMED_OBJECT_VAR
)
6996 return this->var_value()->get_backend_variable(gogo
, function
,
6997 this->package_
, this->name_
);
6998 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
6999 return this->result_var_value()->get_backend_variable(gogo
, function
,
7006 // Return the external identifier for this object.
7009 Named_object::get_id(Gogo
* gogo
)
7011 go_assert(!this->is_variable() && !this->is_result_variable());
7012 std::string decl_name
;
7013 if (this->is_function_declaration()
7014 && !this->func_declaration_value()->asm_name().empty())
7015 decl_name
= this->func_declaration_value()->asm_name();
7016 else if (this->is_type()
7017 && Linemap::is_predeclared_location(this->type_value()->location()))
7019 // We don't need the package name for builtin types.
7020 decl_name
= Gogo::unpack_hidden_name(this->name_
);
7024 std::string package_name
;
7025 if (this->package_
== NULL
)
7026 package_name
= gogo
->package_name();
7028 package_name
= this->package_
->package_name();
7030 // Note that this will be misleading if this is an unexported
7031 // method generated for an embedded imported type. In that case
7032 // the unexported method should have the package name of the
7033 // package from which it is imported, but we are going to give
7034 // it our package name. Fixing this would require knowing the
7035 // package name, but we only know the package path. It might be
7036 // better to use package paths here anyhow. This doesn't affect
7037 // the assembler code, because we always set that name in
7038 // Function::get_or_make_decl anyhow. FIXME.
7040 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
7042 Function_type
* fntype
;
7043 if (this->is_function())
7044 fntype
= this->func_value()->type();
7045 else if (this->is_function_declaration())
7046 fntype
= this->func_declaration_value()->type();
7049 if (fntype
!= NULL
&& fntype
->is_method())
7051 decl_name
.push_back('.');
7052 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
7055 if (this->is_type())
7058 const Named_object
* in_function
= this->type_value()->in_function(&index
);
7059 if (in_function
!= NULL
)
7061 decl_name
+= '$' + Gogo::unpack_hidden_name(in_function
->name());
7065 snprintf(buf
, sizeof buf
, "%u", index
);
7074 // Get the backend representation for this named object.
7077 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
7078 std::vector
<Btype
*>& type_decls
,
7079 std::vector
<Bfunction
*>& func_decls
)
7081 switch (this->classification_
)
7083 case NAMED_OBJECT_CONST
:
7084 if (!Gogo::is_erroneous_name(this->name_
))
7085 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
7088 case NAMED_OBJECT_TYPE
:
7090 Named_type
* named_type
= this->u_
.type_value
;
7091 if (!Gogo::is_erroneous_name(this->name_
))
7092 type_decls
.push_back(named_type
->get_backend(gogo
));
7094 // We need to produce a type descriptor for every named
7095 // type, and for a pointer to every named type, since
7096 // other files or packages might refer to them. We need
7097 // to do this even for hidden types, because they might
7098 // still be returned by some function. Simply calling the
7099 // type_descriptor method is enough to create the type
7100 // descriptor, even though we don't do anything with it.
7101 if (this->package_
== NULL
)
7104 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7105 named_type
->gc_symbol_pointer(gogo
);
7106 Type
* pn
= Type::make_pointer_type(named_type
);
7107 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7108 pn
->gc_symbol_pointer(gogo
);
7113 case NAMED_OBJECT_TYPE_DECLARATION
:
7114 error("reference to undefined type %qs",
7115 this->message_name().c_str());
7118 case NAMED_OBJECT_VAR
:
7119 case NAMED_OBJECT_RESULT_VAR
:
7120 case NAMED_OBJECT_SINK
:
7123 case NAMED_OBJECT_FUNC
:
7125 Function
* func
= this->u_
.func_value
;
7126 if (!Gogo::is_erroneous_name(this->name_
))
7127 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
7129 if (func
->block() != NULL
)
7130 func
->build(gogo
, this);
7134 case NAMED_OBJECT_ERRONEOUS
:
7144 Bindings::Bindings(Bindings
* enclosing
)
7145 : enclosing_(enclosing
), named_objects_(), bindings_()
7152 Bindings::clear_file_scope(Gogo
* gogo
)
7154 Contour::iterator p
= this->bindings_
.begin();
7155 while (p
!= this->bindings_
.end())
7158 if (p
->second
->package() != NULL
)
7160 else if (p
->second
->is_package())
7162 else if (p
->second
->is_function()
7163 && !p
->second
->func_value()->type()->is_method()
7164 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
7173 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
7174 p
= this->bindings_
.erase(p
);
7179 // Look up a symbol.
7182 Bindings::lookup(const std::string
& name
) const
7184 Contour::const_iterator p
= this->bindings_
.find(name
);
7185 if (p
!= this->bindings_
.end())
7186 return p
->second
->resolve();
7187 else if (this->enclosing_
!= NULL
)
7188 return this->enclosing_
->lookup(name
);
7193 // Look up a symbol locally.
7196 Bindings::lookup_local(const std::string
& name
) const
7198 Contour::const_iterator p
= this->bindings_
.find(name
);
7199 if (p
== this->bindings_
.end())
7204 // Remove an object from a set of bindings. This is used for a
7205 // special case in thunks for functions which call recover.
7208 Bindings::remove_binding(Named_object
* no
)
7210 Contour::iterator pb
= this->bindings_
.find(no
->name());
7211 go_assert(pb
!= this->bindings_
.end());
7212 this->bindings_
.erase(pb
);
7213 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
7214 pn
!= this->named_objects_
.end();
7219 this->named_objects_
.erase(pn
);
7226 // Add a method to the list of objects. This is not added to the
7227 // lookup table. This is so that we have a single list of objects
7228 // declared at the top level, which we walk through when it's time to
7229 // convert to trees.
7232 Bindings::add_method(Named_object
* method
)
7234 this->named_objects_
.push_back(method
);
7237 // Add a generic Named_object to a Contour.
7240 Bindings::add_named_object_to_contour(Contour
* contour
,
7241 Named_object
* named_object
)
7243 go_assert(named_object
== named_object
->resolve());
7244 const std::string
& name(named_object
->name());
7245 go_assert(!Gogo::is_sink_name(name
));
7247 std::pair
<Contour::iterator
, bool> ins
=
7248 contour
->insert(std::make_pair(name
, named_object
));
7251 // The name was already there.
7252 if (named_object
->package() != NULL
7253 && ins
.first
->second
->package() == named_object
->package()
7254 && (ins
.first
->second
->classification()
7255 == named_object
->classification()))
7257 // This is a second import of the same object.
7258 return ins
.first
->second
;
7260 ins
.first
->second
= this->new_definition(ins
.first
->second
,
7262 return ins
.first
->second
;
7266 // Don't push declarations on the list. We push them on when
7267 // and if we find the definitions. That way we genericize the
7268 // functions in order.
7269 if (!named_object
->is_type_declaration()
7270 && !named_object
->is_function_declaration()
7271 && !named_object
->is_unknown())
7272 this->named_objects_
.push_back(named_object
);
7273 return named_object
;
7277 // We had an existing named object OLD_OBJECT, and we've seen a new
7278 // one NEW_OBJECT with the same name. FIXME: This does not free the
7279 // new object when we don't need it.
7282 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
7284 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
7288 switch (old_object
->classification())
7291 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
7294 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7297 case Named_object::NAMED_OBJECT_UNKNOWN
:
7299 Named_object
* real
= old_object
->unknown_value()->real_named_object();
7301 return this->new_definition(real
, new_object
);
7302 go_assert(!new_object
->is_unknown());
7303 old_object
->unknown_value()->set_real_named_object(new_object
);
7304 if (!new_object
->is_type_declaration()
7305 && !new_object
->is_function_declaration())
7306 this->named_objects_
.push_back(new_object
);
7310 case Named_object::NAMED_OBJECT_CONST
:
7313 case Named_object::NAMED_OBJECT_TYPE
:
7314 if (new_object
->is_type_declaration())
7318 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7319 if (new_object
->is_type_declaration())
7321 if (new_object
->is_type())
7323 old_object
->set_type_value(new_object
->type_value());
7324 new_object
->type_value()->set_named_object(old_object
);
7325 this->named_objects_
.push_back(old_object
);
7330 case Named_object::NAMED_OBJECT_VAR
:
7331 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7332 // We have already given an error in the parser for cases where
7333 // one parameter or result variable redeclares another one.
7334 if ((new_object
->is_variable()
7335 && new_object
->var_value()->is_parameter())
7336 || new_object
->is_result_variable())
7340 case Named_object::NAMED_OBJECT_SINK
:
7343 case Named_object::NAMED_OBJECT_FUNC
:
7344 if (new_object
->is_function_declaration())
7346 if (!new_object
->func_declaration_value()->asm_name().empty())
7347 sorry("__asm__ for function definitions");
7348 Function_type
* old_type
= old_object
->func_value()->type();
7349 Function_type
* new_type
=
7350 new_object
->func_declaration_value()->type();
7351 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7356 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7358 Function_type
* old_type
= old_object
->func_declaration_value()->type();
7359 if (new_object
->is_function_declaration())
7361 Function_type
* new_type
=
7362 new_object
->func_declaration_value()->type();
7363 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7366 if (new_object
->is_function())
7368 Function_type
* new_type
= new_object
->func_value()->type();
7369 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7371 if (!old_object
->func_declaration_value()->asm_name().empty())
7372 sorry("__asm__ for function definitions");
7373 old_object
->set_function_value(new_object
->func_value());
7374 this->named_objects_
.push_back(old_object
);
7381 case Named_object::NAMED_OBJECT_PACKAGE
:
7385 std::string n
= old_object
->message_name();
7387 error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
7389 error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
7392 inform(old_object
->location(), "previous definition of %qs was here",
7398 // Add a named type.
7401 Bindings::add_named_type(Named_type
* named_type
)
7403 return this->add_named_object(named_type
->named_object());
7409 Bindings::add_function(const std::string
& name
, const Package
* package
,
7412 return this->add_named_object(Named_object::make_function(name
, package
,
7416 // Add a function declaration.
7419 Bindings::add_function_declaration(const std::string
& name
,
7420 const Package
* package
,
7421 Function_type
* type
,
7424 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
7426 return this->add_named_object(no
);
7429 // Define a type which was previously declared.
7432 Bindings::define_type(Named_object
* no
, Named_type
* type
)
7434 no
->set_type_value(type
);
7435 this->named_objects_
.push_back(no
);
7438 // Mark all local variables as used. This is used for some types of
7442 Bindings::mark_locals_used()
7444 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
7445 p
!= this->named_objects_
.end();
7447 if ((*p
)->is_variable())
7448 (*p
)->var_value()->set_is_used();
7451 // Traverse bindings.
7454 Bindings::traverse(Traverse
* traverse
, bool is_global
)
7456 unsigned int traverse_mask
= traverse
->traverse_mask();
7458 // We don't use an iterator because we permit the traversal to add
7459 // new global objects.
7460 const unsigned int e_or_t
= (Traverse::traverse_expressions
7461 | Traverse::traverse_types
);
7462 const unsigned int e_or_t_or_s
= (e_or_t
7463 | Traverse::traverse_statements
);
7464 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
7466 Named_object
* p
= this->named_objects_
[i
];
7467 int t
= TRAVERSE_CONTINUE
;
7468 switch (p
->classification())
7470 case Named_object::NAMED_OBJECT_CONST
:
7471 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
7472 t
= traverse
->constant(p
, is_global
);
7473 if (t
== TRAVERSE_CONTINUE
7474 && (traverse_mask
& e_or_t
) != 0)
7476 Type
* tc
= p
->const_value()->type();
7478 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
7479 return TRAVERSE_EXIT
;
7480 t
= p
->const_value()->traverse_expression(traverse
);
7484 case Named_object::NAMED_OBJECT_VAR
:
7485 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7486 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
7487 t
= traverse
->variable(p
);
7488 if (t
== TRAVERSE_CONTINUE
7489 && (traverse_mask
& e_or_t
) != 0)
7491 if (p
->is_result_variable()
7492 || p
->var_value()->has_type())
7494 Type
* tv
= (p
->is_variable()
7495 ? p
->var_value()->type()
7496 : p
->result_var_value()->type());
7498 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
7499 return TRAVERSE_EXIT
;
7502 if (t
== TRAVERSE_CONTINUE
7503 && (traverse_mask
& e_or_t_or_s
) != 0
7504 && p
->is_variable())
7505 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
7508 case Named_object::NAMED_OBJECT_FUNC
:
7509 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
7510 t
= traverse
->function(p
);
7512 if (t
== TRAVERSE_CONTINUE
7514 & (Traverse::traverse_variables
7515 | Traverse::traverse_constants
7516 | Traverse::traverse_functions
7517 | Traverse::traverse_blocks
7518 | Traverse::traverse_statements
7519 | Traverse::traverse_expressions
7520 | Traverse::traverse_types
)) != 0)
7521 t
= p
->func_value()->traverse(traverse
);
7524 case Named_object::NAMED_OBJECT_PACKAGE
:
7525 // These are traversed in Gogo::traverse.
7526 go_assert(is_global
);
7529 case Named_object::NAMED_OBJECT_TYPE
:
7530 if ((traverse_mask
& e_or_t
) != 0)
7531 t
= Type::traverse(p
->type_value(), traverse
);
7534 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7535 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7536 case Named_object::NAMED_OBJECT_UNKNOWN
:
7537 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7540 case Named_object::NAMED_OBJECT_SINK
:
7545 if (t
== TRAVERSE_EXIT
)
7546 return TRAVERSE_EXIT
;
7549 // If we need to traverse types, check the function declarations,
7550 // which have types. Also check any methods of a type declaration.
7551 if ((traverse_mask
& e_or_t
) != 0)
7553 for (Bindings::const_declarations_iterator p
=
7554 this->begin_declarations();
7555 p
!= this->end_declarations();
7558 if (p
->second
->is_function_declaration())
7560 if (Type::traverse(p
->second
->func_declaration_value()->type(),
7563 return TRAVERSE_EXIT
;
7565 else if (p
->second
->is_type_declaration())
7567 const std::vector
<Named_object
*>* methods
=
7568 p
->second
->type_declaration_value()->methods();
7569 for (std::vector
<Named_object
*>::const_iterator pm
=
7571 pm
!= methods
->end();
7574 Named_object
* no
= *pm
;
7576 if (no
->is_function())
7577 t
= no
->func_value()->type();
7578 else if (no
->is_function_declaration())
7579 t
= no
->func_declaration_value()->type();
7582 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
7583 return TRAVERSE_EXIT
;
7589 return TRAVERSE_CONTINUE
;
7594 // Clear any references to this label.
7599 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
7600 p
!= this->refs_
.end();
7603 this->refs_
.clear();
7606 // Get the backend representation for a label.
7609 Label::get_backend_label(Translate_context
* context
)
7611 if (this->blabel_
== NULL
)
7613 Function
* function
= context
->function()->func_value();
7614 Bfunction
* bfunction
= function
->get_decl();
7615 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
7618 return this->blabel_
;
7621 // Return an expression for the address of this label.
7624 Label::get_addr(Translate_context
* context
, Location location
)
7626 Blabel
* label
= this->get_backend_label(context
);
7627 return context
->backend()->label_address(label
, location
);
7630 // Return the dummy label that represents any instance of the blank label.
7633 Label::create_dummy_label()
7635 static Label
* dummy_label
;
7636 if (dummy_label
== NULL
)
7638 dummy_label
= new Label("_");
7639 dummy_label
->set_is_used();
7644 // Class Unnamed_label.
7646 // Get the backend representation for an unnamed label.
7649 Unnamed_label::get_blabel(Translate_context
* context
)
7651 if (this->blabel_
== NULL
)
7653 Function
* function
= context
->function()->func_value();
7654 Bfunction
* bfunction
= function
->get_decl();
7655 this->blabel_
= context
->backend()->label(bfunction
, "",
7658 return this->blabel_
;
7661 // Return a statement which defines this unnamed label.
7664 Unnamed_label::get_definition(Translate_context
* context
)
7666 Blabel
* blabel
= this->get_blabel(context
);
7667 return context
->backend()->label_definition_statement(blabel
);
7670 // Return a goto statement to this unnamed label.
7673 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
7675 Blabel
* blabel
= this->get_blabel(context
);
7676 return context
->backend()->goto_statement(blabel
, location
);
7681 Package::Package(const std::string
& pkgpath
,
7682 const std::string
& pkgpath_symbol
, Location location
)
7683 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
7684 package_name_(), bindings_(new Bindings(NULL
)), priority_(0),
7685 location_(location
), used_(false), is_imported_(false),
7686 uses_sink_alias_(false)
7688 go_assert(!pkgpath
.empty());
7692 // Set the package name.
7695 Package::set_package_name(const std::string
& package_name
, Location location
)
7697 go_assert(!package_name
.empty());
7698 if (this->package_name_
.empty())
7699 this->package_name_
= package_name
;
7700 else if (this->package_name_
!= package_name
)
7702 "saw two different packages with the same package path %s: %s, %s",
7703 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
7704 package_name
.c_str());
7707 // Return the pkgpath symbol, which is a prefix for symbols defined in
7711 Package::pkgpath_symbol() const
7713 if (this->pkgpath_symbol_
.empty())
7714 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
7715 return this->pkgpath_symbol_
;
7718 // Set the package path symbol.
7721 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
7723 go_assert(!pkgpath_symbol
.empty());
7724 if (this->pkgpath_symbol_
.empty())
7725 this->pkgpath_symbol_
= pkgpath_symbol
;
7727 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
7730 // Set the priority. We may see multiple priorities for an imported
7731 // package; we want to use the largest one.
7734 Package::set_priority(int priority
)
7736 if (priority
> this->priority_
)
7737 this->priority_
= priority
;
7740 // Forget a given usage. If forgetting this usage means this package becomes
7741 // unused, report that error.
7744 Package::forget_usage(Expression
* usage
) const
7746 if (this->fake_uses_
.empty())
7749 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
7750 go_assert(p
!= this->fake_uses_
.end());
7751 this->fake_uses_
.erase(p
);
7753 if (this->fake_uses_
.empty())
7754 error_at(this->location(), "imported and not used: %s",
7755 Gogo::message_name(this->package_name()).c_str());
7758 // Clear the used field for the next file. If the only usages of this package
7759 // are possibly fake, keep the fake usages for lowering.
7762 Package::clear_used()
7764 if (this->used_
> this->fake_uses_
.size())
7765 this->fake_uses_
.clear();
7770 // Determine types of constants. Everything else in a package
7771 // (variables, function declarations) should already have a fixed
7772 // type. Constants may have abstract types.
7775 Package::determine_types()
7777 Bindings
* bindings
= this->bindings_
;
7778 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
7779 p
!= bindings
->end_definitions();
7782 if ((*p
)->is_const())
7783 (*p
)->const_value()->determine_type();
7791 Traverse::~Traverse()
7793 if (this->types_seen_
!= NULL
)
7794 delete this->types_seen_
;
7795 if (this->expressions_seen_
!= NULL
)
7796 delete this->expressions_seen_
;
7799 // Record that we are looking at a type, and return true if we have
7803 Traverse::remember_type(const Type
* type
)
7805 if (type
->is_error_type())
7807 go_assert((this->traverse_mask() & traverse_types
) != 0
7808 || (this->traverse_mask() & traverse_expressions
) != 0);
7809 // We mostly only have to remember named types. But it turns out
7810 // that an interface type can refer to itself without using a name
7811 // by relying on interface inheritance, as in
7812 // type I interface { F() interface{I} }
7813 if (type
->classification() != Type::TYPE_NAMED
7814 && type
->classification() != Type::TYPE_INTERFACE
)
7816 if (this->types_seen_
== NULL
)
7817 this->types_seen_
= new Types_seen();
7818 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
7822 // Record that we are looking at an expression, and return true if we
7823 // have already seen it.
7826 Traverse::remember_expression(const Expression
* expression
)
7828 go_assert((this->traverse_mask() & traverse_types
) != 0
7829 || (this->traverse_mask() & traverse_expressions
) != 0);
7830 if (this->expressions_seen_
== NULL
)
7831 this->expressions_seen_
= new Expressions_seen();
7832 std::pair
<Expressions_seen::iterator
, bool> ins
=
7833 this->expressions_seen_
->insert(expression
);
7837 // The default versions of these functions should never be called: the
7838 // traversal mask indicates which functions may be called.
7841 Traverse::variable(Named_object
*)
7847 Traverse::constant(Named_object
*, bool)
7853 Traverse::function(Named_object
*)
7859 Traverse::block(Block
*)
7865 Traverse::statement(Block
*, size_t*, Statement
*)
7871 Traverse::expression(Expression
**)
7877 Traverse::type(Type
*)
7882 // Class Statement_inserter.
7885 Statement_inserter::insert(Statement
* s
)
7887 if (this->block_
!= NULL
)
7889 go_assert(this->pindex_
!= NULL
);
7890 this->block_
->insert_statement_before(*this->pindex_
, s
);
7893 else if (this->var_
!= NULL
)
7894 this->var_
->add_preinit_statement(this->gogo_
, s
);
7896 go_assert(saw_errors());