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.
11 #include "filenames.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
17 #include "go-optimize.h"
20 #include "statements.h"
21 #include "expressions.h"
30 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
35 globals_(new Bindings(NULL
)),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
60 specific_type_functions_(),
61 specific_type_functions_are_written_(false),
62 named_types_are_converted_(false),
66 const Location loc
= Linemap::predeclared_location();
68 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
69 RUNTIME_TYPE_KIND_UINT8
);
70 this->add_named_type(uint8_type
);
71 this->add_named_type(Type::make_integer_type("uint16", true, 16,
72 RUNTIME_TYPE_KIND_UINT16
));
73 this->add_named_type(Type::make_integer_type("uint32", true, 32,
74 RUNTIME_TYPE_KIND_UINT32
));
75 this->add_named_type(Type::make_integer_type("uint64", true, 64,
76 RUNTIME_TYPE_KIND_UINT64
));
78 this->add_named_type(Type::make_integer_type("int8", false, 8,
79 RUNTIME_TYPE_KIND_INT8
));
80 this->add_named_type(Type::make_integer_type("int16", false, 16,
81 RUNTIME_TYPE_KIND_INT16
));
82 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
83 RUNTIME_TYPE_KIND_INT32
);
84 this->add_named_type(int32_type
);
85 this->add_named_type(Type::make_integer_type("int64", false, 64,
86 RUNTIME_TYPE_KIND_INT64
));
88 this->add_named_type(Type::make_float_type("float32", 32,
89 RUNTIME_TYPE_KIND_FLOAT32
));
90 this->add_named_type(Type::make_float_type("float64", 64,
91 RUNTIME_TYPE_KIND_FLOAT64
));
93 this->add_named_type(Type::make_complex_type("complex64", 64,
94 RUNTIME_TYPE_KIND_COMPLEX64
));
95 this->add_named_type(Type::make_complex_type("complex128", 128,
96 RUNTIME_TYPE_KIND_COMPLEX128
));
98 int int_type_size
= pointer_size
;
99 if (int_type_size
< 32)
101 this->add_named_type(Type::make_integer_type("uint", true,
103 RUNTIME_TYPE_KIND_UINT
));
104 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
105 RUNTIME_TYPE_KIND_INT
);
106 this->add_named_type(int_type
);
108 this->add_named_type(Type::make_integer_type("uintptr", true,
110 RUNTIME_TYPE_KIND_UINTPTR
));
112 // "byte" is an alias for "uint8".
113 uint8_type
->integer_type()->set_is_byte();
114 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
116 byte_type
->type_value()->set_is_alias();
117 this->add_named_type(byte_type
->type_value());
119 // "rune" is an alias for "int32".
120 int32_type
->integer_type()->set_is_rune();
121 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
123 rune_type
->type_value()->set_is_alias();
124 this->add_named_type(rune_type
->type_value());
126 this->add_named_type(Type::make_named_bool_type());
128 this->add_named_type(Type::make_named_string_type());
130 // "error" is interface { Error() string }.
132 Typed_identifier_list
*methods
= new Typed_identifier_list
;
133 Typed_identifier_list
*results
= new Typed_identifier_list
;
134 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
135 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
136 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
137 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
138 error_iface
->finalize_methods();
139 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
140 this->add_named_type(error_type
);
143 this->globals_
->add_constant(Typed_identifier("true",
144 Type::make_boolean_type(),
147 Expression::make_boolean(true, loc
),
149 this->globals_
->add_constant(Typed_identifier("false",
150 Type::make_boolean_type(),
153 Expression::make_boolean(false, loc
),
156 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
159 Expression::make_nil(loc
),
162 Type
* abstract_int_type
= Type::make_abstract_integer_type();
163 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
166 Expression::make_iota(),
169 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
170 new_type
->set_is_varargs();
171 new_type
->set_is_builtin();
172 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
174 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
175 make_type
->set_is_varargs();
176 make_type
->set_is_builtin();
177 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
179 Typed_identifier_list
* len_result
= new Typed_identifier_list();
180 len_result
->push_back(Typed_identifier("", int_type
, loc
));
181 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
183 len_type
->set_is_builtin();
184 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
186 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
187 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
188 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
190 cap_type
->set_is_builtin();
191 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
193 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
194 print_type
->set_is_varargs();
195 print_type
->set_is_builtin();
196 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
198 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
199 print_type
->set_is_varargs();
200 print_type
->set_is_builtin();
201 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
203 Type
*empty
= Type::make_empty_interface_type(loc
);
204 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
205 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
206 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
208 panic_type
->set_is_builtin();
209 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
211 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
212 recover_result
->push_back(Typed_identifier("", empty
, loc
));
213 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
216 recover_type
->set_is_builtin();
217 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
219 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
220 close_type
->set_is_varargs();
221 close_type
->set_is_builtin();
222 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
224 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
225 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
226 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
228 copy_type
->set_is_varargs();
229 copy_type
->set_is_builtin();
230 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
232 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
233 append_type
->set_is_varargs();
234 append_type
->set_is_builtin();
235 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
237 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
238 complex_type
->set_is_varargs();
239 complex_type
->set_is_builtin();
240 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
242 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
243 real_type
->set_is_varargs();
244 real_type
->set_is_builtin();
245 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
247 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
248 imag_type
->set_is_varargs();
249 imag_type
->set_is_builtin();
250 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
252 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
253 delete_type
->set_is_varargs();
254 delete_type
->set_is_builtin();
255 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
258 // Convert a pkgpath into a string suitable for a symbol. Note that
259 // this transformation is convenient but imperfect. A -fgo-pkgpath
260 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
261 // possibly leading to link time errors.
264 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
266 std::string s
= pkgpath
;
267 for (size_t i
= 0; i
< s
.length(); ++i
)
270 if ((c
>= 'a' && c
<= 'z')
271 || (c
>= 'A' && c
<= 'Z')
272 || (c
>= '0' && c
<= '9'))
280 // Get the package path to use for type reflection data. This should
281 // ideally be unique across the entire link.
284 Gogo::pkgpath() const
286 go_assert(this->pkgpath_set_
);
287 return this->pkgpath_
;
290 // Set the package path from the -fgo-pkgpath command line option.
293 Gogo::set_pkgpath(const std::string
& arg
)
295 go_assert(!this->pkgpath_set_
);
296 this->pkgpath_
= arg
;
297 this->pkgpath_set_
= true;
298 this->pkgpath_from_option_
= true;
301 // Get the package path to use for symbol names.
304 Gogo::pkgpath_symbol() const
306 go_assert(this->pkgpath_set_
);
307 return this->pkgpath_symbol_
;
310 // Set the unique prefix to use to determine the package path, from
311 // the -fgo-prefix command line option.
314 Gogo::set_prefix(const std::string
& arg
)
316 go_assert(!this->prefix_from_option_
);
318 this->prefix_from_option_
= true;
321 // Munge name for use in an error message.
324 Gogo::message_name(const std::string
& name
)
326 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
329 // Get the package name.
332 Gogo::package_name() const
334 go_assert(this->package_
!= NULL
);
335 return this->package_
->package_name();
338 // Set the package name.
341 Gogo::set_package_name(const std::string
& package_name
,
344 if (this->package_
!= NULL
)
346 if (this->package_
->package_name() != package_name
)
347 go_error_at(location
, "expected package %<%s%>",
348 Gogo::message_name(this->package_
->package_name()).c_str());
352 // Now that we know the name of the package we are compiling, set
353 // the package path to use for reflect.Type.PkgPath and global
355 if (this->pkgpath_set_
)
356 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
359 if (!this->prefix_from_option_
&& package_name
== "main")
361 this->pkgpath_
= package_name
;
362 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
366 if (!this->prefix_from_option_
)
367 this->prefix_
= "go";
368 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
369 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
370 + Gogo::pkgpath_for_symbol(package_name
));
372 this->pkgpath_set_
= true;
375 this->package_
= this->register_package(this->pkgpath_
,
376 this->pkgpath_symbol_
, location
);
377 this->package_
->set_package_name(package_name
, location
);
379 if (this->is_main_package())
381 // Declare "main" as a function which takes no parameters and
383 Location uloc
= Linemap::unknown_location();
384 this->declare_function(Gogo::pack_hidden_name("main", false),
385 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
390 // Return whether this is the "main" package. This is not true if
391 // -fgo-pkgpath or -fgo-prefix was used.
394 Gogo::is_main_package() const
396 return (this->package_name() == "main"
397 && !this->pkgpath_from_option_
398 && !this->prefix_from_option_
);
404 Gogo::import_package(const std::string
& filename
,
405 const std::string
& local_name
,
406 bool is_local_name_exported
,
410 if (filename
.empty())
412 go_error_at(location
, "import path is empty");
416 const char *pf
= filename
.data();
417 const char *pend
= pf
+ filename
.length();
421 int adv
= Lex::fetch_char(pf
, &c
);
424 go_error_at(location
, "import path contains invalid UTF-8 sequence");
429 go_error_at(location
, "import path contains NUL");
432 if (c
< 0x20 || c
== 0x7f)
434 go_error_at(location
, "import path contains control character");
439 go_error_at(location
, "import path contains backslash; use slash");
442 if (Lex::is_unicode_space(c
))
444 go_error_at(location
, "import path contains space character");
447 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
449 go_error_at(location
,
450 "import path contains invalid character '%c'", c
);
456 if (IS_ABSOLUTE_PATH(filename
.c_str()))
458 go_error_at(location
, "import path cannot be absolute path");
462 if (local_name
== "init")
463 go_error_at(location
, "cannot import package as init");
465 if (filename
== "unsafe")
467 this->import_unsafe(local_name
, is_local_name_exported
, location
);
468 this->current_file_imported_unsafe_
= true;
472 Imports::const_iterator p
= this->imports_
.find(filename
);
473 if (p
!= this->imports_
.end())
475 Package
* package
= p
->second
;
476 package
->set_location(location
);
477 std::string ln
= local_name
;
478 bool is_ln_exported
= is_local_name_exported
;
481 ln
= package
->package_name();
482 go_assert(!ln
.empty());
483 is_ln_exported
= Lex::is_exported_name(ln
);
489 Bindings
* bindings
= package
->bindings();
490 for (Bindings::const_declarations_iterator p
=
491 bindings
->begin_declarations();
492 p
!= bindings
->end_declarations();
494 this->add_dot_import_object(p
->second
);
495 std::string dot_alias
= "." + package
->package_name();
496 package
->add_alias(dot_alias
, location
);
500 package
->add_alias(ln
, location
);
501 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
502 this->package_
->bindings()->add_package(ln
, package
);
507 Import::Stream
* stream
= Import::open_package(filename
, location
,
508 this->relative_import_path_
);
512 go_error_at(location
, "import file %qs not found", filename
.c_str());
516 Import
imp(stream
, location
);
517 imp
.register_builtin_types(this);
518 Package
* package
= imp
.import(this, local_name
, is_local_name_exported
);
521 if (package
->pkgpath() == this->pkgpath())
522 go_error_at(location
,
523 ("imported package uses same package path as package "
524 "being compiled (see -fgo-pkgpath option)"));
526 this->imports_
.insert(std::make_pair(filename
, package
));
533 Gogo::lookup_init(const std::string
& init_name
)
535 Import_init
tmp("", init_name
, -1);
536 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
537 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
540 // Add an import control function for an imported package to the list.
543 Gogo::add_import_init_fn(const std::string
& package_name
,
544 const std::string
& init_name
, int prio
)
546 for (Import_init_set::iterator p
=
547 this->imported_init_fns_
.begin();
548 p
!= this->imported_init_fns_
.end();
551 Import_init
*ii
= (*p
);
552 if (ii
->init_name() == init_name
)
554 // If a test of package P1, built as part of package P1,
555 // imports package P2, and P2 imports P1 (perhaps
556 // indirectly), then we will see the same import name with
557 // different import priorities. That is OK, so don't give
558 // an error about it.
559 if (ii
->package_name() != package_name
)
561 go_error_at(Linemap::unknown_location(),
562 "duplicate package initialization name %qs",
563 Gogo::message_name(init_name
).c_str());
564 go_inform(Linemap::unknown_location(), "used by package %qs",
565 Gogo::message_name(ii
->package_name()).c_str());
566 go_inform(Linemap::unknown_location(), " and by package %qs",
567 Gogo::message_name(package_name
).c_str());
569 ii
->set_priority(prio
);
574 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
575 this->imported_init_fns_
.insert(nii
);
578 // Return whether we are at the global binding level.
581 Gogo::in_global_scope() const
583 return this->functions_
.empty();
586 // Return the current binding contour.
589 Gogo::current_bindings()
591 if (!this->functions_
.empty())
592 return this->functions_
.back().blocks
.back()->bindings();
593 else if (this->package_
!= NULL
)
594 return this->package_
->bindings();
596 return this->globals_
;
600 Gogo::current_bindings() const
602 if (!this->functions_
.empty())
603 return this->functions_
.back().blocks
.back()->bindings();
604 else if (this->package_
!= NULL
)
605 return this->package_
->bindings();
607 return this->globals_
;
611 Gogo::update_init_priority(Import_init
* ii
,
612 std::set
<const Import_init
*>* visited
)
617 for (std::set
<std::string
>::const_iterator pci
=
618 ii
->precursors().begin();
619 pci
!= ii
->precursors().end();
622 Import_init
* succ
= this->lookup_init(*pci
);
623 if (visited
->find(succ
) == visited
->end())
624 update_init_priority(succ
, visited
);
625 succ_prior
= std::max(succ_prior
, succ
->priority());
627 if (ii
->priority() <= succ_prior
)
628 ii
->set_priority(succ_prior
+ 1);
632 Gogo::recompute_init_priorities()
634 std::set
<Import_init
*> nonroots
;
636 for (Import_init_set::const_iterator p
=
637 this->imported_init_fns_
.begin();
638 p
!= this->imported_init_fns_
.end();
641 const Import_init
*ii
= *p
;
642 for (std::set
<std::string
>::const_iterator pci
=
643 ii
->precursors().begin();
644 pci
!= ii
->precursors().end();
647 Import_init
* ii
= this->lookup_init(*pci
);
652 // Recursively update priorities starting at roots.
653 std::set
<const Import_init
*> visited
;
654 for (Import_init_set::iterator p
=
655 this->imported_init_fns_
.begin();
656 p
!= this->imported_init_fns_
.end();
659 Import_init
* ii
= *p
;
660 if (nonroots
.find(ii
) != nonroots
.end())
662 update_init_priority(ii
, &visited
);
666 // Add statements to INIT_STMTS which run the initialization
667 // functions for imported packages. This is only used for the "main"
671 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
673 go_assert(this->is_main_package());
675 if (this->imported_init_fns_
.empty())
678 Location unknown_loc
= Linemap::unknown_location();
679 Function_type
* func_type
=
680 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
681 Btype
* fntype
= func_type
->get_backend_fntype(this);
683 // Recompute init priorities based on a walk of the init graph.
684 recompute_init_priorities();
686 // We must call them in increasing priority order.
687 std::vector
<const Import_init
*> v
;
688 for (Import_init_set::const_iterator p
=
689 this->imported_init_fns_
.begin();
690 p
!= this->imported_init_fns_
.end();
693 if ((*p
)->priority() < 0)
694 go_error_at(Linemap::unknown_location(),
695 "internal error: failed to set init priority for %s",
696 (*p
)->package_name().c_str());
699 std::sort(v
.begin(), v
.end(), priority_compare
);
701 // We build calls to the init functions, which take no arguments.
702 std::vector
<Bexpression
*> empty_args
;
703 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
707 const Import_init
* ii
= *p
;
708 std::string user_name
= ii
->package_name() + ".init";
709 const std::string
& init_name(ii
->init_name());
711 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
712 true, true, true, false,
714 Bexpression
* pfunc_code
=
715 this->backend()->function_code_expression(pfunc
, unknown_loc
);
716 Bexpression
* pfunc_call
=
717 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
719 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
724 // Register global variables with the garbage collector. We need to
725 // register all variables which can hold a pointer value. They become
726 // roots during the mark phase. We build a struct that is easy to
727 // hook into a list of roots.
729 // type gcRoot struct {
730 // decl unsafe.Pointer // Pointer to variable.
731 // size uintptr // Total size of variable.
732 // ptrdata uintptr // Length of variable's gcdata.
733 // gcdata *byte // Pointer mask.
736 // type gcRootList struct {
742 // The last entry in the roots array has a NULL decl field.
745 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
746 std::vector
<Bstatement
*>& init_stmts
,
749 if (var_gc
.empty() && this->gc_roots_
.empty())
752 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
753 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
754 Type
* byte_type
= this->lookup_global("byte")->type_value();
755 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
756 Struct_type
* root_type
=
757 Type::make_builtin_struct_type(4,
759 "size", uintptr_type
,
760 "ptrdata", uintptr_type
,
761 "gcdata", pointer_byte_type
);
763 Location builtin_loc
= Linemap::predeclared_location();
764 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
765 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
767 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
768 root_array_type
->set_is_array_incomparable();
770 Type
* int_type
= Type::lookup_integer_type("int");
771 Struct_type
* root_list_type
=
772 Type::make_builtin_struct_type(3,
775 "roots", root_array_type
);
777 // Build an initializer for the roots array.
779 Expression_list
* roots_init
= new Expression_list();
781 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
785 Expression_list
* init
= new Expression_list();
787 Location no_loc
= (*p
)->location();
788 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
789 Expression
* decl_addr
=
790 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
791 decl_addr
->unary_expression()->set_does_not_escape();
792 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
793 init
->push_back(decl_addr
);
796 Expression::make_type_info(decl
->type(),
797 Expression::TYPE_INFO_SIZE
);
798 init
->push_back(size
);
800 Expression
* ptrdata
=
801 Expression::make_type_info(decl
->type(),
802 Expression::TYPE_INFO_BACKEND_PTRDATA
);
803 init
->push_back(ptrdata
);
805 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
806 init
->push_back(gcdata
);
808 Expression
* root_ctor
=
809 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
810 roots_init
->push_back(root_ctor
);
813 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
814 p
!= this->gc_roots_
.end();
817 Expression_list
*init
= new Expression_list();
819 Expression
* expr
= *p
;
820 Location eloc
= expr
->location();
821 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
823 Type
* type
= expr
->type()->points_to();
824 go_assert(type
!= NULL
);
827 Expression::make_type_info(type
,
828 Expression::TYPE_INFO_SIZE
);
829 init
->push_back(size
);
831 Expression
* ptrdata
=
832 Expression::make_type_info(type
,
833 Expression::TYPE_INFO_BACKEND_PTRDATA
);
834 init
->push_back(ptrdata
);
836 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
837 init
->push_back(gcdata
);
839 Expression
* root_ctor
=
840 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
841 roots_init
->push_back(root_ctor
);
844 // Build a constructor for the struct.
846 Expression_list
* root_list_init
= new Expression_list();
847 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
848 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
851 Expression
* roots_ctor
=
852 Expression::make_array_composite_literal(root_array_type
, roots_init
,
854 root_list_init
->push_back(roots_ctor
);
856 Expression
* root_list_ctor
=
857 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
860 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
862 root_addr
->unary_expression()->set_is_gc_root();
863 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
864 builtin_loc
, 1, root_addr
);
866 Translate_context
context(this, NULL
, NULL
, NULL
);
867 Bexpression
* bcall
= register_roots
->get_backend(&context
);
868 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
871 // Build the decl for the initialization function.
874 Gogo::initialization_function_decl()
876 std::string name
= this->get_init_fn_name();
877 Location loc
= this->package_
->location();
879 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
880 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
881 return Named_object::make_function(name
, NULL
, initfn
);
884 // Create the magic initialization function. CODE_STMT is the
885 // code that it needs to run.
888 Gogo::create_initialization_function(Named_object
* initfn
,
889 Bstatement
* code_stmt
)
891 // Make sure that we thought we needed an initialization function,
892 // as otherwise we will not have reported it in the export data.
893 go_assert(this->is_main_package() || this->need_init_fn_
);
896 initfn
= this->initialization_function_decl();
898 // Bind the initialization function code to a block.
899 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
900 Location pkg_loc
= this->package_
->location();
901 std::vector
<Bvariable
*> vars
;
902 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
904 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
906 go_assert(saw_errors());
912 // Search for references to VAR in any statements or called functions.
914 class Find_var
: public Traverse
917 // A hash table we use to avoid looping. The index is the name of a
918 // named object. We only look through objects defined in this
920 typedef Unordered_set(const void*) Seen_objects
;
922 Find_var(Named_object
* var
, Seen_objects
* seen_objects
)
923 : Traverse(traverse_expressions
),
924 var_(var
), seen_objects_(seen_objects
), found_(false)
927 // Whether the variable was found.
930 { return this->found_
; }
933 expression(Expression
**);
936 // The variable we are looking for.
938 // Names of objects we have already seen.
939 Seen_objects
* seen_objects_
;
940 // True if the variable was found.
944 // See if EXPR refers to VAR, looking through function calls and
945 // variable initializations.
948 Find_var::expression(Expression
** pexpr
)
950 Expression
* e
= *pexpr
;
952 Var_expression
* ve
= e
->var_expression();
955 Named_object
* v
= ve
->named_object();
959 return TRAVERSE_EXIT
;
962 if (v
->is_variable() && v
->package() == NULL
)
964 Expression
* init
= v
->var_value()->init();
967 std::pair
<Seen_objects::iterator
, bool> ins
=
968 this->seen_objects_
->insert(v
);
971 // This is the first time we have seen this name.
972 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
973 return TRAVERSE_EXIT
;
979 // We traverse the code of any function or bound method we see. Note that
980 // this means that we will traverse the code of a function or bound method
981 // whose address is taken even if it is not called.
982 Func_expression
* fe
= e
->func_expression();
983 Bound_method_expression
* bme
= e
->bound_method_expression();
984 if (fe
!= NULL
|| bme
!= NULL
)
986 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
987 if (f
->is_function() && f
->package() == NULL
)
989 std::pair
<Seen_objects::iterator
, bool> ins
=
990 this->seen_objects_
->insert(f
);
993 // This is the first time we have seen this name.
994 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
995 return TRAVERSE_EXIT
;
1000 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1003 Temporary_statement
* ts
= tre
->statement();
1004 Expression
* init
= ts
->init();
1007 std::pair
<Seen_objects::iterator
, bool> ins
=
1008 this->seen_objects_
->insert(ts
);
1011 // This is the first time we have seen this temporary
1013 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1014 return TRAVERSE_EXIT
;
1019 return TRAVERSE_CONTINUE
;
1022 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1025 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1028 Find_var::Seen_objects seen_objects
;
1029 Find_var
find_var(var
, &seen_objects
);
1031 Expression::traverse(&expr
, &find_var
);
1032 if (preinit
!= NULL
)
1033 preinit
->traverse(&find_var
);
1036 Expression
* init
= dep
->var_value()->init();
1038 Expression::traverse(&init
, &find_var
);
1039 if (dep
->var_value()->has_pre_init())
1040 dep
->var_value()->preinit()->traverse(&find_var
);
1043 return find_var
.found();
1046 // Sort variable initializations. If the initialization expression
1047 // for variable A refers directly or indirectly to the initialization
1048 // expression for variable B, then we must initialize B before A.
1054 : var_(NULL
), init_(NULL
), dep_count_(0)
1057 Var_init(Named_object
* var
, Bstatement
* init
)
1058 : var_(var
), init_(init
), dep_count_(0)
1061 // Return the variable.
1064 { return this->var_
; }
1066 // Return the initialization expression.
1069 { return this->init_
; }
1071 // Return the number of remaining dependencies.
1074 { return this->dep_count_
; }
1076 // Increment the number of dependencies.
1079 { ++this->dep_count_
; }
1081 // Decrement the number of dependencies.
1084 { --this->dep_count_
; }
1087 // The variable being initialized.
1089 // The initialization statement.
1091 // The number of initializations this is dependent on. A variable
1092 // initialization should not be emitted if any of its dependencies
1093 // have not yet been resolved.
1097 // For comparing Var_init keys in a map.
1100 operator<(const Var_init
& v1
, const Var_init
& v2
)
1101 { return v1
.var()->name() < v2
.var()->name(); }
1103 typedef std::list
<Var_init
> Var_inits
;
1105 // Sort the variable initializations. The rule we follow is that we
1106 // emit them in the order they appear in the array, except that if the
1107 // initialization expression for a variable V1 depends upon another
1108 // variable V2 then we initialize V1 after V2.
1111 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1113 if (var_inits
->empty())
1116 typedef std::pair
<Named_object
*, Named_object
*> No_no
;
1117 typedef std::map
<No_no
, bool> Cache
;
1120 // A mapping from a variable initialization to a set of
1121 // variable initializations that depend on it.
1122 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1123 Init_deps init_deps
;
1124 bool init_loop
= false;
1125 for (Var_inits::iterator p1
= var_inits
->begin();
1126 p1
!= var_inits
->end();
1129 Named_object
* var
= p1
->var();
1130 Expression
* init
= var
->var_value()->init();
1131 Block
* preinit
= var
->var_value()->preinit();
1132 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1134 // Start walking through the list to see which variables VAR
1135 // needs to wait for.
1136 for (Var_inits::iterator p2
= var_inits
->begin();
1137 p2
!= var_inits
->end();
1140 if (var
== p2
->var())
1143 Named_object
* p2var
= p2
->var();
1144 No_no
key(var
, p2var
);
1145 std::pair
<Cache::iterator
, bool> ins
=
1146 cache
.insert(std::make_pair(key
, false));
1148 ins
.first
->second
= expression_requires(init
, preinit
, dep
, p2var
);
1149 if (ins
.first
->second
)
1151 // VAR depends on P2VAR.
1152 init_deps
[*p2
].insert(&(*p1
));
1153 p1
->add_dependency();
1155 // Check for cycles.
1156 key
= std::make_pair(p2var
, var
);
1157 ins
= cache
.insert(std::make_pair(key
, false));
1160 expression_requires(p2var
->var_value()->init(),
1161 p2var
->var_value()->preinit(),
1162 gogo
->var_depends_on(p2var
->var_value()),
1164 if (ins
.first
->second
)
1166 go_error_at(var
->location(),
1167 ("initialization expressions for %qs and "
1168 "%qs depend upon each other"),
1169 var
->message_name().c_str(),
1170 p2var
->message_name().c_str());
1171 go_inform(p2
->var()->location(), "%qs defined here",
1172 p2var
->message_name().c_str());
1180 // If there are no dependencies then the declaration order is sorted.
1181 if (!init_deps
.empty() && !init_loop
)
1183 // Otherwise, sort variable initializations by emitting all variables with
1184 // no dependencies in declaration order. VAR_INITS is already in
1185 // declaration order.
1187 while (!var_inits
->empty())
1189 Var_inits::iterator v1
;;
1190 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1192 if (v1
->dep_count() == 0)
1195 go_assert(v1
!= var_inits
->end());
1197 // V1 either has no dependencies or its dependencies have already
1198 // been emitted, add it to READY next. When V1 is emitted, remove
1199 // a dependency from each V that depends on V1.
1200 ready
.splice(ready
.end(), *var_inits
, v1
);
1202 Init_deps::iterator p1
= init_deps
.find(*v1
);
1203 if (p1
!= init_deps
.end())
1205 std::set
<Var_init
*> resolved
= p1
->second
;
1206 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1207 pv
!= resolved
.end();
1209 (*pv
)->remove_dependency();
1210 init_deps
.erase(p1
);
1213 var_inits
->swap(ready
);
1214 go_assert(init_deps
.empty());
1217 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1218 // check for a loop of VAR on itself.
1219 // interpret as a loop.
1220 for (Var_inits::const_iterator p
= var_inits
->begin();
1221 p
!= var_inits
->end();
1223 gogo
->check_self_dep(p
->var());
1226 // Give an error if the initialization expression for VAR depends on
1227 // itself. We only check if INIT is not NULL and there is no
1228 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1229 // which we will interpret as a loop.
1232 Gogo::check_self_dep(Named_object
* var
)
1234 Expression
* init
= var
->var_value()->init();
1235 Block
* preinit
= var
->var_value()->preinit();
1236 Named_object
* dep
= this->var_depends_on(var
->var_value());
1239 && expression_requires(init
, preinit
, NULL
, var
))
1240 go_error_at(var
->location(),
1241 "initialization expression for %qs depends upon itself",
1242 var
->message_name().c_str());
1245 // Write out the global definitions.
1248 Gogo::write_globals()
1250 this->build_interface_method_tables();
1252 Bindings
* bindings
= this->current_bindings();
1254 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1255 p
!= bindings
->end_declarations();
1258 // If any function declarations needed a descriptor, make sure
1260 Named_object
* no
= p
->second
;
1261 if (no
->is_function_declaration())
1262 no
->func_declaration_value()->build_backend_descriptor(this);
1265 // Lists of globally declared types, variables, constants, and functions
1266 // that must be defined.
1267 std::vector
<Btype
*> type_decls
;
1268 std::vector
<Bvariable
*> var_decls
;
1269 std::vector
<Bexpression
*> const_decls
;
1270 std::vector
<Bfunction
*> func_decls
;
1272 // The init function declaration and associated Bfunction, if necessary.
1273 Named_object
* init_fndecl
= NULL
;
1274 Bfunction
* init_bfn
= NULL
;
1276 std::vector
<Bstatement
*> init_stmts
;
1277 std::vector
<Bstatement
*> var_init_stmts
;
1279 if (this->is_main_package())
1281 init_fndecl
= this->initialization_function_decl();
1282 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1283 this->init_imports(init_stmts
, init_bfn
);
1286 // A list of variable initializations.
1287 Var_inits var_inits
;
1289 // A list of variables which need to be registered with the garbage
1291 size_t count_definitions
= bindings
->size_definitions();
1292 std::vector
<Named_object
*> var_gc
;
1293 var_gc
.reserve(count_definitions
);
1295 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1296 p
!= bindings
->end_definitions();
1299 Named_object
* no
= *p
;
1300 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1302 // There is nothing to do for a package.
1303 if (no
->is_package())
1306 // There is nothing to do for an object which was imported from
1307 // a different package into the global scope.
1308 if (no
->package() != NULL
)
1311 // Skip blank named functions and constants.
1312 if ((no
->is_function() && no
->func_value()->is_sink())
1313 || (no
->is_const() && no
->const_value()->is_sink()))
1316 // There is nothing useful we can output for constants which
1317 // have ideal or non-integral type.
1320 Type
* type
= no
->const_value()->type();
1322 type
= no
->const_value()->expr()->type();
1323 if (type
->is_abstract() || !type
->is_numeric_type())
1327 if (!no
->is_variable())
1328 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1331 Variable
* var
= no
->var_value();
1332 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1333 var_decls
.push_back(bvar
);
1335 // Check for a sink variable, which may be used to run an
1336 // initializer purely for its side effects.
1337 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1339 Bstatement
* var_init_stmt
= NULL
;
1340 if (!var
->has_pre_init())
1342 // If the backend representation of the variable initializer is
1343 // constant, we can just set the initial value using
1344 // global_var_set_init instead of during the init() function.
1345 // The initializer is constant if it is the zero-value of the
1346 // variable's type or if the initial value is an immutable value
1347 // that is not copied to the heap.
1348 bool is_static_initializer
= false;
1349 if (var
->init() == NULL
)
1350 is_static_initializer
= true;
1353 Type
* var_type
= var
->type();
1354 Expression
* init
= var
->init();
1355 Expression
* init_cast
=
1356 Expression::make_cast(var_type
, init
, var
->location());
1357 is_static_initializer
= init_cast
->is_static_initializer();
1360 // Non-constant variable initializations might need to create
1361 // temporary variables, which will need the initialization
1362 // function as context.
1363 Named_object
* var_init_fn
;
1364 if (is_static_initializer
)
1368 if (init_fndecl
== NULL
)
1370 init_fndecl
= this->initialization_function_decl();
1371 Function
* func
= init_fndecl
->func_value();
1372 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1374 var_init_fn
= init_fndecl
;
1376 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1378 if (var_binit
== NULL
)
1380 else if (is_static_initializer
)
1382 if (expression_requires(var
->init(), NULL
,
1383 this->var_depends_on(var
), no
))
1384 go_error_at(no
->location(),
1385 "initialization expression for %qs depends "
1387 no
->message_name().c_str());
1388 this->backend()->global_variable_set_init(bvar
, var_binit
);
1392 this->backend()->expression_statement(init_bfn
, var_binit
);
1395 Location loc
= var
->location();
1396 Bexpression
* var_expr
=
1397 this->backend()->var_expression(bvar
, VE_lvalue
, loc
);
1399 this->backend()->assignment_statement(init_bfn
, var_expr
,
1405 // We are going to create temporary variables which
1406 // means that we need an fndecl.
1407 if (init_fndecl
== NULL
)
1408 init_fndecl
= this->initialization_function_decl();
1410 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1411 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1414 if (var_init_stmt
!= NULL
)
1416 if (var
->init() == NULL
&& !var
->has_pre_init())
1417 var_init_stmts
.push_back(var_init_stmt
);
1419 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1421 else if (this->var_depends_on(var
) != NULL
)
1423 // This variable is initialized from something that is
1424 // not in its init or preinit. This variable needs to
1425 // participate in dependency analysis sorting, in case
1426 // some other variable depends on this one.
1427 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1428 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1429 Bstatement
* zero_stmt
=
1430 this->backend()->expression_statement(init_bfn
, zero
);
1431 var_inits
.push_back(Var_init(no
, zero_stmt
));
1434 // Collect a list of all global variables with pointers,
1435 // to register them for the garbage collector.
1436 if (!is_sink
&& var
->type()->has_pointer())
1438 // Avoid putting runtime.gcRoots itself on the list.
1439 if (this->compiling_runtime()
1440 && this->package_name() == "runtime"
1441 && Gogo::unpack_hidden_name(no
->name()) == "gcRoots")
1444 var_gc
.push_back(no
);
1449 // Register global variables with the garbage collector.
1450 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1452 // Simple variable initializations, after all variables are
1454 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1456 // Complete variable initializations, first sorting them into a
1458 if (!var_inits
.empty())
1460 sort_var_inits(this, &var_inits
);
1461 for (Var_inits::const_iterator p
= var_inits
.begin();
1462 p
!= var_inits
.end();
1464 init_stmts
.push_back(p
->init());
1467 // After all the variables are initialized, call the init
1468 // functions if there are any. Init functions take no arguments, so
1469 // we pass in EMPTY_ARGS to call them.
1470 std::vector
<Bexpression
*> empty_args
;
1471 for (std::vector
<Named_object
*>::const_iterator p
=
1472 this->init_functions_
.begin();
1473 p
!= this->init_functions_
.end();
1476 Location func_loc
= (*p
)->location();
1477 Function
* func
= (*p
)->func_value();
1478 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1479 Bexpression
* func_code
=
1480 this->backend()->function_code_expression(initfn
, func_loc
);
1481 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1484 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1485 init_stmts
.push_back(ist
);
1488 // Set up a magic function to do all the initialization actions.
1489 // This will be called if this package is imported.
1490 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1491 if (this->need_init_fn_
|| this->is_main_package())
1494 this->create_initialization_function(init_fndecl
, init_fncode
);
1495 if (init_fndecl
!= NULL
)
1496 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1499 // We should not have seen any new bindings created during the conversion.
1500 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1502 // Define all globally declared values.
1504 this->backend()->write_global_definitions(type_decls
, const_decls
,
1505 func_decls
, var_decls
);
1508 // Return the current block.
1511 Gogo::current_block()
1513 if (this->functions_
.empty())
1516 return this->functions_
.back().blocks
.back();
1519 // Look up a name in the current binding contour. If PFUNCTION is not
1520 // NULL, set it to the function in which the name is defined, or NULL
1521 // if the name is defined in global scope.
1524 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1526 if (pfunction
!= NULL
)
1529 if (Gogo::is_sink_name(name
))
1530 return Named_object::make_sink();
1532 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1533 p
!= this->functions_
.rend();
1536 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1539 if (pfunction
!= NULL
)
1540 *pfunction
= p
->function
;
1545 if (this->package_
!= NULL
)
1547 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1550 if (ret
->package() != NULL
)
1552 std::string dot_alias
= "." + ret
->package()->package_name();
1553 ret
->package()->note_usage(dot_alias
);
1559 // We do not look in the global namespace. If we did, the global
1560 // namespace would effectively hide names which were defined in
1561 // package scope which we have not yet seen. Instead,
1562 // define_global_names is called after parsing is over to connect
1563 // undefined names at package scope with names defined at global
1569 // Look up a name in the current block, without searching enclosing
1573 Gogo::lookup_in_block(const std::string
& name
) const
1575 go_assert(!this->functions_
.empty());
1576 go_assert(!this->functions_
.back().blocks
.empty());
1577 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1580 // Look up a name in the global namespace.
1583 Gogo::lookup_global(const char* name
) const
1585 return this->globals_
->lookup(name
);
1588 // Add an imported package.
1591 Gogo::add_imported_package(const std::string
& real_name
,
1592 const std::string
& alias_arg
,
1593 bool is_alias_exported
,
1594 const std::string
& pkgpath
,
1595 const std::string
& pkgpath_symbol
,
1597 bool* padd_to_globals
)
1599 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1600 ret
->set_package_name(real_name
, location
);
1602 *padd_to_globals
= false;
1604 if (alias_arg
== "_")
1606 else if (alias_arg
== ".")
1608 *padd_to_globals
= true;
1609 std::string dot_alias
= "." + real_name
;
1610 ret
->add_alias(dot_alias
, location
);
1614 std::string alias
= alias_arg
;
1618 is_alias_exported
= Lex::is_exported_name(alias
);
1620 ret
->add_alias(alias
, location
);
1621 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1622 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1623 if (!no
->is_package())
1630 // Register a package. This package may or may not be imported. This
1631 // returns the Package structure for the package, creating if it
1632 // necessary. LOCATION is the location of the import statement that
1633 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1634 // for names in the package; it may be the empty string, in which case
1635 // we either get it later or make a guess when we need it.
1638 Gogo::register_package(const std::string
& pkgpath
,
1639 const std::string
& pkgpath_symbol
, Location location
)
1641 Package
* package
= NULL
;
1642 std::pair
<Packages::iterator
, bool> ins
=
1643 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1646 // We have seen this package name before.
1647 package
= ins
.first
->second
;
1648 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1649 if (!pkgpath_symbol
.empty())
1650 package
->set_pkgpath_symbol(pkgpath_symbol
);
1651 if (Linemap::is_unknown_location(package
->location()))
1652 package
->set_location(location
);
1656 // First time we have seen this package name.
1657 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1658 go_assert(ins
.first
->second
== NULL
);
1659 ins
.first
->second
= package
;
1665 // Return the pkgpath symbol for a package, given the pkgpath.
1668 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1670 Packages::iterator p
= this->packages_
.find(pkgpath
);
1671 go_assert(p
!= this->packages_
.end());
1672 return p
->second
->pkgpath_symbol();
1675 // Start compiling a function.
1678 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1679 bool add_method_to_type
, Location location
)
1681 bool at_top_level
= this->functions_
.empty();
1683 Block
* block
= new Block(NULL
, location
);
1685 Named_object
* enclosing
= (at_top_level
1687 : this->functions_
.back().function
);
1689 Function
* function
= new Function(type
, enclosing
, block
, location
);
1691 if (type
->is_method())
1693 const Typed_identifier
* receiver
= type
->receiver();
1694 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1695 true, true, location
);
1696 std::string rname
= receiver
->name();
1697 if (rname
.empty() || Gogo::is_sink_name(rname
))
1699 // We need to give receivers a name since they wind up in
1700 // DECL_ARGUMENTS. FIXME.
1701 static unsigned int count
;
1703 snprintf(buf
, sizeof buf
, "r.%u", count
);
1707 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1710 const Typed_identifier_list
* parameters
= type
->parameters();
1711 bool is_varargs
= type
->is_varargs();
1712 if (parameters
!= NULL
)
1714 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1715 p
!= parameters
->end();
1718 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1720 if (is_varargs
&& p
+ 1 == parameters
->end())
1721 param
->set_is_varargs_parameter();
1723 std::string pname
= p
->name();
1724 if (pname
.empty() || Gogo::is_sink_name(pname
))
1726 // We need to give parameters a name since they wind up
1727 // in DECL_ARGUMENTS. FIXME.
1728 static unsigned int count
;
1730 snprintf(buf
, sizeof buf
, "p.%u", count
);
1734 block
->bindings()->add_variable(pname
, NULL
, param
);
1738 function
->create_result_variables(this);
1740 const std::string
* pname
;
1741 std::string nested_name
;
1742 bool is_init
= false;
1743 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1745 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1746 || (type
->results() != NULL
&& !type
->results()->empty()))
1747 go_error_at(location
,
1748 "func init must have no arguments and no return values");
1749 // There can be multiple "init" functions, so give them each a
1751 nested_name
= this->init_function_name();
1752 pname
= &nested_name
;
1755 else if (!name
.empty())
1759 // Invent a name for a nested function.
1760 nested_name
= this->nested_function_name();
1761 pname
= &nested_name
;
1765 if (Gogo::is_sink_name(*pname
))
1767 std::string
sname(this->sink_function_name());
1768 ret
= Named_object::make_function(sname
, NULL
, function
);
1769 ret
->func_value()->set_is_sink();
1771 if (!type
->is_method())
1772 ret
= this->package_
->bindings()->add_named_object(ret
);
1773 else if (add_method_to_type
)
1775 // We should report errors even for sink methods.
1776 Type
* rtype
= type
->receiver()->type();
1777 // Avoid points_to and deref to avoid getting an error if
1778 // the type is not yet defined.
1779 if (rtype
->classification() == Type::TYPE_POINTER
)
1780 rtype
= rtype
->points_to();
1781 while (rtype
->named_type() != NULL
1782 && rtype
->named_type()->is_alias())
1783 rtype
= rtype
->named_type()->real_type()->forwarded();
1784 if (rtype
->is_error_type())
1786 else if (rtype
->named_type() != NULL
)
1788 if (rtype
->named_type()->named_object()->package() != NULL
)
1789 go_error_at(type
->receiver()->location(),
1790 "may not define methods on non-local type");
1792 else if (rtype
->forward_declaration_type() != NULL
)
1794 // Go ahead and add the method in case we need to report
1795 // an error when we see the definition.
1796 rtype
->forward_declaration_type()->add_existing_method(ret
);
1799 go_error_at(type
->receiver()->location(),
1800 ("invalid receiver type "
1801 "(receiver must be a named type)"));
1804 else if (!type
->is_method())
1806 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1807 if (!ret
->is_function() || ret
->func_value() != function
)
1809 // Redefinition error. Invent a name to avoid knockon
1811 std::string
rname(this->redefined_function_name());
1812 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
1817 if (!add_method_to_type
)
1818 ret
= Named_object::make_function(name
, NULL
, function
);
1821 go_assert(at_top_level
);
1822 Type
* rtype
= type
->receiver()->type();
1824 // We want to look through the pointer created by the
1825 // parser, without getting an error if the type is not yet
1827 if (rtype
->classification() == Type::TYPE_POINTER
)
1828 rtype
= rtype
->points_to();
1830 while (rtype
->named_type() != NULL
1831 && rtype
->named_type()->is_alias())
1832 rtype
= rtype
->named_type()->real_type()->forwarded();
1834 if (rtype
->is_error_type())
1835 ret
= Named_object::make_function(name
, NULL
, function
);
1836 else if (rtype
->named_type() != NULL
)
1838 if (rtype
->named_type()->named_object()->package() != NULL
)
1840 go_error_at(type
->receiver()->location(),
1841 "may not define methods on non-local type");
1842 ret
= Named_object::make_function(name
, NULL
, function
);
1846 ret
= rtype
->named_type()->add_method(name
, function
);
1847 if (!ret
->is_function())
1849 // Redefinition error.
1850 ret
= Named_object::make_function(name
, NULL
, function
);
1854 else if (rtype
->forward_declaration_type() != NULL
)
1856 Named_object
* type_no
=
1857 rtype
->forward_declaration_type()->named_object();
1858 if (type_no
->is_unknown())
1860 // If we are seeing methods it really must be a
1861 // type. Declare it as such. An alternative would
1862 // be to support lists of methods for unknown
1863 // expressions. Either way the error messages if
1864 // this is not a type are going to get confusing.
1865 Named_object
* declared
=
1866 this->declare_package_type(type_no
->name(),
1867 type_no
->location());
1869 == type_no
->unknown_value()->real_named_object());
1871 ret
= rtype
->forward_declaration_type()->add_method(name
,
1876 go_error_at(type
->receiver()->location(),
1877 ("invalid receiver type (receiver must "
1878 "be a named type)"));
1879 ret
= Named_object::make_function(name
, NULL
, function
);
1882 this->package_
->bindings()->add_method(ret
);
1885 this->functions_
.resize(this->functions_
.size() + 1);
1886 Open_function
& of(this->functions_
.back());
1888 of
.blocks
.push_back(block
);
1892 this->init_functions_
.push_back(ret
);
1893 this->need_init_fn_
= true;
1899 // Finish compiling a function.
1902 Gogo::finish_function(Location location
)
1904 this->finish_block(location
);
1905 go_assert(this->functions_
.back().blocks
.empty());
1906 this->functions_
.pop_back();
1909 // Return the current function.
1912 Gogo::current_function() const
1914 go_assert(!this->functions_
.empty());
1915 return this->functions_
.back().function
;
1918 // Start a new block.
1921 Gogo::start_block(Location location
)
1923 go_assert(!this->functions_
.empty());
1924 Block
* block
= new Block(this->current_block(), location
);
1925 this->functions_
.back().blocks
.push_back(block
);
1931 Gogo::finish_block(Location location
)
1933 go_assert(!this->functions_
.empty());
1934 go_assert(!this->functions_
.back().blocks
.empty());
1935 Block
* block
= this->functions_
.back().blocks
.back();
1936 this->functions_
.back().blocks
.pop_back();
1937 block
->set_end_location(location
);
1941 // Add an erroneous name.
1944 Gogo::add_erroneous_name(const std::string
& name
)
1946 return this->package_
->bindings()->add_erroneous_name(name
);
1949 // Add an unknown name.
1952 Gogo::add_unknown_name(const std::string
& name
, Location location
)
1954 return this->package_
->bindings()->add_unknown_name(name
, location
);
1957 // Declare a function.
1960 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
1963 if (!type
->is_method())
1964 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
1968 // We don't bother to add this to the list of global
1970 Type
* rtype
= type
->receiver()->type();
1972 // We want to look through the pointer created by the
1973 // parser, without getting an error if the type is not yet
1975 if (rtype
->classification() == Type::TYPE_POINTER
)
1976 rtype
= rtype
->points_to();
1978 if (rtype
->is_error_type())
1980 else if (rtype
->named_type() != NULL
)
1981 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
1983 else if (rtype
->forward_declaration_type() != NULL
)
1985 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
1986 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
1990 go_error_at(type
->receiver()->location(),
1991 "invalid receiver type (receiver must be a named type)");
1992 return Named_object::make_erroneous_name(name
);
1997 // Add a label definition.
2000 Gogo::add_label_definition(const std::string
& label_name
,
2003 go_assert(!this->functions_
.empty());
2004 Function
* func
= this->functions_
.back().function
->func_value();
2005 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2006 this->add_statement(Statement::make_label_statement(label
, location
));
2010 // Add a label reference.
2013 Gogo::add_label_reference(const std::string
& label_name
,
2014 Location location
, bool issue_goto_errors
)
2016 go_assert(!this->functions_
.empty());
2017 Function
* func
= this->functions_
.back().function
->func_value();
2018 return func
->add_label_reference(this, label_name
, location
,
2022 // Return the current binding state.
2025 Gogo::bindings_snapshot(Location location
)
2027 return new Bindings_snapshot(this->current_block(), location
);
2033 Gogo::add_statement(Statement
* statement
)
2035 go_assert(!this->functions_
.empty()
2036 && !this->functions_
.back().blocks
.empty());
2037 this->functions_
.back().blocks
.back()->add_statement(statement
);
2043 Gogo::add_block(Block
* block
, Location location
)
2045 go_assert(!this->functions_
.empty()
2046 && !this->functions_
.back().blocks
.empty());
2047 Statement
* statement
= Statement::make_block_statement(block
, location
);
2048 this->functions_
.back().blocks
.back()->add_statement(statement
);
2054 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2057 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2063 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2065 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2067 if (!this->in_global_scope() && no
->is_type())
2069 Named_object
* f
= this->functions_
.back().function
;
2071 if (f
->is_function())
2072 index
= f
->func_value()->new_local_type_index();
2075 no
->type_value()->set_in_function(f
, index
);
2079 // Add a named type.
2082 Gogo::add_named_type(Named_type
* type
)
2084 go_assert(this->in_global_scope());
2085 this->current_bindings()->add_named_type(type
);
2091 Gogo::declare_type(const std::string
& name
, Location location
)
2093 Bindings
* bindings
= this->current_bindings();
2094 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2095 if (!this->in_global_scope() && no
->is_type_declaration())
2097 Named_object
* f
= this->functions_
.back().function
;
2099 if (f
->is_function())
2100 index
= f
->func_value()->new_local_type_index();
2103 no
->type_declaration_value()->set_in_function(f
, index
);
2108 // Declare a type at the package level.
2111 Gogo::declare_package_type(const std::string
& name
, Location location
)
2113 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2116 // Declare a function at the package level.
2119 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2122 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2126 // Define a type which was already declared.
2129 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2131 this->current_bindings()->define_type(no
, type
);
2137 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2139 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2142 // In a function the middle-end wants to see a DECL_EXPR node.
2144 && no
->is_variable()
2145 && !no
->var_value()->is_parameter()
2146 && !this->functions_
.empty())
2147 this->add_statement(Statement::make_variable_declaration(no
));
2152 // Add a sink--a reference to the blank identifier _.
2157 return Named_object::make_sink();
2160 // Add a named object for a dot import.
2163 Gogo::add_dot_import_object(Named_object
* no
)
2165 // If the name already exists, then it was defined in some file seen
2166 // earlier. If the earlier name is just a declaration, don't add
2167 // this name, because that will cause the previous declaration to
2168 // merge to this imported name, which should not happen. Just add
2169 // this name to the list of file block names to get appropriate
2170 // errors if we see a later definition.
2171 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2172 if (e
!= NULL
&& e
->package() == NULL
)
2174 if (e
->is_unknown())
2176 if (e
->package() == NULL
2177 && (e
->is_type_declaration()
2178 || e
->is_function_declaration()
2179 || e
->is_unknown()))
2181 this->add_file_block_name(no
->name(), no
->location());
2186 this->current_bindings()->add_named_object(no
);
2189 // Add a linkname. This implements the go:linkname compiler directive.
2190 // We only support this for functions and function declarations.
2193 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2194 const std::string
& ext_name
, Location loc
)
2197 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2200 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2201 else if (no
->is_function())
2202 no
->func_value()->set_asm_name(ext_name
);
2203 else if (no
->is_function_declaration())
2204 no
->func_declaration_value()->set_asm_name(ext_name
);
2207 ("%s is not a function; "
2208 "//go:linkname is only supported for functions"),
2212 // Mark all local variables used. This is used when some types of
2213 // parse error occur.
2216 Gogo::mark_locals_used()
2218 for (Open_functions::iterator pf
= this->functions_
.begin();
2219 pf
!= this->functions_
.end();
2222 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2223 pb
!= pf
->blocks
.end();
2225 (*pb
)->bindings()->mark_locals_used();
2229 // Record that we've seen an interface type.
2232 Gogo::record_interface_type(Interface_type
* itype
)
2234 this->interface_types_
.push_back(itype
);
2237 // Define the global names. We do this only after parsing all the
2238 // input files, because the program might define the global names
2242 Gogo::define_global_names()
2244 if (this->is_main_package())
2246 // Every Go program has to import the runtime package, so that
2247 // it is properly initialized.
2248 this->import_package("runtime", "_", false, false,
2249 Linemap::predeclared_location());
2252 for (Bindings::const_declarations_iterator p
=
2253 this->globals_
->begin_declarations();
2254 p
!= this->globals_
->end_declarations();
2257 Named_object
* global_no
= p
->second
;
2258 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2259 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2263 if (no
->is_type_declaration())
2265 if (global_no
->is_type())
2267 if (no
->type_declaration_value()->has_methods())
2269 for (std::vector
<Named_object
*>::const_iterator p
=
2270 no
->type_declaration_value()->methods()->begin();
2271 p
!= no
->type_declaration_value()->methods()->end();
2273 go_error_at((*p
)->location(),
2274 "may not define methods on non-local type");
2276 no
->set_type_value(global_no
->type_value());
2280 go_error_at(no
->location(), "expected type");
2281 Type
* errtype
= Type::make_error_type();
2283 Named_object::make_type("erroneous_type", NULL
, errtype
,
2284 Linemap::predeclared_location());
2285 no
->set_type_value(err
->type_value());
2288 else if (no
->is_unknown())
2289 no
->unknown_value()->set_real_named_object(global_no
);
2292 // Give an error if any name is defined in both the package block
2293 // and the file block. For example, this can happen if one file
2294 // imports "fmt" and another file defines a global variable fmt.
2295 for (Bindings::const_declarations_iterator p
=
2296 this->package_
->bindings()->begin_declarations();
2297 p
!= this->package_
->bindings()->end_declarations();
2300 if (p
->second
->is_unknown()
2301 && p
->second
->unknown_value()->real_named_object() == NULL
)
2303 // No point in warning about an undefined name, as we will
2304 // get other errors later anyhow.
2307 File_block_names::const_iterator pf
=
2308 this->file_block_names_
.find(p
->second
->name());
2309 if (pf
!= this->file_block_names_
.end())
2311 std::string n
= p
->second
->message_name();
2312 go_error_at(p
->second
->location(),
2313 "%qs defined as both imported name and global name",
2315 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2318 // No package scope identifier may be named "init".
2319 if (!p
->second
->is_function()
2320 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2322 go_error_at(p
->second
->location(),
2323 "cannot declare init - must be func");
2328 // Clear out names in file scope.
2331 Gogo::clear_file_scope()
2333 this->package_
->bindings()->clear_file_scope(this);
2335 // Warn about packages which were imported but not used.
2336 bool quiet
= saw_errors();
2337 for (Packages::iterator p
= this->packages_
.begin();
2338 p
!= this->packages_
.end();
2341 Package
* package
= p
->second
;
2342 if (package
!= this->package_
&& !quiet
)
2344 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2345 p1
!= package
->aliases().end();
2348 if (!p1
->second
->used())
2350 // Give a more refined error message if the alias name is known.
2351 std::string pkg_name
= package
->package_name();
2352 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2354 go_error_at(p1
->second
->location(),
2355 "imported and not used: %s as %s",
2356 Gogo::message_name(pkg_name
).c_str(),
2357 Gogo::message_name(p1
->first
).c_str());
2360 go_error_at(p1
->second
->location(),
2361 "imported and not used: %s",
2362 Gogo::message_name(pkg_name
).c_str());
2366 package
->clear_used();
2369 this->current_file_imported_unsafe_
= false;
2372 // Queue up a type specific function for later writing. These are
2373 // written out in write_specific_type_functions, called after the
2374 // parse tree is lowered.
2377 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
, int64_t size
,
2378 const std::string
& hash_name
,
2379 Function_type
* hash_fntype
,
2380 const std::string
& equal_name
,
2381 Function_type
* equal_fntype
)
2383 go_assert(!this->specific_type_functions_are_written_
);
2384 go_assert(!this->in_global_scope());
2385 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2390 this->specific_type_functions_
.push_back(tsf
);
2393 // Look for types which need specific hash or equality functions.
2395 class Specific_type_functions
: public Traverse
2398 Specific_type_functions(Gogo
* gogo
)
2399 : Traverse(traverse_types
),
2411 Specific_type_functions::type(Type
* t
)
2413 Named_object
* hash_fn
;
2414 Named_object
* equal_fn
;
2415 switch (t
->classification())
2417 case Type::TYPE_NAMED
:
2419 Named_type
* nt
= t
->named_type();
2421 return TRAVERSE_CONTINUE
;
2422 if (t
->needs_specific_type_functions(this->gogo_
))
2423 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2425 // If this is a struct type, we don't want to make functions
2426 // for the unnamed struct.
2427 Type
* rt
= nt
->real_type();
2428 if (rt
->struct_type() == NULL
)
2430 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2431 return TRAVERSE_EXIT
;
2435 // If this type is defined in another package, then we don't
2436 // need to worry about the unexported fields.
2437 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2438 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2439 for (Struct_field_list::const_iterator p
= fields
->begin();
2443 if (is_defined_elsewhere
2444 && Gogo::is_hidden_name(p
->field_name()))
2446 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2447 return TRAVERSE_EXIT
;
2451 return TRAVERSE_SKIP_COMPONENTS
;
2454 case Type::TYPE_STRUCT
:
2455 case Type::TYPE_ARRAY
:
2456 if (t
->needs_specific_type_functions(this->gogo_
))
2457 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2464 return TRAVERSE_CONTINUE
;
2467 // Write out type specific functions.
2470 Gogo::write_specific_type_functions()
2472 Specific_type_functions
stf(this);
2473 this->traverse(&stf
);
2475 while (!this->specific_type_functions_
.empty())
2477 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2478 this->specific_type_functions_
.pop_back();
2479 tsf
->type
->write_specific_type_functions(this, tsf
->name
, tsf
->size
,
2486 this->specific_type_functions_are_written_
= true;
2489 // Traverse the tree.
2492 Gogo::traverse(Traverse
* traverse
)
2494 // Traverse the current package first for consistency. The other
2495 // packages will only contain imported types, constants, and
2497 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2499 for (Packages::const_iterator p
= this->packages_
.begin();
2500 p
!= this->packages_
.end();
2503 if (p
->second
!= this->package_
)
2505 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2511 // Add a type to verify. This is used for types of sink variables, in
2512 // order to give appropriate error messages.
2515 Gogo::add_type_to_verify(Type
* type
)
2517 this->verify_types_
.push_back(type
);
2520 // Traversal class used to verify types.
2522 class Verify_types
: public Traverse
2526 : Traverse(traverse_types
)
2533 // Verify that a type is correct.
2536 Verify_types::type(Type
* t
)
2539 return TRAVERSE_SKIP_COMPONENTS
;
2540 return TRAVERSE_CONTINUE
;
2543 // Verify that all types are correct.
2546 Gogo::verify_types()
2548 Verify_types traverse
;
2549 this->traverse(&traverse
);
2551 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2552 p
!= this->verify_types_
.end();
2555 this->verify_types_
.clear();
2558 // Traversal class used to lower parse tree.
2560 class Lower_parse_tree
: public Traverse
2563 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2564 : Traverse(traverse_variables
2565 | traverse_constants
2566 | traverse_functions
2567 | traverse_statements
2568 | traverse_expressions
),
2569 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2573 set_inserter(const Statement_inserter
* inserter
)
2574 { this->inserter_
= *inserter
; }
2577 variable(Named_object
*);
2580 constant(Named_object
*, bool);
2583 function(Named_object
*);
2586 statement(Block
*, size_t* pindex
, Statement
*);
2589 expression(Expression
**);
2594 // The function we are traversing.
2595 Named_object
* function_
;
2596 // Value to use for the predeclared constant iota.
2598 // Current statement inserter for use by expressions.
2599 Statement_inserter inserter_
;
2605 Lower_parse_tree::variable(Named_object
* no
)
2607 if (!no
->is_variable())
2608 return TRAVERSE_CONTINUE
;
2610 if (no
->is_variable() && no
->var_value()->is_global())
2612 // Global variables can have loops in their initialization
2613 // expressions. This is handled in lower_init_expression.
2614 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2616 return TRAVERSE_CONTINUE
;
2619 // This is a local variable. We are going to return
2620 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2621 // initialization expression when we reach the variable declaration
2622 // statement. However, that means that we need to traverse the type
2624 if (no
->var_value()->has_type())
2626 Type
* type
= no
->var_value()->type();
2629 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2630 return TRAVERSE_EXIT
;
2633 go_assert(!no
->var_value()->has_pre_init());
2635 return TRAVERSE_SKIP_COMPONENTS
;
2638 // Lower constants. We handle constants specially so that we can set
2639 // the right value for the predeclared constant iota. This works in
2640 // conjunction with the way we lower Const_expression objects.
2643 Lower_parse_tree::constant(Named_object
* no
, bool)
2645 Named_constant
* nc
= no
->const_value();
2647 // Don't get into trouble if the constant's initializer expression
2648 // refers to the constant itself.
2650 return TRAVERSE_CONTINUE
;
2653 go_assert(this->iota_value_
== -1);
2654 this->iota_value_
= nc
->iota_value();
2655 nc
->traverse_expression(this);
2656 this->iota_value_
= -1;
2658 nc
->clear_lowering();
2660 // We will traverse the expression a second time, but that will be
2663 return TRAVERSE_CONTINUE
;
2666 // Lower the body of a function, and set the closure type. Record the
2667 // function while lowering it, so that we can pass it down when
2668 // lowering an expression.
2671 Lower_parse_tree::function(Named_object
* no
)
2673 no
->func_value()->set_closure_type();
2675 go_assert(this->function_
== NULL
);
2676 this->function_
= no
;
2677 int t
= no
->func_value()->traverse(this);
2678 this->function_
= NULL
;
2680 if (t
== TRAVERSE_EXIT
)
2682 return TRAVERSE_SKIP_COMPONENTS
;
2685 // Lower statement parse trees.
2688 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2690 // Because we explicitly traverse the statement's contents
2691 // ourselves, we want to skip block statements here. There is
2692 // nothing to lower in a block statement.
2693 if (sorig
->is_block_statement())
2694 return TRAVERSE_CONTINUE
;
2696 Statement_inserter
hold_inserter(this->inserter_
);
2697 this->inserter_
= Statement_inserter(block
, pindex
);
2699 // Lower the expressions first.
2700 int t
= sorig
->traverse_contents(this);
2701 if (t
== TRAVERSE_EXIT
)
2703 this->inserter_
= hold_inserter
;
2707 // Keep lowering until nothing changes.
2708 Statement
* s
= sorig
;
2711 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2716 t
= s
->traverse_contents(this);
2717 if (t
== TRAVERSE_EXIT
)
2719 this->inserter_
= hold_inserter
;
2725 block
->replace_statement(*pindex
, s
);
2727 this->inserter_
= hold_inserter
;
2728 return TRAVERSE_SKIP_COMPONENTS
;
2731 // Lower expression parse trees.
2734 Lower_parse_tree::expression(Expression
** pexpr
)
2736 // We have to lower all subexpressions first, so that we can get
2737 // their type if necessary. This is awkward, because we don't have
2738 // a postorder traversal pass.
2739 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2740 return TRAVERSE_EXIT
;
2741 // Keep lowering until nothing changes.
2744 Expression
* e
= *pexpr
;
2745 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2746 &this->inserter_
, this->iota_value_
);
2749 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2750 return TRAVERSE_EXIT
;
2753 return TRAVERSE_SKIP_COMPONENTS
;
2756 // Lower the parse tree. This is called after the parse is complete,
2757 // when all names should be resolved.
2760 Gogo::lower_parse_tree()
2762 Lower_parse_tree
lower_parse_tree(this, NULL
);
2763 this->traverse(&lower_parse_tree
);
2765 // There might be type definitions that involve expressions such as the
2766 // array length. Make sure to lower these expressions as well. Otherwise,
2767 // errors hidden within a type can introduce unexpected errors into later
2769 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2770 p
!= this->verify_types_
.end();
2772 Type::traverse(*p
, &lower_parse_tree
);
2778 Gogo::lower_block(Named_object
* function
, Block
* block
)
2780 Lower_parse_tree
lower_parse_tree(this, function
);
2781 block
->traverse(&lower_parse_tree
);
2784 // Lower an expression. INSERTER may be NULL, in which case the
2785 // expression had better not need to create any temporaries.
2788 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2791 Lower_parse_tree
lower_parse_tree(this, function
);
2792 if (inserter
!= NULL
)
2793 lower_parse_tree
.set_inserter(inserter
);
2794 lower_parse_tree
.expression(pexpr
);
2797 // Lower a constant. This is called when lowering a reference to a
2798 // constant. We have to make sure that the constant has already been
2802 Gogo::lower_constant(Named_object
* no
)
2804 go_assert(no
->is_const());
2805 Lower_parse_tree
lower(this, NULL
);
2806 lower
.constant(no
, false);
2809 // Traverse the tree to create function descriptors as needed.
2811 class Create_function_descriptors
: public Traverse
2814 Create_function_descriptors(Gogo
* gogo
)
2815 : Traverse(traverse_functions
| traverse_expressions
),
2820 function(Named_object
*);
2823 expression(Expression
**);
2829 // Create a descriptor for every top-level exported function.
2832 Create_function_descriptors::function(Named_object
* no
)
2834 if (no
->is_function()
2835 && no
->func_value()->enclosing() == NULL
2836 && !no
->func_value()->is_method()
2837 && !Gogo::is_hidden_name(no
->name())
2838 && !Gogo::is_thunk(no
))
2839 no
->func_value()->descriptor(this->gogo_
, no
);
2841 return TRAVERSE_CONTINUE
;
2844 // If we see a function referenced in any way other than calling it,
2845 // create a descriptor for it.
2848 Create_function_descriptors::expression(Expression
** pexpr
)
2850 Expression
* expr
= *pexpr
;
2852 Func_expression
* fe
= expr
->func_expression();
2855 // We would not get here for a call to this function, so this is
2856 // a reference to a function other than calling it. We need a
2858 if (fe
->closure() != NULL
)
2859 return TRAVERSE_CONTINUE
;
2860 Named_object
* no
= fe
->named_object();
2861 if (no
->is_function() && !no
->func_value()->is_method())
2862 no
->func_value()->descriptor(this->gogo_
, no
);
2863 else if (no
->is_function_declaration()
2864 && !no
->func_declaration_value()->type()->is_method()
2865 && !Linemap::is_predeclared_location(no
->location()))
2866 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
2867 return TRAVERSE_CONTINUE
;
2870 Bound_method_expression
* bme
= expr
->bound_method_expression();
2873 // We would not get here for a call to this method, so this is a
2874 // method value. We need to create a thunk.
2875 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
2877 return TRAVERSE_CONTINUE
;
2880 Interface_field_reference_expression
* ifre
=
2881 expr
->interface_field_reference_expression();
2884 // We would not get here for a call to this interface method, so
2885 // this is a method value. We need to create a thunk.
2886 Interface_type
* type
= ifre
->expr()->type()->interface_type();
2888 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
2890 return TRAVERSE_CONTINUE
;
2893 Call_expression
* ce
= expr
->call_expression();
2896 Expression
* fn
= ce
->fn();
2897 if (fn
->func_expression() != NULL
2898 || fn
->bound_method_expression() != NULL
2899 || fn
->interface_field_reference_expression() != NULL
)
2901 // Traverse the arguments but not the function.
2902 Expression_list
* args
= ce
->args();
2905 if (args
->traverse(this) == TRAVERSE_EXIT
)
2906 return TRAVERSE_EXIT
;
2908 return TRAVERSE_SKIP_COMPONENTS
;
2912 return TRAVERSE_CONTINUE
;
2915 // Create function descriptors as needed. We need a function
2916 // descriptor for all exported functions and for all functions that
2917 // are referenced without being called.
2920 Gogo::create_function_descriptors()
2922 // Create a function descriptor for any exported function that is
2923 // declared in this package. This is so that we have a descriptor
2924 // for functions written in assembly. Gather the descriptors first
2925 // so that we don't add declarations while looping over them.
2926 std::vector
<Named_object
*> fndecls
;
2927 Bindings
* b
= this->package_
->bindings();
2928 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
2929 p
!= b
->end_declarations();
2932 Named_object
* no
= p
->second
;
2933 if (no
->is_function_declaration()
2934 && !no
->func_declaration_value()->type()->is_method()
2935 && !Linemap::is_predeclared_location(no
->location())
2936 && !Gogo::is_hidden_name(no
->name()))
2937 fndecls
.push_back(no
);
2939 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
2942 (*p
)->func_declaration_value()->descriptor(this, *p
);
2945 Create_function_descriptors
cfd(this);
2946 this->traverse(&cfd
);
2949 // Look for interface types to finalize methods of inherited
2952 class Finalize_methods
: public Traverse
2955 Finalize_methods(Gogo
* gogo
)
2956 : Traverse(traverse_types
),
2967 // Finalize the methods of an interface type.
2970 Finalize_methods::type(Type
* t
)
2972 // Check the classification so that we don't finalize the methods
2973 // twice for a named interface type.
2974 switch (t
->classification())
2976 case Type::TYPE_INTERFACE
:
2977 t
->interface_type()->finalize_methods();
2980 case Type::TYPE_NAMED
:
2982 Named_type
* nt
= t
->named_type();
2983 Type
* rt
= nt
->real_type();
2984 if (rt
->classification() != Type::TYPE_STRUCT
)
2986 // Finalize the methods of the real type first.
2987 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2988 return TRAVERSE_EXIT
;
2990 // Finalize the methods of this type.
2991 nt
->finalize_methods(this->gogo_
);
2995 // We don't want to finalize the methods of a named struct
2996 // type, as the methods should be attached to the named
2997 // type, not the struct type. We just want to finalize
3000 // It is possible that a field type refers indirectly to
3001 // this type, such as via a field with function type with
3002 // an argument or result whose type is this type. To
3003 // avoid the cycle, first finalize the methods of any
3004 // embedded types, which are the only types we need to
3005 // know to finalize the methods of this type.
3006 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3009 for (Struct_field_list::const_iterator pf
= fields
->begin();
3010 pf
!= fields
->end();
3013 if (pf
->is_anonymous())
3015 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3016 return TRAVERSE_EXIT
;
3021 // Finalize the methods of this type.
3022 nt
->finalize_methods(this->gogo_
);
3024 // Finalize all the struct fields.
3025 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3026 return TRAVERSE_EXIT
;
3029 // If this type is defined in a different package, then finalize the
3030 // types of all the methods, since we won't see them otherwise.
3031 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3033 const Methods
* methods
= nt
->methods();
3034 for (Methods::const_iterator p
= methods
->begin();
3035 p
!= methods
->end();
3038 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3039 return TRAVERSE_EXIT
;
3043 // Finalize the types of all methods that are declared but not
3044 // defined, since we won't see the declarations otherwise.
3045 if (nt
->named_object()->package() == NULL
3046 && nt
->local_methods() != NULL
)
3048 const Bindings
* methods
= nt
->local_methods();
3049 for (Bindings::const_declarations_iterator p
=
3050 methods
->begin_declarations();
3051 p
!= methods
->end_declarations();
3054 if (p
->second
->is_function_declaration())
3056 Type
* mt
= p
->second
->func_declaration_value()->type();
3057 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3058 return TRAVERSE_EXIT
;
3063 return TRAVERSE_SKIP_COMPONENTS
;
3066 case Type::TYPE_STRUCT
:
3067 // Traverse the field types first in case there is an embedded
3068 // field with methods that the struct should inherit.
3069 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3070 return TRAVERSE_EXIT
;
3071 t
->struct_type()->finalize_methods(this->gogo_
);
3072 return TRAVERSE_SKIP_COMPONENTS
;
3078 return TRAVERSE_CONTINUE
;
3081 // Finalize method lists and build stub methods for types.
3084 Gogo::finalize_methods()
3086 Finalize_methods
finalize(this);
3087 this->traverse(&finalize
);
3090 // Set types for unspecified variables and constants.
3093 Gogo::determine_types()
3095 Bindings
* bindings
= this->current_bindings();
3096 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3097 p
!= bindings
->end_definitions();
3100 if ((*p
)->is_function())
3101 (*p
)->func_value()->determine_types();
3102 else if ((*p
)->is_variable())
3103 (*p
)->var_value()->determine_type();
3104 else if ((*p
)->is_const())
3105 (*p
)->const_value()->determine_type();
3107 // See if a variable requires us to build an initialization
3108 // function. We know that we will see all global variables
3110 if (!this->need_init_fn_
&& (*p
)->is_variable())
3112 Variable
* variable
= (*p
)->var_value();
3114 // If this is a global variable which requires runtime
3115 // initialization, we need an initialization function.
3116 if (!variable
->is_global())
3118 else if (variable
->init() == NULL
)
3120 else if (variable
->type()->interface_type() != NULL
)
3121 this->need_init_fn_
= true;
3122 else if (variable
->init()->is_constant())
3124 else if (!variable
->init()->is_composite_literal())
3125 this->need_init_fn_
= true;
3126 else if (variable
->init()->is_nonconstant_composite_literal())
3127 this->need_init_fn_
= true;
3129 // If this is a global variable which holds a pointer value,
3130 // then we need an initialization function to register it as a
3132 if (variable
->is_global() && variable
->type()->has_pointer())
3133 this->need_init_fn_
= true;
3137 // Determine the types of constants in packages.
3138 for (Packages::const_iterator p
= this->packages_
.begin();
3139 p
!= this->packages_
.end();
3141 p
->second
->determine_types();
3144 // Traversal class used for type checking.
3146 class Check_types_traverse
: public Traverse
3149 Check_types_traverse(Gogo
* gogo
)
3150 : Traverse(traverse_variables
3151 | traverse_constants
3152 | traverse_functions
3153 | traverse_statements
3154 | traverse_expressions
),
3159 variable(Named_object
*);
3162 constant(Named_object
*, bool);
3165 function(Named_object
*);
3168 statement(Block
*, size_t* pindex
, Statement
*);
3171 expression(Expression
**);
3178 // Check that a variable initializer has the right type.
3181 Check_types_traverse::variable(Named_object
* named_object
)
3183 if (named_object
->is_variable())
3185 Variable
* var
= named_object
->var_value();
3187 // Give error if variable type is not defined.
3188 var
->type()->base();
3190 Expression
* init
= var
->init();
3193 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3196 go_error_at(var
->location(), "incompatible type in initialization");
3198 go_error_at(var
->location(),
3199 "incompatible type in initialization (%s)",
3201 init
= Expression::make_error(named_object
->location());
3204 else if (init
!= NULL
3205 && init
->func_expression() != NULL
)
3207 Named_object
* no
= init
->func_expression()->named_object();
3208 Function_type
* fntype
;
3209 if (no
->is_function())
3210 fntype
= no
->func_value()->type();
3211 else if (no
->is_function_declaration())
3212 fntype
= no
->func_declaration_value()->type();
3216 // Builtin functions cannot be used as function values for variable
3218 if (fntype
->is_builtin())
3220 go_error_at(init
->location(),
3221 "invalid use of special builtin function %qs; "
3223 no
->message_name().c_str());
3227 && !var
->is_global()
3228 && !var
->is_parameter()
3229 && !var
->is_receiver()
3230 && !var
->type()->is_error()
3231 && (init
== NULL
|| !init
->is_error_expression())
3232 && !Lex::is_invalid_identifier(named_object
->name()))
3233 go_error_at(var
->location(), "%qs declared and not used",
3234 named_object
->message_name().c_str());
3236 return TRAVERSE_CONTINUE
;
3239 // Check that a constant initializer has the right type.
3242 Check_types_traverse::constant(Named_object
* named_object
, bool)
3244 Named_constant
* constant
= named_object
->const_value();
3245 Type
* ctype
= constant
->type();
3246 if (ctype
->integer_type() == NULL
3247 && ctype
->float_type() == NULL
3248 && ctype
->complex_type() == NULL
3249 && !ctype
->is_boolean_type()
3250 && !ctype
->is_string_type())
3252 if (ctype
->is_nil_type())
3253 go_error_at(constant
->location(), "const initializer cannot be nil");
3254 else if (!ctype
->is_error())
3255 go_error_at(constant
->location(), "invalid constant type");
3256 constant
->set_error();
3258 else if (!constant
->expr()->is_constant())
3260 go_error_at(constant
->expr()->location(), "expression is not constant");
3261 constant
->set_error();
3263 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3266 go_error_at(constant
->location(),
3267 "initialization expression has wrong type");
3268 constant
->set_error();
3270 return TRAVERSE_CONTINUE
;
3273 // There are no types to check in a function, but this is where we
3274 // issue warnings about labels which are defined but not referenced.
3277 Check_types_traverse::function(Named_object
* no
)
3279 no
->func_value()->check_labels();
3280 return TRAVERSE_CONTINUE
;
3283 // Check that types are valid in a statement.
3286 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3288 s
->check_types(this->gogo_
);
3289 return TRAVERSE_CONTINUE
;
3292 // Check that types are valid in an expression.
3295 Check_types_traverse::expression(Expression
** expr
)
3297 (*expr
)->check_types(this->gogo_
);
3298 return TRAVERSE_CONTINUE
;
3301 // Check that types are valid.
3306 Check_types_traverse
traverse(this);
3307 this->traverse(&traverse
);
3309 Bindings
* bindings
= this->current_bindings();
3310 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3311 p
!= bindings
->end_declarations();
3314 // Also check the types in a function declaration's signature.
3315 Named_object
* no
= p
->second
;
3316 if (no
->is_function_declaration())
3317 no
->func_declaration_value()->check_types();
3321 // Check the types in a single block.
3324 Gogo::check_types_in_block(Block
* block
)
3326 Check_types_traverse
traverse(this);
3327 block
->traverse(&traverse
);
3330 // A traversal class used to find a single shortcut operator within an
3333 class Find_shortcut
: public Traverse
3337 : Traverse(traverse_blocks
3338 | traverse_statements
3339 | traverse_expressions
),
3343 // A pointer to the expression which was found, or NULL if none was
3347 { return this->found_
; }
3352 { return TRAVERSE_SKIP_COMPONENTS
; }
3355 statement(Block
*, size_t*, Statement
*)
3356 { return TRAVERSE_SKIP_COMPONENTS
; }
3359 expression(Expression
**);
3362 Expression
** found_
;
3365 // Find a shortcut expression.
3368 Find_shortcut::expression(Expression
** pexpr
)
3370 Expression
* expr
= *pexpr
;
3371 Binary_expression
* be
= expr
->binary_expression();
3373 return TRAVERSE_CONTINUE
;
3374 Operator op
= be
->op();
3375 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3376 return TRAVERSE_CONTINUE
;
3377 go_assert(this->found_
== NULL
);
3378 this->found_
= pexpr
;
3379 return TRAVERSE_EXIT
;
3382 // A traversal class used to turn shortcut operators into explicit if
3385 class Shortcuts
: public Traverse
3388 Shortcuts(Gogo
* gogo
)
3389 : Traverse(traverse_variables
3390 | traverse_statements
),
3396 variable(Named_object
*);
3399 statement(Block
*, size_t*, Statement
*);
3402 // Convert a shortcut operator.
3404 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3410 // Remove shortcut operators in a single statement.
3413 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3415 // FIXME: This approach doesn't work for switch statements, because
3416 // we add the new statements before the whole switch when we need to
3417 // instead add them just before the switch expression. The right
3418 // fix is probably to lower switch statements with nonconstant cases
3419 // to a series of conditionals.
3420 if (s
->switch_statement() != NULL
)
3421 return TRAVERSE_CONTINUE
;
3425 Find_shortcut find_shortcut
;
3427 // If S is a variable declaration, then ordinary traversal won't
3428 // do anything. We want to explicitly traverse the
3429 // initialization expression if there is one.
3430 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3431 Expression
* init
= NULL
;
3433 s
->traverse_contents(&find_shortcut
);
3436 init
= vds
->var()->var_value()->init();
3438 return TRAVERSE_CONTINUE
;
3439 init
->traverse(&init
, &find_shortcut
);
3441 Expression
** pshortcut
= find_shortcut
.found();
3442 if (pshortcut
== NULL
)
3443 return TRAVERSE_CONTINUE
;
3445 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3446 block
->insert_statement_before(*pindex
, snew
);
3449 if (pshortcut
== &init
)
3450 vds
->var()->var_value()->set_init(init
);
3454 // Remove shortcut operators in the initializer of a global variable.
3457 Shortcuts::variable(Named_object
* no
)
3459 if (no
->is_result_variable())
3460 return TRAVERSE_CONTINUE
;
3461 Variable
* var
= no
->var_value();
3462 Expression
* init
= var
->init();
3463 if (!var
->is_global() || init
== NULL
)
3464 return TRAVERSE_CONTINUE
;
3468 Find_shortcut find_shortcut
;
3469 init
->traverse(&init
, &find_shortcut
);
3470 Expression
** pshortcut
= find_shortcut
.found();
3471 if (pshortcut
== NULL
)
3472 return TRAVERSE_CONTINUE
;
3474 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3475 var
->add_preinit_statement(this->gogo_
, snew
);
3476 if (pshortcut
== &init
)
3477 var
->set_init(init
);
3481 // Given an expression which uses a shortcut operator, return a
3482 // statement which implements it, and update *PSHORTCUT accordingly.
3485 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3487 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3488 Expression
* left
= shortcut
->left();
3489 Expression
* right
= shortcut
->right();
3490 Location loc
= shortcut
->location();
3492 Block
* retblock
= new Block(enclosing
, loc
);
3493 retblock
->set_end_location(loc
);
3495 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3497 retblock
->add_statement(ts
);
3499 Block
* block
= new Block(retblock
, loc
);
3500 block
->set_end_location(loc
);
3501 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
3502 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
3503 block
->add_statement(assign
);
3505 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
3506 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
3507 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
3509 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
3511 retblock
->add_statement(if_statement
);
3513 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
3517 // Now convert any shortcut operators in LEFT and RIGHT.
3518 Shortcuts
shortcuts(this->gogo_
);
3519 retblock
->traverse(&shortcuts
);
3521 return Statement::make_block_statement(retblock
, loc
);
3524 // Turn shortcut operators into explicit if statements. Doing this
3525 // considerably simplifies the order of evaluation rules.
3528 Gogo::remove_shortcuts()
3530 Shortcuts
shortcuts(this);
3531 this->traverse(&shortcuts
);
3534 // A traversal class which finds all the expressions which must be
3535 // evaluated in order within a statement or larger expression. This
3536 // is used to implement the rules about order of evaluation.
3538 class Find_eval_ordering
: public Traverse
3541 typedef std::vector
<Expression
**> Expression_pointers
;
3544 Find_eval_ordering()
3545 : Traverse(traverse_blocks
3546 | traverse_statements
3547 | traverse_expressions
),
3553 { return this->exprs_
.size(); }
3555 typedef Expression_pointers::const_iterator const_iterator
;
3559 { return this->exprs_
.begin(); }
3563 { return this->exprs_
.end(); }
3568 { return TRAVERSE_SKIP_COMPONENTS
; }
3571 statement(Block
*, size_t*, Statement
*)
3572 { return TRAVERSE_SKIP_COMPONENTS
; }
3575 expression(Expression
**);
3578 // A list of pointers to expressions with side-effects.
3579 Expression_pointers exprs_
;
3582 // If an expression must be evaluated in order, put it on the list.
3585 Find_eval_ordering::expression(Expression
** expression_pointer
)
3587 // We have to look at subexpressions before this one.
3588 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3589 return TRAVERSE_EXIT
;
3590 if ((*expression_pointer
)->must_eval_in_order())
3591 this->exprs_
.push_back(expression_pointer
);
3592 return TRAVERSE_SKIP_COMPONENTS
;
3595 // A traversal class for ordering evaluations.
3597 class Order_eval
: public Traverse
3600 Order_eval(Gogo
* gogo
)
3601 : Traverse(traverse_variables
3602 | traverse_statements
),
3607 variable(Named_object
*);
3610 statement(Block
*, size_t*, Statement
*);
3617 // Implement the order of evaluation rules for a statement.
3620 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3622 // FIXME: This approach doesn't work for switch statements, because
3623 // we add the new statements before the whole switch when we need to
3624 // instead add them just before the switch expression. The right
3625 // fix is probably to lower switch statements with nonconstant cases
3626 // to a series of conditionals.
3627 if (stmt
->switch_statement() != NULL
)
3628 return TRAVERSE_CONTINUE
;
3630 Find_eval_ordering find_eval_ordering
;
3632 // If S is a variable declaration, then ordinary traversal won't do
3633 // anything. We want to explicitly traverse the initialization
3634 // expression if there is one.
3635 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
3636 Expression
* init
= NULL
;
3637 Expression
* orig_init
= NULL
;
3639 stmt
->traverse_contents(&find_eval_ordering
);
3642 init
= vds
->var()->var_value()->init();
3644 return TRAVERSE_CONTINUE
;
3647 // It might seem that this could be
3648 // init->traverse_subexpressions. Unfortunately that can fail
3651 // newvar, err := call(arg())
3652 // Here newvar will have an init of call result 0 of
3653 // call(arg()). If we only traverse subexpressions, we will
3654 // only find arg(), and we won't bother to move anything out.
3655 // Then we get to the assignment to err, we will traverse the
3656 // whole statement, and this time we will find both call() and
3657 // arg(), and so we will move them out. This will cause them to
3658 // be put into temporary variables before the assignment to err
3659 // but after the declaration of newvar. To avoid that problem,
3660 // we traverse the entire expression here.
3661 Expression::traverse(&init
, &find_eval_ordering
);
3664 size_t c
= find_eval_ordering
.size();
3666 return TRAVERSE_CONTINUE
;
3668 // If there is only one expression with a side-effect, we can
3669 // usually leave it in place.
3672 switch (stmt
->classification())
3674 case Statement::STATEMENT_ASSIGNMENT
:
3675 // For an assignment statement, we need to evaluate an
3676 // expression on the right hand side before we evaluate any
3677 // index expression on the left hand side, so for that case
3678 // we always move the expression. Otherwise we mishandle
3679 // m[0] = len(m) where m is a map.
3682 case Statement::STATEMENT_EXPRESSION
:
3684 // If this is a call statement that doesn't return any
3685 // values, it will not have been counted as a value to
3686 // move. We need to move any subexpressions in case they
3687 // are themselves call statements that require passing a
3689 Expression
* expr
= stmt
->expression_statement()->expr();
3690 if (expr
->call_expression() != NULL
3691 && expr
->call_expression()->result_count() == 0)
3693 return TRAVERSE_CONTINUE
;
3697 // We can leave the expression in place.
3698 return TRAVERSE_CONTINUE
;
3702 bool is_thunk
= stmt
->thunk_statement() != NULL
;
3703 Expression_statement
* es
= stmt
->expression_statement();
3704 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3705 p
!= find_eval_ordering
.end();
3708 Expression
** pexpr
= *p
;
3710 // The last expression in a thunk will be the call passed to go
3711 // or defer, which we must not evaluate early.
3712 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3715 Location loc
= (*pexpr
)->location();
3717 if ((*pexpr
)->call_expression() == NULL
3718 || (*pexpr
)->call_expression()->result_count() < 2)
3720 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3723 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3727 // A call expression which returns multiple results needs to
3728 // be handled specially. We can't create a temporary
3729 // because there is no type to give it. Any actual uses of
3730 // the values will be done via Call_result_expressions.
3732 // Since a given call expression can be shared by multiple
3733 // Call_result_expressions, avoid hoisting the call the
3734 // second time we see it here. In addition, don't try to
3735 // hoist the top-level multi-return call in the statement,
3736 // since doing this would result a tree with more than one copy
3738 if (this->remember_expression(*pexpr
))
3740 else if (es
!= NULL
&& *pexpr
== es
->expr())
3743 s
= Statement::make_statement(*pexpr
, true);
3748 block
->insert_statement_before(*pindex
, s
);
3753 if (init
!= orig_init
)
3754 vds
->var()->var_value()->set_init(init
);
3756 return TRAVERSE_CONTINUE
;
3759 // Implement the order of evaluation rules for the initializer of a
3763 Order_eval::variable(Named_object
* no
)
3765 if (no
->is_result_variable())
3766 return TRAVERSE_CONTINUE
;
3767 Variable
* var
= no
->var_value();
3768 Expression
* init
= var
->init();
3769 if (!var
->is_global() || init
== NULL
)
3770 return TRAVERSE_CONTINUE
;
3772 Find_eval_ordering find_eval_ordering
;
3773 Expression::traverse(&init
, &find_eval_ordering
);
3775 if (find_eval_ordering
.size() <= 1)
3777 // If there is only one expression with a side-effect, we can
3778 // leave it in place.
3779 return TRAVERSE_SKIP_COMPONENTS
;
3782 Expression
* orig_init
= init
;
3784 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3785 p
!= find_eval_ordering
.end();
3788 Expression
** pexpr
= *p
;
3789 Location loc
= (*pexpr
)->location();
3791 if ((*pexpr
)->call_expression() == NULL
3792 || (*pexpr
)->call_expression()->result_count() < 2)
3794 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3797 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3801 // A call expression which returns multiple results needs to
3802 // be handled specially.
3803 s
= Statement::make_statement(*pexpr
, true);
3805 var
->add_preinit_statement(this->gogo_
, s
);
3808 if (init
!= orig_init
)
3809 var
->set_init(init
);
3811 return TRAVERSE_SKIP_COMPONENTS
;
3814 // Use temporary variables to implement the order of evaluation rules.
3817 Gogo::order_evaluations()
3819 Order_eval
order_eval(this);
3820 this->traverse(&order_eval
);
3823 // Traversal to flatten parse tree after order of evaluation rules are applied.
3825 class Flatten
: public Traverse
3828 Flatten(Gogo
* gogo
, Named_object
* function
)
3829 : Traverse(traverse_variables
3830 | traverse_functions
3831 | traverse_statements
3832 | traverse_expressions
),
3833 gogo_(gogo
), function_(function
), inserter_()
3837 set_inserter(const Statement_inserter
* inserter
)
3838 { this->inserter_
= *inserter
; }
3841 variable(Named_object
*);
3844 function(Named_object
*);
3847 statement(Block
*, size_t* pindex
, Statement
*);
3850 expression(Expression
**);
3855 // The function we are traversing.
3856 Named_object
* function_
;
3857 // Current statement inserter for use by expressions.
3858 Statement_inserter inserter_
;
3861 // Flatten variables.
3864 Flatten::variable(Named_object
* no
)
3866 if (!no
->is_variable())
3867 return TRAVERSE_CONTINUE
;
3869 if (no
->is_variable() && no
->var_value()->is_global())
3871 // Global variables can have loops in their initialization
3872 // expressions. This is handled in flatten_init_expression.
3873 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
3875 return TRAVERSE_CONTINUE
;
3878 go_assert(!no
->var_value()->has_pre_init());
3880 return TRAVERSE_SKIP_COMPONENTS
;
3883 // Flatten the body of a function. Record the function while flattening it,
3884 // so that we can pass it down when flattening an expression.
3887 Flatten::function(Named_object
* no
)
3889 go_assert(this->function_
== NULL
);
3890 this->function_
= no
;
3891 int t
= no
->func_value()->traverse(this);
3892 this->function_
= NULL
;
3894 if (t
== TRAVERSE_EXIT
)
3896 return TRAVERSE_SKIP_COMPONENTS
;
3899 // Flatten statement parse trees.
3902 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3904 // Because we explicitly traverse the statement's contents
3905 // ourselves, we want to skip block statements here. There is
3906 // nothing to flatten in a block statement.
3907 if (sorig
->is_block_statement())
3908 return TRAVERSE_CONTINUE
;
3910 Statement_inserter
hold_inserter(this->inserter_
);
3911 this->inserter_
= Statement_inserter(block
, pindex
);
3913 // Flatten the expressions first.
3914 int t
= sorig
->traverse_contents(this);
3915 if (t
== TRAVERSE_EXIT
)
3917 this->inserter_
= hold_inserter
;
3921 // Keep flattening until nothing changes.
3922 Statement
* s
= sorig
;
3925 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
3930 t
= s
->traverse_contents(this);
3931 if (t
== TRAVERSE_EXIT
)
3933 this->inserter_
= hold_inserter
;
3939 block
->replace_statement(*pindex
, s
);
3941 this->inserter_
= hold_inserter
;
3942 return TRAVERSE_SKIP_COMPONENTS
;
3945 // Flatten expression parse trees.
3948 Flatten::expression(Expression
** pexpr
)
3950 // Keep flattening until nothing changes.
3953 Expression
* e
= *pexpr
;
3954 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3955 return TRAVERSE_EXIT
;
3957 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
3963 return TRAVERSE_SKIP_COMPONENTS
;
3969 Gogo::flatten_block(Named_object
* function
, Block
* block
)
3971 Flatten
flatten(this, function
);
3972 block
->traverse(&flatten
);
3975 // Flatten an expression. INSERTER may be NULL, in which case the
3976 // expression had better not need to create any temporaries.
3979 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
3982 Flatten
flatten(this, function
);
3983 if (inserter
!= NULL
)
3984 flatten
.set_inserter(inserter
);
3985 flatten
.expression(pexpr
);
3991 Flatten
flatten(this, NULL
);
3992 this->traverse(&flatten
);
3995 // Traversal to convert calls to the predeclared recover function to
3996 // pass in an argument indicating whether it can recover from a panic
3999 class Convert_recover
: public Traverse
4002 Convert_recover(Named_object
* arg
)
4003 : Traverse(traverse_expressions
),
4009 expression(Expression
**);
4012 // The argument to pass to the function.
4016 // Convert calls to recover.
4019 Convert_recover::expression(Expression
** pp
)
4021 Call_expression
* ce
= (*pp
)->call_expression();
4022 if (ce
!= NULL
&& ce
->is_recover_call())
4023 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4025 return TRAVERSE_CONTINUE
;
4028 // Traversal for build_recover_thunks.
4030 class Build_recover_thunks
: public Traverse
4033 Build_recover_thunks(Gogo
* gogo
)
4034 : Traverse(traverse_functions
),
4039 function(Named_object
*);
4043 can_recover_arg(Location
);
4049 // If this function calls recover, turn it into a thunk.
4052 Build_recover_thunks::function(Named_object
* orig_no
)
4054 Function
* orig_func
= orig_no
->func_value();
4055 if (!orig_func
->calls_recover()
4056 || orig_func
->is_recover_thunk()
4057 || orig_func
->has_recover_thunk())
4058 return TRAVERSE_CONTINUE
;
4060 Gogo
* gogo
= this->gogo_
;
4061 Location location
= orig_func
->location();
4066 Function_type
* orig_fntype
= orig_func
->type();
4067 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4068 std::string receiver_name
;
4069 if (orig_fntype
->is_method())
4071 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4072 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4074 receiver_name
= buf
;
4075 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4076 receiver
->location()));
4078 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4079 if (orig_params
!= NULL
&& !orig_params
->empty())
4081 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4082 p
!= orig_params
->end();
4085 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4087 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4091 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4093 std::string can_recover_name
= buf
;
4094 new_params
->push_back(Typed_identifier(can_recover_name
,
4095 Type::lookup_bool_type(),
4096 orig_fntype
->location()));
4098 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4099 Typed_identifier_list
* new_results
;
4100 if (orig_results
== NULL
|| orig_results
->empty())
4104 new_results
= new Typed_identifier_list();
4105 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4106 p
!= orig_results
->end();
4108 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4111 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4113 orig_fntype
->location());
4114 if (orig_fntype
->is_varargs())
4115 new_fntype
->set_is_varargs();
4118 if (orig_fntype
->is_method())
4119 rtype
= orig_fntype
->receiver()->type();
4120 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4121 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4123 Function
*new_func
= new_no
->func_value();
4124 if (orig_func
->enclosing() != NULL
)
4125 new_func
->set_enclosing(orig_func
->enclosing());
4127 // We build the code for the original function attached to the new
4128 // function, and then swap the original and new function bodies.
4129 // This means that existing references to the original function will
4130 // then refer to the new function. That makes this code a little
4131 // confusing, in that the reference to NEW_NO really refers to the
4132 // other function, not the one we are building.
4134 Expression
* closure
= NULL
;
4135 if (orig_func
->needs_closure())
4137 // For the new function we are creating, declare a new parameter
4138 // variable NEW_CLOSURE_NO and set it to be the closure variable
4139 // of the function. This will be set to the closure value
4140 // passed in by the caller. Then pass a reference to this
4141 // variable as the closure value when calling the original
4142 // function. In other words, simply pass the closure value
4143 // through the thunk we are creating.
4144 Named_object
* orig_closure_no
= orig_func
->closure_var();
4145 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4146 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4147 false, false, location
);
4148 new_var
->set_is_closure();
4149 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4151 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4153 new_func
->set_closure_var(new_closure_no
);
4154 closure
= Expression::make_var_reference(new_closure_no
, location
);
4157 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4159 Expression_list
* args
= new Expression_list();
4160 if (new_params
!= NULL
)
4162 // Note that we skip the last parameter, which is the boolean
4163 // indicating whether recover can succed.
4164 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4165 p
+ 1 != new_params
->end();
4168 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4169 go_assert(p_no
!= NULL
4170 && p_no
->is_variable()
4171 && p_no
->var_value()->is_parameter());
4172 args
->push_back(Expression::make_var_reference(p_no
, location
));
4175 args
->push_back(this->can_recover_arg(location
));
4177 gogo
->start_block(location
);
4179 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4181 // Any varargs call has already been lowered.
4182 call
->set_varargs_are_lowered();
4184 Statement
* s
= Statement::make_return_from_call(call
, location
);
4185 s
->determine_types();
4186 gogo
->add_statement(s
);
4188 Block
* b
= gogo
->finish_block(location
);
4190 gogo
->add_block(b
, location
);
4192 // Lower the call in case it returns multiple results.
4193 gogo
->lower_block(new_no
, b
);
4195 gogo
->finish_function(location
);
4197 // Swap the function bodies and types.
4198 new_func
->swap_for_recover(orig_func
);
4199 orig_func
->set_is_recover_thunk();
4200 new_func
->set_calls_recover();
4201 new_func
->set_has_recover_thunk();
4203 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4204 Bindings
* new_bindings
= new_func
->block()->bindings();
4205 if (orig_fntype
->is_method())
4207 // We changed the receiver to be a regular parameter. We have
4208 // to update the binding accordingly in both functions.
4209 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4210 go_assert(orig_rec_no
!= NULL
4211 && orig_rec_no
->is_variable()
4212 && !orig_rec_no
->var_value()->is_receiver());
4213 orig_rec_no
->var_value()->set_is_receiver();
4215 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4216 if (new_receiver_name
.empty())
4218 // Find the receiver. It was named "r.NNN" in
4219 // Gogo::start_function.
4220 for (Bindings::const_definitions_iterator p
=
4221 new_bindings
->begin_definitions();
4222 p
!= new_bindings
->end_definitions();
4225 const std::string
& pname((*p
)->name());
4226 if (pname
[0] == 'r' && pname
[1] == '.')
4228 new_receiver_name
= pname
;
4232 go_assert(!new_receiver_name
.empty());
4234 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4235 if (new_rec_no
== NULL
)
4236 go_assert(saw_errors());
4239 go_assert(new_rec_no
->is_variable()
4240 && new_rec_no
->var_value()->is_receiver());
4241 new_rec_no
->var_value()->set_is_not_receiver();
4245 // Because we flipped blocks but not types, the can_recover
4246 // parameter appears in the (now) old bindings as a parameter.
4247 // Change it to a local variable, whereupon it will be discarded.
4248 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4249 go_assert(can_recover_no
!= NULL
4250 && can_recover_no
->is_variable()
4251 && can_recover_no
->var_value()->is_parameter());
4252 orig_bindings
->remove_binding(can_recover_no
);
4254 // Add the can_recover argument to the (now) new bindings, and
4255 // attach it to any recover statements.
4256 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4257 false, true, false, location
);
4258 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4260 Convert_recover
convert_recover(can_recover_no
);
4261 new_func
->traverse(&convert_recover
);
4263 // Update the function pointers in any named results.
4264 new_func
->update_result_variables();
4265 orig_func
->update_result_variables();
4267 return TRAVERSE_CONTINUE
;
4270 // Return the expression to pass for the .can_recover parameter to the
4271 // new function. This indicates whether a call to recover may return
4272 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4275 Build_recover_thunks::can_recover_arg(Location location
)
4277 static Named_object
* builtin_return_address
;
4278 if (builtin_return_address
== NULL
)
4279 builtin_return_address
=
4280 Gogo::declare_builtin_rf_address("__builtin_return_address");
4282 static Named_object
* can_recover
;
4283 if (can_recover
== NULL
)
4285 const Location bloc
= Linemap::predeclared_location();
4286 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4287 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4288 param_types
->push_back(Typed_identifier("a", voidptr_type
, bloc
));
4289 Type
* boolean_type
= Type::lookup_bool_type();
4290 Typed_identifier_list
* results
= new Typed_identifier_list();
4291 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4292 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4295 Named_object::make_function_declaration("runtime_canrecover",
4296 NULL
, fntype
, bloc
);
4297 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4300 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4303 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4304 Expression_list
*args
= new Expression_list();
4305 args
->push_back(zexpr
);
4307 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4309 args
= new Expression_list();
4310 args
->push_back(call
);
4312 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4313 return Expression::make_call(fn
, args
, false, location
);
4316 // Build thunks for functions which call recover. We build a new
4317 // function with an extra parameter, which is whether a call to
4318 // recover can succeed. We then move the body of this function to
4319 // that one. We then turn this function into a thunk which calls the
4320 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4321 // The function will be marked as not splitting the stack. This will
4322 // cooperate with the implementation of defer to make recover do the
4326 Gogo::build_recover_thunks()
4328 Build_recover_thunks
build_recover_thunks(this);
4329 this->traverse(&build_recover_thunks
);
4332 // Return a declaration for __builtin_return_address or
4333 // __builtin_frame_address.
4336 Gogo::declare_builtin_rf_address(const char* name
)
4338 const Location bloc
= Linemap::predeclared_location();
4340 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4341 Type
* uint32_type
= Type::lookup_integer_type("uint32");
4342 param_types
->push_back(Typed_identifier("l", uint32_type
, bloc
));
4344 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4345 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4346 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4348 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4349 return_types
, bloc
);
4350 Named_object
* ret
= Named_object::make_function_declaration(name
, NULL
,
4352 ret
->func_declaration_value()->set_asm_name(name
);
4356 // Build a call to the runtime error function.
4359 Gogo::runtime_error(int code
, Location location
)
4361 Type
* int32_type
= Type::lookup_integer_type("int32");
4362 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4364 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4367 // Look for named types to see whether we need to create an interface
4370 class Build_method_tables
: public Traverse
4373 Build_method_tables(Gogo
* gogo
,
4374 const std::vector
<Interface_type
*>& interfaces
)
4375 : Traverse(traverse_types
),
4376 gogo_(gogo
), interfaces_(interfaces
)
4385 // A list of locally defined interfaces which have hidden methods.
4386 const std::vector
<Interface_type
*>& interfaces_
;
4389 // Build all required interface method tables for types. We need to
4390 // ensure that we have an interface method table for every interface
4391 // which has a hidden method, for every named type which implements
4392 // that interface. Normally we can just build interface method tables
4393 // as we need them. However, in some cases we can require an
4394 // interface method table for an interface defined in a different
4395 // package for a type defined in that package. If that interface and
4396 // type both use a hidden method, that is OK. However, we will not be
4397 // able to build that interface method table when we need it, because
4398 // the type's hidden method will be static. So we have to build it
4399 // here, and just refer it from other packages as needed.
4402 Gogo::build_interface_method_tables()
4407 std::vector
<Interface_type
*> hidden_interfaces
;
4408 hidden_interfaces
.reserve(this->interface_types_
.size());
4409 for (std::vector
<Interface_type
*>::const_iterator pi
=
4410 this->interface_types_
.begin();
4411 pi
!= this->interface_types_
.end();
4414 const Typed_identifier_list
* methods
= (*pi
)->methods();
4415 if (methods
== NULL
)
4417 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4418 pm
!= methods
->end();
4421 if (Gogo::is_hidden_name(pm
->name()))
4423 hidden_interfaces
.push_back(*pi
);
4429 if (!hidden_interfaces
.empty())
4431 // Now traverse the tree looking for all named types.
4432 Build_method_tables
bmt(this, hidden_interfaces
);
4433 this->traverse(&bmt
);
4436 // We no longer need the list of interfaces.
4438 this->interface_types_
.clear();
4441 // This is called for each type. For a named type, for each of the
4442 // interfaces with hidden methods that it implements, create the
4446 Build_method_tables::type(Type
* type
)
4448 Named_type
* nt
= type
->named_type();
4449 Struct_type
* st
= type
->struct_type();
4450 if (nt
!= NULL
|| st
!= NULL
)
4452 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4453 for (std::vector
<Interface_type
*>::const_iterator p
=
4454 this->interfaces_
.begin();
4455 p
!= this->interfaces_
.end();
4458 // We ask whether a pointer to the named type implements the
4459 // interface, because a pointer can implement more methods
4463 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4466 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4467 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4472 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4475 st
->interface_method_table(*p
, false)->get_backend(&context
);
4476 st
->interface_method_table(*p
, true)->get_backend(&context
);
4481 return TRAVERSE_CONTINUE
;
4484 // Return an expression which allocates memory to hold values of type TYPE.
4487 Gogo::allocate_memory(Type
* type
, Location location
)
4489 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4490 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
4493 // Traversal class used to check for return statements.
4495 class Check_return_statements_traverse
: public Traverse
4498 Check_return_statements_traverse()
4499 : Traverse(traverse_functions
)
4503 function(Named_object
*);
4506 // Check that a function has a return statement if it needs one.
4509 Check_return_statements_traverse::function(Named_object
* no
)
4511 Function
* func
= no
->func_value();
4512 const Function_type
* fntype
= func
->type();
4513 const Typed_identifier_list
* results
= fntype
->results();
4515 // We only need a return statement if there is a return value.
4516 if (results
== NULL
|| results
->empty())
4517 return TRAVERSE_CONTINUE
;
4519 if (func
->block()->may_fall_through())
4520 go_error_at(func
->block()->end_location(),
4521 "missing return at end of function");
4523 return TRAVERSE_CONTINUE
;
4526 // Check return statements.
4529 Gogo::check_return_statements()
4531 Check_return_statements_traverse traverse
;
4532 this->traverse(&traverse
);
4535 // Export identifiers as requested.
4540 // For now we always stream to a section. Later we may want to
4541 // support streaming to a separate file.
4542 Stream_to_section
stream(this->backend());
4544 // Write out either the prefix or pkgpath depending on how we were
4547 std::string pkgpath
;
4548 if (this->pkgpath_from_option_
)
4549 pkgpath
= this->pkgpath_
;
4550 else if (this->prefix_from_option_
)
4551 prefix
= this->prefix_
;
4552 else if (this->is_main_package())
4557 Export
exp(&stream
);
4558 exp
.register_builtin_types(this);
4559 exp
.export_globals(this->package_name(),
4564 (this->need_init_fn_
&& !this->is_main_package()
4565 ? this->get_init_fn_name()
4567 this->imported_init_fns_
,
4568 this->package_
->bindings());
4570 if (!this->c_header_
.empty() && !saw_errors())
4571 this->write_c_header();
4574 // Write the top level named struct types in C format to a C header
4575 // file. This is used when building the runtime package, to share
4576 // struct definitions between C and Go.
4579 Gogo::write_c_header()
4582 out
.open(this->c_header_
.c_str());
4585 go_error_at(Linemap::unknown_location(),
4586 "cannot open %s: %m", this->c_header_
.c_str());
4590 std::list
<Named_object
*> types
;
4591 Bindings
* top
= this->package_
->bindings();
4592 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
4593 p
!= top
->end_definitions();
4596 Named_object
* no
= *p
;
4598 // Skip names that start with underscore followed by something
4599 // other than an uppercase letter, as when compiling the runtime
4600 // package they are mostly types defined by mkrsysinfo.sh based
4601 // on the C system header files. We don't need to translate
4602 // types to C and back to Go. But do accept the special cases
4603 // _defer and _panic.
4604 std::string name
= Gogo::unpack_hidden_name(no
->name());
4606 && (name
[1] < 'A' || name
[1] > 'Z')
4607 && (name
!= "_defer" && name
!= "_panic"))
4610 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
4611 types
.push_back(no
);
4612 if (no
->is_const() && no
->const_value()->type()->integer_type() != NULL
)
4614 Numeric_constant nc
;
4616 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
4617 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
4619 out
<< "#define " << no
->message_name() << ' ' << val
4625 std::vector
<const Named_object
*> written
;
4627 while (!types
.empty())
4629 Named_object
* no
= types
.front();
4632 std::vector
<const Named_object
*> requires
;
4633 std::vector
<const Named_object
*> declare
;
4634 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
4639 for (std::vector
<const Named_object
*>::const_iterator pr
4641 pr
!= requires
.end() && ok
;
4644 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
4645 pt
!= types
.end() && ok
;
4655 // This should be impossible since the code parsed and
4660 types
.push_back(no
);
4664 for (std::vector
<const Named_object
*>::const_iterator pd
4666 pd
!= declare
.end();
4672 std::vector
<const Named_object
*> drequires
;
4673 std::vector
<const Named_object
*> ddeclare
;
4674 if (!(*pd
)->type_value()->struct_type()->
4675 can_write_to_c_header(&drequires
, &ddeclare
))
4679 for (std::vector
<const Named_object
*>::const_iterator pw
4681 pw
!= written
.end();
4693 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
4694 written
.push_back(*pd
);
4699 out
<< "struct " << no
->message_name() << " {" << std::endl
;
4700 no
->type_value()->struct_type()->write_to_c_header(out
);
4701 out
<< "};" << std::endl
;
4702 written
.push_back(no
);
4707 go_error_at(Linemap::unknown_location(),
4708 "error writing to %s: %m", this->c_header_
.c_str());
4711 // Find the blocks in order to convert named types defined in blocks.
4713 class Convert_named_types
: public Traverse
4716 Convert_named_types(Gogo
* gogo
)
4717 : Traverse(traverse_blocks
),
4723 block(Block
* block
);
4730 Convert_named_types::block(Block
* block
)
4732 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
4733 return TRAVERSE_CONTINUE
;
4736 // Convert all named types to the backend representation. Since named
4737 // types can refer to other types, this needs to be done in the right
4738 // sequence, which is handled by Named_type::convert. Here we arrange
4739 // to call that for each named type.
4742 Gogo::convert_named_types()
4744 this->convert_named_types_in_bindings(this->globals_
);
4745 for (Packages::iterator p
= this->packages_
.begin();
4746 p
!= this->packages_
.end();
4749 Package
* package
= p
->second
;
4750 this->convert_named_types_in_bindings(package
->bindings());
4753 Convert_named_types
cnt(this);
4754 this->traverse(&cnt
);
4756 // Make all the builtin named types used for type descriptors, and
4757 // then convert them. They will only be written out if they are
4759 Type::make_type_descriptor_type();
4760 Type::make_type_descriptor_ptr_type();
4761 Function_type::make_function_type_descriptor_type();
4762 Pointer_type::make_pointer_type_descriptor_type();
4763 Struct_type::make_struct_type_descriptor_type();
4764 Array_type::make_array_type_descriptor_type();
4765 Array_type::make_slice_type_descriptor_type();
4766 Map_type::make_map_type_descriptor_type();
4767 Channel_type::make_chan_type_descriptor_type();
4768 Interface_type::make_interface_type_descriptor_type();
4769 Expression::make_func_descriptor_type();
4770 Type::convert_builtin_named_types(this);
4772 Runtime::convert_types(this);
4774 this->named_types_are_converted_
= true;
4776 Type::finish_pointer_types(this);
4779 // Convert all names types in a set of bindings.
4782 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
4784 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
4785 p
!= bindings
->end_definitions();
4788 if ((*p
)->is_type())
4789 (*p
)->type_value()->convert(this);
4795 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
4797 : type_(type
), enclosing_(enclosing
), results_(NULL
),
4798 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
4799 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
4800 pragmas_(0), is_sink_(false), results_are_named_(false),
4801 is_unnamed_type_stub_method_(false), calls_recover_(false),
4802 is_recover_thunk_(false), has_recover_thunk_(false),
4803 calls_defer_retaddr_(false), is_type_specific_function_(false),
4804 in_unique_section_(false)
4808 // Create the named result variables.
4811 Function::create_result_variables(Gogo
* gogo
)
4813 const Typed_identifier_list
* results
= this->type_
->results();
4814 if (results
== NULL
|| results
->empty())
4817 if (!results
->front().name().empty())
4818 this->results_are_named_
= true;
4820 this->results_
= new Results();
4821 this->results_
->reserve(results
->size());
4823 Block
* block
= this->block_
;
4825 for (Typed_identifier_list::const_iterator p
= results
->begin();
4826 p
!= results
->end();
4829 std::string name
= p
->name();
4830 if (name
.empty() || Gogo::is_sink_name(name
))
4832 static int result_counter
;
4834 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
4836 name
= gogo
->pack_hidden_name(buf
, false);
4838 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
4840 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
4841 if (no
->is_result_variable())
4842 this->results_
->push_back(no
);
4845 static int dummy_result_count
;
4847 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
4848 ++dummy_result_count
;
4849 name
= gogo
->pack_hidden_name(buf
, false);
4850 no
= block
->bindings()->add_result_variable(name
, result
);
4851 go_assert(no
->is_result_variable());
4852 this->results_
->push_back(no
);
4857 // Update the named result variables when cloning a function which
4861 Function::update_result_variables()
4863 if (this->results_
== NULL
)
4866 for (Results::iterator p
= this->results_
->begin();
4867 p
!= this->results_
->end();
4869 (*p
)->result_var_value()->set_function(this);
4872 // Whether this method should not be included in the type descriptor.
4875 Function::nointerface() const
4877 go_assert(this->is_method());
4878 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
4881 // Record that this method should not be included in the type
4885 Function::set_nointerface()
4887 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
4890 // Return the closure variable, creating it if necessary.
4893 Function::closure_var()
4895 if (this->closure_var_
== NULL
)
4897 go_assert(this->descriptor_
== NULL
);
4898 // We don't know the type of the variable yet. We add fields as
4900 Location loc
= this->type_
->location();
4901 Struct_field_list
* sfl
= new Struct_field_list
;
4902 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
4903 struct_type
->set_is_struct_incomparable();
4904 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
4905 NULL
, false, false, false, loc
);
4907 var
->set_is_closure();
4908 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
4909 // Note that the new variable is not in any binding contour.
4911 return this->closure_var_
;
4914 // Set the type of the closure variable.
4917 Function::set_closure_type()
4919 if (this->closure_var_
== NULL
)
4921 Named_object
* closure
= this->closure_var_
;
4922 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
4924 // The first field of a closure is always a pointer to the function
4926 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4927 st
->push_field(Struct_field(Typed_identifier(".$f", voidptr_type
,
4930 unsigned int index
= 1;
4931 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
4932 p
!= this->closure_fields_
.end();
4935 Named_object
* no
= p
->first
;
4937 snprintf(buf
, sizeof buf
, "%u", index
);
4938 std::string n
= no
->name() + buf
;
4940 if (no
->is_variable())
4941 var_type
= no
->var_value()->type();
4943 var_type
= no
->result_var_value()->type();
4944 Type
* field_type
= Type::make_pointer_type(var_type
);
4945 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
4949 // Return whether this function is a method.
4952 Function::is_method() const
4954 return this->type_
->is_method();
4957 // Add a label definition.
4960 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
4963 Label
* lnull
= NULL
;
4964 std::pair
<Labels::iterator
, bool> ins
=
4965 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4967 if (label_name
== "_")
4969 label
= Label::create_dummy_label();
4971 ins
.first
->second
= label
;
4973 else if (ins
.second
)
4975 // This is a new label.
4976 label
= new Label(label_name
);
4977 ins
.first
->second
= label
;
4981 // The label was already in the hash table.
4982 label
= ins
.first
->second
;
4983 if (label
->is_defined())
4985 go_error_at(location
, "label %qs already defined",
4986 Gogo::message_name(label_name
).c_str());
4987 go_inform(label
->location(), "previous definition of %qs was here",
4988 Gogo::message_name(label_name
).c_str());
4989 return new Label(label_name
);
4993 label
->define(location
, gogo
->bindings_snapshot(location
));
4995 // Issue any errors appropriate for any previous goto's to this
4997 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
4998 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5001 (*p
)->check_goto_to(gogo
->current_block());
5002 label
->clear_refs();
5007 // Add a reference to a label.
5010 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5011 Location location
, bool issue_goto_errors
)
5013 Label
* lnull
= NULL
;
5014 std::pair
<Labels::iterator
, bool> ins
=
5015 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5019 // The label was already in the hash table.
5020 label
= ins
.first
->second
;
5024 go_assert(ins
.first
->second
== NULL
);
5025 label
= new Label(label_name
);
5026 ins
.first
->second
= label
;
5029 label
->set_is_used();
5031 if (issue_goto_errors
)
5033 Bindings_snapshot
* snapshot
= label
->snapshot();
5034 if (snapshot
!= NULL
)
5035 snapshot
->check_goto_from(gogo
->current_block(), location
);
5037 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5043 // Warn about labels that are defined but not used.
5046 Function::check_labels() const
5048 for (Labels::const_iterator p
= this->labels_
.begin();
5049 p
!= this->labels_
.end();
5052 Label
* label
= p
->second
;
5053 if (!label
->is_used())
5054 go_error_at(label
->location(), "label %qs defined and not used",
5055 Gogo::message_name(label
->name()).c_str());
5059 // Swap one function with another. This is used when building the
5060 // thunk we use to call a function which calls recover. It may not
5061 // work for any other case.
5064 Function::swap_for_recover(Function
*x
)
5066 go_assert(this->enclosing_
== x
->enclosing_
);
5067 std::swap(this->results_
, x
->results_
);
5068 std::swap(this->closure_var_
, x
->closure_var_
);
5069 std::swap(this->block_
, x
->block_
);
5070 go_assert(this->location_
== x
->location_
);
5071 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5072 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5075 // Traverse the tree.
5078 Function::traverse(Traverse
* traverse
)
5080 unsigned int traverse_mask
= traverse
->traverse_mask();
5083 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5086 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5087 return TRAVERSE_EXIT
;
5090 // FIXME: We should check traverse_functions here if nested
5091 // functions are stored in block bindings.
5092 if (this->block_
!= NULL
5094 & (Traverse::traverse_variables
5095 | Traverse::traverse_constants
5096 | Traverse::traverse_blocks
5097 | Traverse::traverse_statements
5098 | Traverse::traverse_expressions
5099 | Traverse::traverse_types
)) != 0)
5101 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5102 return TRAVERSE_EXIT
;
5105 return TRAVERSE_CONTINUE
;
5108 // Work out types for unspecified variables and constants.
5111 Function::determine_types()
5113 if (this->block_
!= NULL
)
5114 this->block_
->determine_types();
5117 // Return the function descriptor, the value you get when you refer to
5118 // the function in Go code without calling it.
5121 Function::descriptor(Gogo
*, Named_object
* no
)
5123 go_assert(!this->is_method());
5124 go_assert(this->closure_var_
== NULL
);
5125 if (this->descriptor_
== NULL
)
5126 this->descriptor_
= Expression::make_func_descriptor(no
);
5127 return this->descriptor_
;
5130 // Get a pointer to the variable representing the defer stack for this
5131 // function, making it if necessary. The value of the variable is set
5132 // by the runtime routines to true if the function is returning,
5133 // rather than panicing through. A pointer to this variable is used
5134 // as a marker for the functions on the defer stack associated with
5135 // this function. A function-specific variable permits inlining a
5136 // function which uses defer.
5139 Function::defer_stack(Location location
)
5141 if (this->defer_stack_
== NULL
)
5143 Type
* t
= Type::lookup_bool_type();
5144 Expression
* n
= Expression::make_boolean(false, location
);
5145 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5146 this->defer_stack_
->set_is_address_taken();
5148 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5150 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5153 // Export the function.
5156 Function::export_func(Export
* exp
, const std::string
& name
) const
5158 Function::export_func_with_type(exp
, name
, this->type_
);
5161 // Export a function with a type.
5164 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
5165 const Function_type
* fntype
)
5167 exp
->write_c_string("func ");
5169 if (fntype
->is_method())
5171 exp
->write_c_string("(");
5172 const Typed_identifier
* receiver
= fntype
->receiver();
5173 exp
->write_name(receiver
->name());
5174 exp
->write_escape(receiver
->note());
5175 exp
->write_c_string(" ");
5176 exp
->write_type(receiver
->type());
5177 exp
->write_c_string(") ");
5180 exp
->write_string(name
);
5182 exp
->write_c_string(" (");
5183 const Typed_identifier_list
* parameters
= fntype
->parameters();
5184 if (parameters
!= NULL
)
5187 bool is_varargs
= fntype
->is_varargs();
5189 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5190 p
!= parameters
->end();
5196 exp
->write_c_string(", ");
5197 exp
->write_name(p
->name());
5198 exp
->write_escape(p
->note());
5199 exp
->write_c_string(" ");
5200 if (!is_varargs
|| p
+ 1 != parameters
->end())
5201 exp
->write_type(p
->type());
5204 exp
->write_c_string("...");
5205 exp
->write_type(p
->type()->array_type()->element_type());
5209 exp
->write_c_string(")");
5211 const Typed_identifier_list
* results
= fntype
->results();
5212 if (results
!= NULL
)
5214 if (results
->size() == 1 && results
->begin()->name().empty())
5216 exp
->write_c_string(" ");
5217 exp
->write_type(results
->begin()->type());
5221 exp
->write_c_string(" (");
5223 for (Typed_identifier_list::const_iterator p
= results
->begin();
5224 p
!= results
->end();
5230 exp
->write_c_string(", ");
5231 exp
->write_name(p
->name());
5232 exp
->write_escape(p
->note());
5233 exp
->write_c_string(" ");
5234 exp
->write_type(p
->type());
5236 exp
->write_c_string(")");
5239 exp
->write_c_string(";\n");
5242 // Import a function.
5245 Function::import_func(Import
* imp
, std::string
* pname
,
5246 Typed_identifier
** preceiver
,
5247 Typed_identifier_list
** pparameters
,
5248 Typed_identifier_list
** presults
,
5251 imp
->require_c_string("func ");
5254 if (imp
->peek_char() == '(')
5256 imp
->require_c_string("(");
5257 std::string name
= imp
->read_name();
5258 std::string escape_note
= imp
->read_escape();
5259 imp
->require_c_string(" ");
5260 Type
* rtype
= imp
->read_type();
5261 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5262 (*preceiver
)->set_note(escape_note
);
5263 imp
->require_c_string(") ");
5266 *pname
= imp
->read_identifier();
5268 Typed_identifier_list
* parameters
;
5269 *is_varargs
= false;
5270 imp
->require_c_string(" (");
5271 if (imp
->peek_char() == ')')
5275 parameters
= new Typed_identifier_list();
5278 std::string name
= imp
->read_name();
5279 std::string escape_note
= imp
->read_escape();
5280 imp
->require_c_string(" ");
5282 if (imp
->match_c_string("..."))
5288 Type
* ptype
= imp
->read_type();
5290 ptype
= Type::make_array_type(ptype
, NULL
);
5291 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
5292 t
.set_note(escape_note
);
5293 parameters
->push_back(t
);
5294 if (imp
->peek_char() != ',')
5296 go_assert(!*is_varargs
);
5297 imp
->require_c_string(", ");
5300 imp
->require_c_string(")");
5301 *pparameters
= parameters
;
5303 Typed_identifier_list
* results
;
5304 if (imp
->peek_char() != ' ')
5308 results
= new Typed_identifier_list();
5309 imp
->require_c_string(" ");
5310 if (imp
->peek_char() != '(')
5312 Type
* rtype
= imp
->read_type();
5313 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5317 imp
->require_c_string("(");
5320 std::string name
= imp
->read_name();
5321 std::string note
= imp
->read_escape();
5322 imp
->require_c_string(" ");
5323 Type
* rtype
= imp
->read_type();
5324 Typed_identifier t
= Typed_identifier(name
, rtype
,
5327 results
->push_back(t
);
5328 if (imp
->peek_char() != ',')
5330 imp
->require_c_string(", ");
5332 imp
->require_c_string(")");
5335 imp
->require_c_string(";\n");
5336 *presults
= results
;
5339 // Get the backend representation.
5342 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5344 if (this->fndecl_
== NULL
)
5346 bool is_visible
= false;
5347 bool is_init_fn
= false;
5349 if (no
->package() != NULL
)
5351 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5353 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5354 && !this->type_
->is_method())
5356 else if (no
->name() == gogo
->get_init_fn_name())
5361 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5362 && gogo
->is_main_package())
5364 // Methods have to be public even if they are hidden because
5365 // they can be pulled into type descriptors when using
5366 // anonymous fields.
5367 else if (!Gogo::is_hidden_name(no
->name())
5368 || this->type_
->is_method())
5370 if (!this->is_unnamed_type_stub_method_
)
5372 if (this->type_
->is_method())
5373 rtype
= this->type_
->receiver()->type();
5376 std::string asm_name
;
5377 if (!this->asm_name_
.empty())
5379 asm_name
= this->asm_name_
;
5381 // If an assembler name is explicitly specified, there must
5382 // be some reason to refer to the symbol from a different
5386 else if (is_init_fn
)
5388 // These names appear in the export data and are used
5389 // directly in the assembler code. If we change this here
5390 // we need to change Gogo::init_imports.
5391 asm_name
= no
->name();
5394 asm_name
= gogo
->function_asm_name(no
->name(), NULL
, rtype
);
5396 // If a function calls the predeclared recover function, we
5397 // can't inline it, because recover behaves differently in a
5398 // function passed directly to defer. If this is a recover
5399 // thunk that we built to test whether a function can be
5400 // recovered, we can't inline it, because that will mess up
5401 // our return address comparison.
5402 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5404 // If a function calls __go_set_defer_retaddr, then mark it as
5405 // uninlinable. This prevents the GCC backend from splitting
5406 // the function; splitting the function is a bad idea because we
5407 // want the return address label to be in the same function as
5409 if (this->calls_defer_retaddr_
)
5410 is_inlinable
= false;
5412 // Check the //go:noinline compiler directive.
5413 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
5414 is_inlinable
= false;
5416 // If this is a thunk created to call a function which calls
5417 // the predeclared recover function, we need to disable
5418 // stack splitting for the thunk.
5419 bool disable_split_stack
= this->is_recover_thunk_
;
5421 // Check the //go:nosplit compiler directive.
5422 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
5423 disable_split_stack
= true;
5425 // This should go into a unique section if that has been
5426 // requested elsewhere, or if this is a nointerface function.
5427 // We want to put a nointerface function into a unique section
5428 // because there is a good chance that the linker garbage
5429 // collection can discard it.
5430 bool in_unique_section
= (this->in_unique_section_
5431 || (this->is_method() && this->nointerface()));
5433 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5435 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5436 is_visible
, false, is_inlinable
,
5437 disable_split_stack
, in_unique_section
,
5440 return this->fndecl_
;
5443 // Get the backend representation.
5446 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5448 if (this->fndecl_
== NULL
)
5450 // Let Go code use an asm declaration to pick up a builtin
5452 if (!this->asm_name_
.empty())
5454 Bfunction
* builtin_decl
=
5455 gogo
->backend()->lookup_builtin(this->asm_name_
);
5456 if (builtin_decl
!= NULL
)
5458 this->fndecl_
= builtin_decl
;
5459 return this->fndecl_
;
5463 std::string asm_name
;
5464 if (this->asm_name_
.empty())
5467 if (this->fntype_
->is_method())
5468 rtype
= this->fntype_
->receiver()->type();
5469 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
5471 else if (go_id_needs_encoding(no
->get_id(gogo
)))
5472 asm_name
= go_encode_id(no
->get_id(gogo
));
5474 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5476 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5477 true, true, true, false, false,
5481 return this->fndecl_
;
5484 // Build the descriptor for a function declaration. This won't
5485 // necessarily happen if the package has just a declaration for the
5486 // function and no other reference to it, but we may still need the
5487 // descriptor for references from other packages.
5489 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5491 if (this->descriptor_
!= NULL
)
5493 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5494 this->descriptor_
->get_backend(&context
);
5498 // Check that the types used in this declaration's signature are defined.
5499 // Reports errors for any undefined type.
5502 Function_declaration::check_types() const
5504 // Calling Type::base will give errors for any undefined types.
5505 Function_type
* fntype
= this->type();
5506 if (fntype
->receiver() != NULL
)
5507 fntype
->receiver()->type()->base();
5508 if (fntype
->parameters() != NULL
)
5510 const Typed_identifier_list
* params
= fntype
->parameters();
5511 for (Typed_identifier_list::const_iterator p
= params
->begin();
5518 // Return the function's decl after it has been built.
5521 Function::get_decl() const
5523 go_assert(this->fndecl_
!= NULL
);
5524 return this->fndecl_
;
5527 // Build the backend representation for the function code.
5530 Function::build(Gogo
* gogo
, Named_object
* named_function
)
5532 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5534 // A list of parameter variables for this function.
5535 std::vector
<Bvariable
*> param_vars
;
5537 // Variables that need to be declared for this function and their
5539 std::vector
<Bvariable
*> vars
;
5540 std::vector
<Bexpression
*> var_inits
;
5541 for (Bindings::const_definitions_iterator p
=
5542 this->block_
->bindings()->begin_definitions();
5543 p
!= this->block_
->bindings()->end_definitions();
5546 Location loc
= (*p
)->location();
5547 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
5549 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5550 Bvariable
* parm_bvar
= bvar
;
5552 // We always pass the receiver to a method as a pointer. If
5553 // the receiver is declared as a non-pointer type, then we
5554 // copy the value into a local variable.
5555 if ((*p
)->var_value()->is_receiver()
5556 && (*p
)->var_value()->type()->points_to() == NULL
)
5558 std::string name
= (*p
)->name() + ".pointer";
5559 Type
* var_type
= (*p
)->var_value()->type();
5560 Variable
* parm_var
=
5561 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
5563 Named_object
* parm_no
=
5564 Named_object::make_variable(name
, NULL
, parm_var
);
5565 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5567 vars
.push_back(bvar
);
5568 Expression
* parm_ref
=
5569 Expression::make_var_reference(parm_no
, loc
);
5570 parm_ref
= Expression::make_unary(OPERATOR_MULT
, parm_ref
, loc
);
5571 if ((*p
)->var_value()->is_in_heap())
5572 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
5573 var_inits
.push_back(parm_ref
->get_backend(&context
));
5575 else if ((*p
)->var_value()->is_in_heap())
5577 // If we take the address of a parameter, then we need
5578 // to copy it into the heap.
5579 std::string parm_name
= (*p
)->name() + ".param";
5580 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
5581 false, true, false, loc
);
5582 Named_object
* parm_no
=
5583 Named_object::make_variable(parm_name
, NULL
, parm_var
);
5584 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5586 vars
.push_back(bvar
);
5587 Expression
* var_ref
=
5588 Expression::make_var_reference(parm_no
, loc
);
5589 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
5590 var_inits
.push_back(var_ref
->get_backend(&context
));
5592 param_vars
.push_back(parm_bvar
);
5594 else if ((*p
)->is_result_variable())
5596 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5598 Type
* type
= (*p
)->result_var_value()->type();
5600 if (!(*p
)->result_var_value()->is_in_heap())
5602 Btype
* btype
= type
->get_backend(gogo
);
5603 init
= gogo
->backend()->zero_expression(btype
);
5606 init
= Expression::make_allocation(type
,
5607 loc
)->get_backend(&context
);
5609 vars
.push_back(bvar
);
5610 var_inits
.push_back(init
);
5613 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
5615 go_assert(saw_errors());
5619 // If we need a closure variable, make sure to create it.
5620 // It gets installed in the function as a side effect of creation.
5621 if (this->closure_var_
!= NULL
)
5623 go_assert(this->closure_var_
->var_value()->is_closure());
5624 this->closure_var_
->get_backend_variable(gogo
, named_function
);
5627 if (this->block_
!= NULL
)
5629 // Declare variables if necessary.
5630 Bblock
* var_decls
= NULL
;
5632 Bstatement
* defer_init
= NULL
;
5633 if (!vars
.empty() || this->defer_stack_
!= NULL
)
5636 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
5637 this->block_
->start_location(),
5638 this->block_
->end_location());
5640 if (this->defer_stack_
!= NULL
)
5642 Translate_context
dcontext(gogo
, named_function
, this->block_
,
5644 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
5648 // Build the backend representation for all the statements in the
5650 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5651 Bblock
* code_block
= this->block_
->get_backend(&context
);
5653 // Initialize variables if necessary.
5654 std::vector
<Bstatement
*> init
;
5655 go_assert(vars
.size() == var_inits
.size());
5656 for (size_t i
= 0; i
< vars
.size(); ++i
)
5658 Bstatement
* init_stmt
=
5659 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
5661 init
.push_back(init_stmt
);
5663 if (defer_init
!= NULL
)
5664 init
.push_back(defer_init
);
5665 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
5667 // Initialize all variables before executing this code block.
5668 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
5669 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
5671 // If we have a defer stack, initialize it at the start of a
5673 Bstatement
* except
= NULL
;
5674 Bstatement
* fini
= NULL
;
5675 if (defer_init
!= NULL
)
5677 // Clean up the defer stack when we leave the function.
5678 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
5680 // Wrap the code for this function in an exception handler to handle
5683 gogo
->backend()->exception_handler_statement(code_stmt
,
5688 // Stick the code into the block we built for the receiver, if
5690 if (var_decls
!= NULL
)
5692 std::vector
<Bstatement
*> code_stmt_list(1, code_stmt
);
5693 gogo
->backend()->block_add_statements(var_decls
, code_stmt_list
);
5694 code_stmt
= gogo
->backend()->block_statement(var_decls
);
5697 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
5699 go_assert(saw_errors());
5704 // If we created a descriptor for the function, make sure we emit it.
5705 if (this->descriptor_
!= NULL
)
5707 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5708 this->descriptor_
->get_backend(&context
);
5712 // Build the wrappers around function code needed if the function has
5713 // any defer statements. This sets *EXCEPT to an exception handler
5714 // and *FINI to a finally handler.
5717 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
5718 Bstatement
** except
, Bstatement
** fini
)
5720 Location end_loc
= this->block_
->end_location();
5722 // Add an exception handler. This is used if a panic occurs. Its
5723 // purpose is to stop the stack unwinding if a deferred function
5724 // calls recover. There are more details in
5725 // libgo/runtime/go-unwind.c.
5727 std::vector
<Bstatement
*> stmts
;
5728 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
5729 this->defer_stack(end_loc
));
5730 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5731 Bexpression
* defer
= call
->get_backend(&context
);
5732 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
5734 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5735 if (ret_bstmt
!= NULL
)
5736 stmts
.push_back(ret_bstmt
);
5738 go_assert(*except
== NULL
);
5739 *except
= gogo
->backend()->statement_list(stmts
);
5741 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
5742 this->defer_stack(end_loc
));
5743 defer
= call
->get_backend(&context
);
5745 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
5746 this->defer_stack(end_loc
));
5747 Bexpression
* undefer
= call
->get_backend(&context
);
5748 Bstatement
* function_defer
=
5749 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
5751 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
5752 if (this->type_
->results() != NULL
5753 && !this->type_
->results()->empty()
5754 && !this->type_
->results()->front().name().empty())
5756 // If the result variables are named, and we are returning from
5757 // this function rather than panicing through it, we need to
5758 // return them again, because they might have been changed by a
5759 // defer function. The runtime routines set the defer_stack
5760 // variable to true if we are returning from this function.
5762 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5763 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
5765 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
5767 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
5768 Bexpression
* bref
= ref
->get_backend(&context
);
5769 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
5770 NULL
, bref
, ret
, NULL
,
5772 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
5775 go_assert(*fini
== NULL
);
5776 *fini
= gogo
->backend()->statement_list(stmts
);
5779 // Return the statement that assigns values to this function's result struct.
5782 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
5783 Location location
) const
5785 const Typed_identifier_list
* results
= this->type_
->results();
5786 if (results
== NULL
|| results
->empty())
5789 go_assert(this->results_
!= NULL
);
5790 if (this->results_
->size() != results
->size())
5792 go_assert(saw_errors());
5793 return gogo
->backend()->error_statement();
5796 std::vector
<Bexpression
*> vals(results
->size());
5797 for (size_t i
= 0; i
< vals
.size(); ++i
)
5799 Named_object
* no
= (*this->results_
)[i
];
5800 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
5801 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, VE_rvalue
,
5803 if (no
->result_var_value()->is_in_heap())
5805 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
5806 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
5810 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
5815 Block::Block(Block
* enclosing
, Location location
)
5816 : enclosing_(enclosing
), statements_(),
5817 bindings_(new Bindings(enclosing
== NULL
5819 : enclosing
->bindings())),
5820 start_location_(location
),
5821 end_location_(Linemap::unknown_location())
5825 // Add a statement to a block.
5828 Block::add_statement(Statement
* statement
)
5830 this->statements_
.push_back(statement
);
5833 // Add a statement to the front of a block. This is slow but is only
5834 // used for reference counts of parameters.
5837 Block::add_statement_at_front(Statement
* statement
)
5839 this->statements_
.insert(this->statements_
.begin(), statement
);
5842 // Replace a statement in a block.
5845 Block::replace_statement(size_t index
, Statement
* s
)
5847 go_assert(index
< this->statements_
.size());
5848 this->statements_
[index
] = s
;
5851 // Add a statement before another statement.
5854 Block::insert_statement_before(size_t index
, Statement
* s
)
5856 go_assert(index
< this->statements_
.size());
5857 this->statements_
.insert(this->statements_
.begin() + index
, s
);
5860 // Add a statement after another statement.
5863 Block::insert_statement_after(size_t index
, Statement
* s
)
5865 go_assert(index
< this->statements_
.size());
5866 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
5869 // Traverse the tree.
5872 Block::traverse(Traverse
* traverse
)
5874 unsigned int traverse_mask
= traverse
->traverse_mask();
5876 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
5878 int t
= traverse
->block(this);
5879 if (t
== TRAVERSE_EXIT
)
5880 return TRAVERSE_EXIT
;
5881 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
5882 return TRAVERSE_CONTINUE
;
5886 & (Traverse::traverse_variables
5887 | Traverse::traverse_constants
5888 | Traverse::traverse_expressions
5889 | Traverse::traverse_types
)) != 0)
5891 const unsigned int e_or_t
= (Traverse::traverse_expressions
5892 | Traverse::traverse_types
);
5893 const unsigned int e_or_t_or_s
= (e_or_t
5894 | Traverse::traverse_statements
);
5895 for (Bindings::const_definitions_iterator pb
=
5896 this->bindings_
->begin_definitions();
5897 pb
!= this->bindings_
->end_definitions();
5900 int t
= TRAVERSE_CONTINUE
;
5901 switch ((*pb
)->classification())
5903 case Named_object::NAMED_OBJECT_CONST
:
5904 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
5905 t
= traverse
->constant(*pb
, false);
5906 if (t
== TRAVERSE_CONTINUE
5907 && (traverse_mask
& e_or_t
) != 0)
5909 Type
* tc
= (*pb
)->const_value()->type();
5911 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
5912 return TRAVERSE_EXIT
;
5913 t
= (*pb
)->const_value()->traverse_expression(traverse
);
5917 case Named_object::NAMED_OBJECT_VAR
:
5918 case Named_object::NAMED_OBJECT_RESULT_VAR
:
5919 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
5920 t
= traverse
->variable(*pb
);
5921 if (t
== TRAVERSE_CONTINUE
5922 && (traverse_mask
& e_or_t
) != 0)
5924 if ((*pb
)->is_result_variable()
5925 || (*pb
)->var_value()->has_type())
5927 Type
* tv
= ((*pb
)->is_variable()
5928 ? (*pb
)->var_value()->type()
5929 : (*pb
)->result_var_value()->type());
5931 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
5932 return TRAVERSE_EXIT
;
5935 if (t
== TRAVERSE_CONTINUE
5936 && (traverse_mask
& e_or_t_or_s
) != 0
5937 && (*pb
)->is_variable())
5938 t
= (*pb
)->var_value()->traverse_expression(traverse
,
5942 case Named_object::NAMED_OBJECT_FUNC
:
5943 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
5946 case Named_object::NAMED_OBJECT_TYPE
:
5947 if ((traverse_mask
& e_or_t
) != 0)
5948 t
= Type::traverse((*pb
)->type_value(), traverse
);
5951 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
5952 case Named_object::NAMED_OBJECT_UNKNOWN
:
5953 case Named_object::NAMED_OBJECT_ERRONEOUS
:
5956 case Named_object::NAMED_OBJECT_PACKAGE
:
5957 case Named_object::NAMED_OBJECT_SINK
:
5964 if (t
== TRAVERSE_EXIT
)
5965 return TRAVERSE_EXIT
;
5969 // No point in checking traverse_mask here--if we got here we always
5970 // want to walk the statements. The traversal can insert new
5971 // statements before or after the current statement. Inserting
5972 // statements before the current statement requires updating I via
5973 // the pointer; those statements will not be traversed. Any new
5974 // statements inserted after the current statement will be traversed
5976 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
5978 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
5979 return TRAVERSE_EXIT
;
5982 return TRAVERSE_CONTINUE
;
5985 // Work out types for unspecified variables and constants.
5988 Block::determine_types()
5990 for (Bindings::const_definitions_iterator pb
=
5991 this->bindings_
->begin_definitions();
5992 pb
!= this->bindings_
->end_definitions();
5995 if ((*pb
)->is_variable())
5996 (*pb
)->var_value()->determine_type();
5997 else if ((*pb
)->is_const())
5998 (*pb
)->const_value()->determine_type();
6001 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6002 ps
!= this->statements_
.end();
6004 (*ps
)->determine_types();
6007 // Return true if the statements in this block may fall through.
6010 Block::may_fall_through() const
6012 if (this->statements_
.empty())
6014 return this->statements_
.back()->may_fall_through();
6017 // Convert a block to the backend representation.
6020 Block::get_backend(Translate_context
* context
)
6022 Gogo
* gogo
= context
->gogo();
6023 Named_object
* function
= context
->function();
6024 std::vector
<Bvariable
*> vars
;
6025 vars
.reserve(this->bindings_
->size_definitions());
6026 for (Bindings::const_definitions_iterator pv
=
6027 this->bindings_
->begin_definitions();
6028 pv
!= this->bindings_
->end_definitions();
6031 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
6032 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
6035 go_assert(function
!= NULL
);
6036 Bfunction
* bfunction
=
6037 function
->func_value()->get_or_make_decl(gogo
, function
);
6038 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
6039 vars
, this->start_location_
,
6040 this->end_location_
);
6042 Translate_context
subcontext(gogo
, function
, this, ret
);
6043 std::vector
<Bstatement
*> bstatements
;
6044 bstatements
.reserve(this->statements_
.size());
6045 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
6046 p
!= this->statements_
.end();
6048 bstatements
.push_back((*p
)->get_backend(&subcontext
));
6050 context
->backend()->block_add_statements(ret
, bstatements
);
6055 // Class Bindings_snapshot.
6057 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
6058 : block_(b
), counts_(), location_(location
)
6062 this->counts_
.push_back(b
->bindings()->size_definitions());
6067 // Report errors appropriate for a goto from B to this.
6070 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
6073 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
6075 this->check_goto_defs(loc
, this->block_
,
6076 this->block_
->bindings()->size_definitions(),
6080 // Report errors appropriate for a goto from this to B.
6083 Bindings_snapshot::check_goto_to(const Block
* b
)
6086 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
6088 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
6089 b
->bindings()->size_definitions());
6092 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6093 // Return true if all is well, false if we reported an error. If this
6094 // returns true, it sets *PINDEX to the number of blocks BTO is above
6098 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
6099 const Block
* bto
, size_t* pindex
)
6101 // It is an error if BTO is not either BFROM or above BFROM.
6103 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
6107 go_error_at(loc
, "goto jumps into block");
6108 go_inform(bto
->start_location(), "goto target block starts here");
6116 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6117 // CFROM is the number of names defined at the point of the goto and
6118 // CTO is the number of names defined at the point of the label.
6121 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
6122 size_t cfrom
, size_t cto
)
6126 Bindings::const_definitions_iterator p
=
6127 block
->bindings()->begin_definitions();
6128 for (size_t i
= 0; i
< cfrom
; ++i
)
6130 go_assert(p
!= block
->bindings()->end_definitions());
6133 go_assert(p
!= block
->bindings()->end_definitions());
6135 std::string n
= (*p
)->message_name();
6136 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
6137 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
6141 // Class Function_declaration.
6143 // Return the function descriptor.
6146 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
6148 go_assert(!this->fntype_
->is_method());
6149 if (this->descriptor_
== NULL
)
6150 this->descriptor_
= Expression::make_func_descriptor(no
);
6151 return this->descriptor_
;
6156 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
6157 bool is_parameter
, bool is_receiver
,
6159 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
6160 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
6161 is_closure_(false), is_receiver_(is_receiver
),
6162 is_varargs_parameter_(false), is_used_(false),
6163 is_address_taken_(false), is_non_escaping_address_taken_(false),
6164 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6165 type_from_init_tuple_(false), type_from_range_index_(false),
6166 type_from_range_value_(false), type_from_chan_element_(false),
6167 is_type_switch_var_(false), determined_type_(false),
6168 in_unique_section_(false), escapes_(true)
6170 go_assert(type
!= NULL
|| init
!= NULL
);
6171 go_assert(!is_parameter
|| init
== NULL
);
6174 // Traverse the initializer expression.
6177 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
6179 if (this->preinit_
!= NULL
)
6181 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
6182 return TRAVERSE_EXIT
;
6184 if (this->init_
!= NULL
6186 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
6189 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
6190 return TRAVERSE_EXIT
;
6192 return TRAVERSE_CONTINUE
;
6195 // Lower the initialization expression after parsing is complete.
6198 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
6199 Statement_inserter
* inserter
)
6201 Named_object
* dep
= gogo
->var_depends_on(this);
6202 if (dep
!= NULL
&& dep
->is_variable())
6203 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
6205 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
6209 // We will give an error elsewhere, this is just to prevent
6210 // an infinite loop.
6215 Statement_inserter global_inserter
;
6216 if (this->is_global_
)
6218 global_inserter
= Statement_inserter(gogo
, this);
6219 inserter
= &global_inserter
;
6222 gogo
->lower_expression(function
, inserter
, &this->init_
);
6224 this->seen_
= false;
6226 this->init_is_lowered_
= true;
6230 // Flatten the initialization expression after ordering evaluations.
6233 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
6234 Statement_inserter
* inserter
)
6236 Named_object
* dep
= gogo
->var_depends_on(this);
6237 if (dep
!= NULL
&& dep
->is_variable())
6238 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
6240 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
6244 // We will give an error elsewhere, this is just to prevent
6245 // an infinite loop.
6250 Statement_inserter global_inserter
;
6251 if (this->is_global_
)
6253 global_inserter
= Statement_inserter(gogo
, this);
6254 inserter
= &global_inserter
;
6257 gogo
->flatten_expression(function
, inserter
, &this->init_
);
6259 // If an interface conversion is needed, we need a temporary
6261 if (this->type_
!= NULL
6262 && !Type::are_identical(this->type_
, this->init_
->type(), false,
6264 && this->init_
->type()->interface_type() != NULL
6265 && !this->init_
->is_variable())
6267 Temporary_statement
* temp
=
6268 Statement::make_temporary(NULL
, this->init_
, this->location_
);
6269 inserter
->insert(temp
);
6270 this->init_
= Expression::make_temporary_reference(temp
,
6274 this->seen_
= false;
6275 this->init_is_flattened_
= true;
6279 // Get the preinit block.
6282 Variable::preinit_block(Gogo
* gogo
)
6284 go_assert(this->is_global_
);
6285 if (this->preinit_
== NULL
)
6286 this->preinit_
= new Block(NULL
, this->location());
6288 // If a global variable has a preinitialization statement, then we
6289 // need to have an initialization function.
6290 gogo
->set_need_init_fn();
6292 return this->preinit_
;
6295 // Add a statement to be run before the initialization expression.
6298 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
6300 Block
* b
= this->preinit_block(gogo
);
6301 b
->add_statement(s
);
6302 b
->set_end_location(s
->location());
6305 // Whether this variable has a type.
6308 Variable::has_type() const
6310 if (this->type_
== NULL
)
6313 // A variable created in a type switch case nil does not actually
6314 // have a type yet. It will be changed to use the initializer's
6315 // type in determine_type.
6316 if (this->is_type_switch_var_
6317 && this->type_
->is_nil_constant_as_type())
6323 // In an assignment which sets a variable to a tuple of EXPR, return
6324 // the type of the first element of the tuple.
6327 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
6329 if (expr
->map_index_expression() != NULL
)
6331 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
6333 return Type::make_error_type();
6334 return mt
->val_type();
6336 else if (expr
->receive_expression() != NULL
)
6338 Expression
* channel
= expr
->receive_expression()->channel();
6339 Type
* channel_type
= channel
->type();
6340 if (channel_type
->channel_type() == NULL
)
6341 return Type::make_error_type();
6342 return channel_type
->channel_type()->element_type();
6347 go_error_at(this->location(), "invalid tuple definition");
6348 return Type::make_error_type();
6352 // Given EXPR used in a range clause, return either the index type or
6353 // the value type of the range, depending upon GET_INDEX_TYPE.
6356 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
6357 bool report_error
) const
6359 Type
* t
= expr
->type();
6360 if (t
->array_type() != NULL
6361 || (t
->points_to() != NULL
6362 && t
->points_to()->array_type() != NULL
6363 && !t
->points_to()->is_slice_type()))
6366 return Type::lookup_integer_type("int");
6368 return t
->deref()->array_type()->element_type();
6370 else if (t
->is_string_type())
6373 return Type::lookup_integer_type("int");
6375 return Type::lookup_integer_type("int32");
6377 else if (t
->map_type() != NULL
)
6380 return t
->map_type()->key_type();
6382 return t
->map_type()->val_type();
6384 else if (t
->channel_type() != NULL
)
6387 return t
->channel_type()->element_type();
6391 go_error_at(this->location(),
6392 ("invalid definition of value variable "
6393 "for channel range"));
6394 return Type::make_error_type();
6400 go_error_at(this->location(), "invalid type for range clause");
6401 return Type::make_error_type();
6405 // EXPR should be a channel. Return the channel's element type.
6408 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
6410 Type
* t
= expr
->type();
6411 if (t
->channel_type() != NULL
)
6412 return t
->channel_type()->element_type();
6416 go_error_at(this->location(), "expected channel");
6417 return Type::make_error_type();
6421 // Return the type of the Variable. This may be called before
6422 // Variable::determine_type is called, which means that we may need to
6423 // get the type from the initializer. FIXME: If we combine lowering
6424 // with type determination, then this should be unnecessary.
6429 // A variable in a type switch with a nil case will have the wrong
6430 // type here. This gets fixed up in determine_type, below.
6431 Type
* type
= this->type_
;
6432 Expression
* init
= this->init_
;
6433 if (this->is_type_switch_var_
6435 && this->type_
->is_nil_constant_as_type())
6437 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6438 go_assert(tge
!= NULL
);
6445 if (this->type_
== NULL
|| !this->type_
->is_error_type())
6447 go_error_at(this->location_
, "variable initializer refers to itself");
6448 this->type_
= Type::make_error_type();
6457 else if (this->type_from_init_tuple_
)
6458 type
= this->type_from_tuple(init
, false);
6459 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6460 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
6461 else if (this->type_from_chan_element_
)
6462 type
= this->type_from_chan_element(init
, false);
6465 go_assert(init
!= NULL
);
6466 type
= init
->type();
6467 go_assert(type
!= NULL
);
6469 // Variables should not have abstract types.
6470 if (type
->is_abstract())
6471 type
= type
->make_non_abstract_type();
6473 if (type
->is_void_type())
6474 type
= Type::make_error_type();
6477 this->seen_
= false;
6482 // Fetch the type from a const pointer, in which case it should have
6483 // been set already.
6486 Variable::type() const
6488 go_assert(this->type_
!= NULL
);
6492 // Set the type if necessary.
6495 Variable::determine_type()
6497 if (this->determined_type_
)
6499 this->determined_type_
= true;
6501 if (this->preinit_
!= NULL
)
6502 this->preinit_
->determine_types();
6504 // A variable in a type switch with a nil case will have the wrong
6505 // type here. It will have an initializer which is a type guard.
6506 // We want to initialize it to the value without the type guard, and
6507 // use the type of that value as well.
6508 if (this->is_type_switch_var_
6509 && this->type_
!= NULL
6510 && this->type_
->is_nil_constant_as_type())
6512 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6513 go_assert(tge
!= NULL
);
6515 this->init_
= tge
->expr();
6518 if (this->init_
== NULL
)
6519 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
6520 else if (this->type_from_init_tuple_
)
6522 Expression
*init
= this->init_
;
6523 init
->determine_type_no_context();
6524 this->type_
= this->type_from_tuple(init
, true);
6527 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6529 Expression
* init
= this->init_
;
6530 init
->determine_type_no_context();
6531 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
6535 else if (this->type_from_chan_element_
)
6537 Expression
* init
= this->init_
;
6538 init
->determine_type_no_context();
6539 this->type_
= this->type_from_chan_element(init
, true);
6544 Type_context
context(this->type_
, false);
6545 this->init_
->determine_type(&context
);
6546 if (this->type_
== NULL
)
6548 Type
* type
= this->init_
->type();
6549 go_assert(type
!= NULL
);
6550 if (type
->is_abstract())
6551 type
= type
->make_non_abstract_type();
6553 if (type
->is_void_type())
6555 go_error_at(this->location_
, "variable has no type");
6556 type
= Type::make_error_type();
6558 else if (type
->is_nil_type())
6560 go_error_at(this->location_
, "variable defined to nil type");
6561 type
= Type::make_error_type();
6563 else if (type
->is_call_multiple_result_type())
6565 go_error_at(this->location_
,
6566 "single variable set to multiple-value function call");
6567 type
= Type::make_error_type();
6575 // Get the initial value of a variable. This does not
6576 // consider whether the variable is in the heap--it returns the
6577 // initial value as though it were always stored in the stack.
6580 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
6582 go_assert(this->preinit_
== NULL
);
6583 Location loc
= this->location();
6584 if (this->init_
== NULL
)
6586 go_assert(!this->is_parameter_
);
6587 if (this->is_global_
|| this->is_in_heap())
6589 Btype
* btype
= this->type()->get_backend(gogo
);
6590 return gogo
->backend()->zero_expression(btype
);
6594 Translate_context
context(gogo
, function
, NULL
, NULL
);
6595 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
6596 return init
->get_backend(&context
);
6600 // Get the initial value of a variable when a block is required.
6601 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6604 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
6605 Bvariable
* var_decl
)
6607 go_assert(this->preinit_
!= NULL
);
6609 // We want to add the variable assignment to the end of the preinit
6612 Translate_context
context(gogo
, function
, NULL
, NULL
);
6613 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
6614 Bfunction
* bfunction
=
6615 function
->func_value()->get_or_make_decl(gogo
, function
);
6617 // It's possible to have pre-init statements without an initializer
6618 // if the pre-init statements set the variable.
6619 Bstatement
* decl_init
= NULL
;
6620 if (this->init_
!= NULL
)
6622 if (var_decl
== NULL
)
6624 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
6625 decl_init
= gogo
->backend()->expression_statement(bfunction
,
6630 Location loc
= this->location();
6631 Expression
* val_expr
=
6632 Expression::make_cast(this->type(), this->init_
, loc
);
6633 Bexpression
* val
= val_expr
->get_backend(&context
);
6634 Bexpression
* var_ref
=
6635 gogo
->backend()->var_expression(var_decl
, VE_lvalue
, loc
);
6636 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
6640 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
6641 if (decl_init
!= NULL
)
6642 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
6646 // Export the variable
6649 Variable::export_var(Export
* exp
, const std::string
& name
) const
6651 go_assert(this->is_global_
);
6652 exp
->write_c_string("var ");
6653 exp
->write_string(name
);
6654 exp
->write_c_string(" ");
6655 exp
->write_type(this->type());
6656 exp
->write_c_string(";\n");
6659 // Import a variable.
6662 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
6664 imp
->require_c_string("var ");
6665 *pname
= imp
->read_identifier();
6666 imp
->require_c_string(" ");
6667 *ptype
= imp
->read_type();
6668 imp
->require_c_string(";\n");
6671 // Convert a variable to the backend representation.
6674 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6675 const Package
* package
, const std::string
& name
)
6677 if (this->backend_
== NULL
)
6679 Backend
* backend
= gogo
->backend();
6680 Type
* type
= this->type_
;
6681 if (type
->is_error_type()
6682 || (type
->is_undefined()
6683 && (!this->is_global_
|| package
== NULL
)))
6684 this->backend_
= backend
->error_variable();
6687 bool is_parameter
= this->is_parameter_
;
6688 if (this->is_receiver_
&& type
->points_to() == NULL
)
6689 is_parameter
= false;
6690 if (this->is_in_heap())
6692 is_parameter
= false;
6693 type
= Type::make_pointer_type(type
);
6696 const std::string n
= Gogo::unpack_hidden_name(name
);
6697 Btype
* btype
= type
->get_backend(gogo
);
6700 if (Map_type::is_zero_value(this))
6701 bvar
= Map_type::backend_zero_value(gogo
);
6702 else if (this->is_global_
)
6704 std::string
var_name(package
!= NULL
6705 ? package
->package_name()
6706 : gogo
->package_name());
6707 var_name
.push_back('.');
6710 std::string
asm_name(gogo
->global_var_asm_name(name
, package
));
6712 bool is_hidden
= Gogo::is_hidden_name(name
);
6713 // Hack to export runtime.writeBarrier. FIXME.
6714 // This is because go:linkname doesn't work on variables.
6715 if (gogo
->compiling_runtime()
6716 && var_name
== "runtime.writeBarrier")
6719 bvar
= backend
->global_variable(var_name
,
6724 this->in_unique_section_
,
6727 else if (function
== NULL
)
6729 go_assert(saw_errors());
6730 bvar
= backend
->error_variable();
6734 Bfunction
* bfunction
= function
->func_value()->get_decl();
6735 bool is_address_taken
= (this->is_non_escaping_address_taken_
6736 && !this->is_in_heap());
6737 if (this->is_closure())
6738 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
6740 else if (is_parameter
)
6741 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
6745 bvar
= backend
->local_variable(bfunction
, n
, btype
,
6749 this->backend_
= bvar
;
6752 return this->backend_
;
6755 // Class Result_variable.
6757 // Convert a result variable to the backend representation.
6760 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6761 const std::string
& name
)
6763 if (this->backend_
== NULL
)
6765 Backend
* backend
= gogo
->backend();
6766 Type
* type
= this->type_
;
6767 if (type
->is_error())
6768 this->backend_
= backend
->error_variable();
6771 if (this->is_in_heap())
6772 type
= Type::make_pointer_type(type
);
6773 Btype
* btype
= type
->get_backend(gogo
);
6774 Bfunction
* bfunction
= function
->func_value()->get_decl();
6775 std::string n
= Gogo::unpack_hidden_name(name
);
6776 bool is_address_taken
= (this->is_non_escaping_address_taken_
6777 && !this->is_in_heap());
6778 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
6783 return this->backend_
;
6786 // Class Named_constant.
6788 // Traverse the initializer expression.
6791 Named_constant::traverse_expression(Traverse
* traverse
)
6793 return Expression::traverse(&this->expr_
, traverse
);
6796 // Determine the type of the constant.
6799 Named_constant::determine_type()
6801 if (this->type_
!= NULL
)
6803 Type_context
context(this->type_
, false);
6804 this->expr_
->determine_type(&context
);
6808 // A constant may have an abstract type.
6809 Type_context
context(NULL
, true);
6810 this->expr_
->determine_type(&context
);
6811 this->type_
= this->expr_
->type();
6812 go_assert(this->type_
!= NULL
);
6816 // Indicate that we found and reported an error for this constant.
6819 Named_constant::set_error()
6821 this->type_
= Type::make_error_type();
6822 this->expr_
= Expression::make_error(this->location_
);
6825 // Export a constant.
6828 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
6830 exp
->write_c_string("const ");
6831 exp
->write_string(name
);
6832 exp
->write_c_string(" ");
6833 if (!this->type_
->is_abstract())
6835 exp
->write_type(this->type_
);
6836 exp
->write_c_string(" ");
6838 exp
->write_c_string("= ");
6839 this->expr()->export_expression(exp
);
6840 exp
->write_c_string(";\n");
6843 // Import a constant.
6846 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
6849 imp
->require_c_string("const ");
6850 *pname
= imp
->read_identifier();
6851 imp
->require_c_string(" ");
6852 if (imp
->peek_char() == '=')
6856 *ptype
= imp
->read_type();
6857 imp
->require_c_string(" ");
6859 imp
->require_c_string("= ");
6860 *pexpr
= Expression::import_expression(imp
);
6861 imp
->require_c_string(";\n");
6864 // Get the backend representation.
6867 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
6869 if (this->bconst_
== NULL
)
6871 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
6872 Type
* type
= this->type();
6873 Location loc
= this->location();
6875 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
6876 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
6877 if (type
!= NULL
&& type
->is_numeric_type())
6879 Btype
* btype
= type
->get_backend(gogo
);
6880 std::string name
= const_no
->get_id(gogo
);
6882 gogo
->backend()->named_constant_expression(btype
, name
,
6885 this->bconst_
= const_decl
;
6887 return this->bconst_
;
6893 Type_declaration::add_method(const std::string
& name
, Function
* function
)
6895 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
6896 this->methods_
.push_back(ret
);
6900 // Add a method declaration.
6903 Type_declaration::add_method_declaration(const std::string
& name
,
6905 Function_type
* type
,
6908 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
6910 this->methods_
.push_back(ret
);
6914 // Return whether any methods are defined.
6917 Type_declaration::has_methods() const
6919 return !this->methods_
.empty();
6922 // Define methods for the real type.
6925 Type_declaration::define_methods(Named_type
* nt
)
6927 if (this->methods_
.empty())
6930 while (nt
->is_alias())
6932 Type
*t
= nt
->real_type()->forwarded();
6933 if (t
->named_type() != NULL
)
6934 nt
= t
->named_type();
6935 else if (t
->forward_declaration_type() != NULL
)
6937 Named_object
* no
= t
->forward_declaration_type()->named_object();
6938 Type_declaration
* td
= no
->type_declaration_value();
6939 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
6940 this->methods_
.end());
6941 this->methods_
.clear();
6946 for (std::vector
<Named_object
*>::const_iterator p
=
6947 this->methods_
.begin();
6948 p
!= this->methods_
.end();
6950 go_error_at((*p
)->location(),
6951 ("invalid receiver type "
6952 "(receiver must be a named type"));
6957 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
6958 p
!= this->methods_
.end();
6961 if (!(*p
)->func_value()->is_sink())
6962 nt
->add_existing_method(*p
);
6966 // We are using the type. Return true if we should issue a warning.
6969 Type_declaration::using_type()
6971 bool ret
= !this->issued_warning_
;
6972 this->issued_warning_
= true;
6976 // Class Unknown_name.
6978 // Set the real named object.
6981 Unknown_name::set_real_named_object(Named_object
* no
)
6983 go_assert(this->real_named_object_
== NULL
);
6984 go_assert(!no
->is_unknown());
6985 this->real_named_object_
= no
;
6988 // Class Named_object.
6990 Named_object::Named_object(const std::string
& name
,
6991 const Package
* package
,
6992 Classification classification
)
6993 : name_(name
), package_(package
), classification_(classification
),
6994 is_redefinition_(false)
6996 if (Gogo::is_sink_name(name
))
6997 go_assert(classification
== NAMED_OBJECT_SINK
);
7000 // Make an unknown name. This is used by the parser. The name must
7001 // be resolved later. Unknown names are only added in the current
7005 Named_object::make_unknown_name(const std::string
& name
,
7008 Named_object
* named_object
= new Named_object(name
, NULL
,
7009 NAMED_OBJECT_UNKNOWN
);
7010 Unknown_name
* value
= new Unknown_name(location
);
7011 named_object
->u_
.unknown_value
= value
;
7012 return named_object
;
7018 Named_object::make_constant(const Typed_identifier
& tid
,
7019 const Package
* package
, Expression
* expr
,
7022 Named_object
* named_object
= new Named_object(tid
.name(), package
,
7023 NAMED_OBJECT_CONST
);
7024 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
7027 named_object
->u_
.const_value
= named_constant
;
7028 return named_object
;
7031 // Make a named type.
7034 Named_object::make_type(const std::string
& name
, const Package
* package
,
7035 Type
* type
, Location location
)
7037 Named_object
* named_object
= new Named_object(name
, package
,
7039 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
7040 named_object
->u_
.type_value
= named_type
;
7041 return named_object
;
7044 // Make a type declaration.
7047 Named_object::make_type_declaration(const std::string
& name
,
7048 const Package
* package
,
7051 Named_object
* named_object
= new Named_object(name
, package
,
7052 NAMED_OBJECT_TYPE_DECLARATION
);
7053 Type_declaration
* type_declaration
= new Type_declaration(location
);
7054 named_object
->u_
.type_declaration
= type_declaration
;
7055 return named_object
;
7061 Named_object::make_variable(const std::string
& name
, const Package
* package
,
7064 Named_object
* named_object
= new Named_object(name
, package
,
7066 named_object
->u_
.var_value
= variable
;
7067 return named_object
;
7070 // Make a result variable.
7073 Named_object::make_result_variable(const std::string
& name
,
7074 Result_variable
* result
)
7076 Named_object
* named_object
= new Named_object(name
, NULL
,
7077 NAMED_OBJECT_RESULT_VAR
);
7078 named_object
->u_
.result_var_value
= result
;
7079 return named_object
;
7082 // Make a sink. This is used for the special blank identifier _.
7085 Named_object::make_sink()
7087 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
7090 // Make a named function.
7093 Named_object::make_function(const std::string
& name
, const Package
* package
,
7096 Named_object
* named_object
= new Named_object(name
, package
,
7098 named_object
->u_
.func_value
= function
;
7099 return named_object
;
7102 // Make a function declaration.
7105 Named_object::make_function_declaration(const std::string
& name
,
7106 const Package
* package
,
7107 Function_type
* fntype
,
7110 Named_object
* named_object
= new Named_object(name
, package
,
7111 NAMED_OBJECT_FUNC_DECLARATION
);
7112 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
7113 named_object
->u_
.func_declaration_value
= func_decl
;
7114 return named_object
;
7120 Named_object::make_package(const std::string
& alias
, Package
* package
)
7122 Named_object
* named_object
= new Named_object(alias
, NULL
,
7123 NAMED_OBJECT_PACKAGE
);
7124 named_object
->u_
.package_value
= package
;
7125 return named_object
;
7128 // Return the name to use in an error message.
7131 Named_object::message_name() const
7133 if (this->package_
== NULL
)
7134 return Gogo::message_name(this->name_
);
7136 if (this->package_
->has_package_name())
7137 ret
= this->package_
->package_name();
7139 ret
= this->package_
->pkgpath();
7140 ret
= Gogo::message_name(ret
);
7142 ret
+= Gogo::message_name(this->name_
);
7146 // Set the type when a declaration is defined.
7149 Named_object::set_type_value(Named_type
* named_type
)
7151 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
7152 Type_declaration
* td
= this->u_
.type_declaration
;
7153 td
->define_methods(named_type
);
7155 Named_object
* in_function
= td
->in_function(&index
);
7156 if (in_function
!= NULL
)
7157 named_type
->set_in_function(in_function
, index
);
7159 this->classification_
= NAMED_OBJECT_TYPE
;
7160 this->u_
.type_value
= named_type
;
7163 // Define a function which was previously declared.
7166 Named_object::set_function_value(Function
* function
)
7168 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
7169 if (this->func_declaration_value()->has_descriptor())
7171 Expression
* descriptor
=
7172 this->func_declaration_value()->descriptor(NULL
, NULL
);
7173 function
->set_descriptor(descriptor
);
7175 this->classification_
= NAMED_OBJECT_FUNC
;
7176 // FIXME: We should free the old value.
7177 this->u_
.func_value
= function
;
7180 // Declare an unknown object as a type declaration.
7183 Named_object::declare_as_type()
7185 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
7186 Unknown_name
* unk
= this->u_
.unknown_value
;
7187 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
7188 this->u_
.type_declaration
= new Type_declaration(unk
->location());
7192 // Return the location of a named object.
7195 Named_object::location() const
7197 switch (this->classification_
)
7200 case NAMED_OBJECT_UNINITIALIZED
:
7203 case NAMED_OBJECT_ERRONEOUS
:
7204 return Linemap::unknown_location();
7206 case NAMED_OBJECT_UNKNOWN
:
7207 return this->unknown_value()->location();
7209 case NAMED_OBJECT_CONST
:
7210 return this->const_value()->location();
7212 case NAMED_OBJECT_TYPE
:
7213 return this->type_value()->location();
7215 case NAMED_OBJECT_TYPE_DECLARATION
:
7216 return this->type_declaration_value()->location();
7218 case NAMED_OBJECT_VAR
:
7219 return this->var_value()->location();
7221 case NAMED_OBJECT_RESULT_VAR
:
7222 return this->result_var_value()->location();
7224 case NAMED_OBJECT_SINK
:
7227 case NAMED_OBJECT_FUNC
:
7228 return this->func_value()->location();
7230 case NAMED_OBJECT_FUNC_DECLARATION
:
7231 return this->func_declaration_value()->location();
7233 case NAMED_OBJECT_PACKAGE
:
7234 return this->package_value()->location();
7238 // Export a named object.
7241 Named_object::export_named_object(Export
* exp
) const
7243 switch (this->classification_
)
7246 case NAMED_OBJECT_UNINITIALIZED
:
7247 case NAMED_OBJECT_UNKNOWN
:
7250 case NAMED_OBJECT_ERRONEOUS
:
7253 case NAMED_OBJECT_CONST
:
7254 this->const_value()->export_const(exp
, this->name_
);
7257 case NAMED_OBJECT_TYPE
:
7258 this->type_value()->export_named_type(exp
, this->name_
);
7261 case NAMED_OBJECT_TYPE_DECLARATION
:
7262 go_error_at(this->type_declaration_value()->location(),
7263 "attempt to export %<%s%> which was declared but not defined",
7264 this->message_name().c_str());
7267 case NAMED_OBJECT_FUNC_DECLARATION
:
7268 this->func_declaration_value()->export_func(exp
, this->name_
);
7271 case NAMED_OBJECT_VAR
:
7272 this->var_value()->export_var(exp
, this->name_
);
7275 case NAMED_OBJECT_RESULT_VAR
:
7276 case NAMED_OBJECT_SINK
:
7279 case NAMED_OBJECT_FUNC
:
7280 this->func_value()->export_func(exp
, this->name_
);
7285 // Convert a variable to the backend representation.
7288 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
7290 if (this->classification_
== NAMED_OBJECT_VAR
)
7291 return this->var_value()->get_backend_variable(gogo
, function
,
7292 this->package_
, this->name_
);
7293 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
7294 return this->result_var_value()->get_backend_variable(gogo
, function
,
7300 // Return the external identifier for this object.
7303 Named_object::get_id(Gogo
* gogo
)
7305 go_assert(!this->is_variable()
7306 && !this->is_result_variable()
7307 && !this->is_type());
7308 std::string decl_name
;
7309 if (this->is_function_declaration()
7310 && !this->func_declaration_value()->asm_name().empty())
7311 decl_name
= this->func_declaration_value()->asm_name();
7314 std::string package_name
;
7315 if (this->package_
== NULL
)
7316 package_name
= gogo
->package_name();
7318 package_name
= this->package_
->package_name();
7320 // Note that this will be misleading if this is an unexported
7321 // method generated for an embedded imported type. In that case
7322 // the unexported method should have the package name of the
7323 // package from which it is imported, but we are going to give
7324 // it our package name. Fixing this would require knowing the
7325 // package name, but we only know the package path. It might be
7326 // better to use package paths here anyhow. This doesn't affect
7327 // the assembler code, because we always set that name in
7328 // Function::get_or_make_decl anyhow. FIXME.
7330 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
7332 Function_type
* fntype
;
7333 if (this->is_function())
7334 fntype
= this->func_value()->type();
7335 else if (this->is_function_declaration())
7336 fntype
= this->func_declaration_value()->type();
7339 if (fntype
!= NULL
&& fntype
->is_method())
7341 decl_name
.push_back('.');
7342 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
7348 // Get the backend representation for this named object.
7351 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
7352 std::vector
<Btype
*>& type_decls
,
7353 std::vector
<Bfunction
*>& func_decls
)
7355 // If this is a definition, avoid trying to get the backend
7356 // representation, as that can crash.
7357 if (this->is_redefinition_
)
7359 go_assert(saw_errors());
7363 switch (this->classification_
)
7365 case NAMED_OBJECT_CONST
:
7366 if (!Gogo::is_erroneous_name(this->name_
))
7367 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
7370 case NAMED_OBJECT_TYPE
:
7372 Named_type
* named_type
= this->u_
.type_value
;
7373 if (!Gogo::is_erroneous_name(this->name_
))
7374 type_decls
.push_back(named_type
->get_backend(gogo
));
7376 // We need to produce a type descriptor for every named
7377 // type, and for a pointer to every named type, since
7378 // other files or packages might refer to them. We need
7379 // to do this even for hidden types, because they might
7380 // still be returned by some function. Simply calling the
7381 // type_descriptor method is enough to create the type
7382 // descriptor, even though we don't do anything with it.
7383 if (this->package_
== NULL
&& !saw_errors())
7386 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7387 named_type
->gc_symbol_pointer(gogo
);
7388 Type
* pn
= Type::make_pointer_type(named_type
);
7389 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7390 pn
->gc_symbol_pointer(gogo
);
7395 case NAMED_OBJECT_TYPE_DECLARATION
:
7396 go_error_at(Linemap::unknown_location(),
7397 "reference to undefined type %qs",
7398 this->message_name().c_str());
7401 case NAMED_OBJECT_VAR
:
7402 case NAMED_OBJECT_RESULT_VAR
:
7403 case NAMED_OBJECT_SINK
:
7406 case NAMED_OBJECT_FUNC
:
7408 Function
* func
= this->u_
.func_value
;
7409 if (!Gogo::is_erroneous_name(this->name_
))
7410 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
7412 if (func
->block() != NULL
)
7413 func
->build(gogo
, this);
7417 case NAMED_OBJECT_ERRONEOUS
:
7427 Bindings::Bindings(Bindings
* enclosing
)
7428 : enclosing_(enclosing
), named_objects_(), bindings_()
7435 Bindings::clear_file_scope(Gogo
* gogo
)
7437 Contour::iterator p
= this->bindings_
.begin();
7438 while (p
!= this->bindings_
.end())
7441 if (p
->second
->package() != NULL
)
7443 else if (p
->second
->is_package())
7445 else if (p
->second
->is_function()
7446 && !p
->second
->func_value()->type()->is_method()
7447 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
7456 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
7457 p
= this->bindings_
.erase(p
);
7462 // Look up a symbol.
7465 Bindings::lookup(const std::string
& name
) const
7467 Contour::const_iterator p
= this->bindings_
.find(name
);
7468 if (p
!= this->bindings_
.end())
7469 return p
->second
->resolve();
7470 else if (this->enclosing_
!= NULL
)
7471 return this->enclosing_
->lookup(name
);
7476 // Look up a symbol locally.
7479 Bindings::lookup_local(const std::string
& name
) const
7481 Contour::const_iterator p
= this->bindings_
.find(name
);
7482 if (p
== this->bindings_
.end())
7487 // Remove an object from a set of bindings. This is used for a
7488 // special case in thunks for functions which call recover.
7491 Bindings::remove_binding(Named_object
* no
)
7493 Contour::iterator pb
= this->bindings_
.find(no
->name());
7494 go_assert(pb
!= this->bindings_
.end());
7495 this->bindings_
.erase(pb
);
7496 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
7497 pn
!= this->named_objects_
.end();
7502 this->named_objects_
.erase(pn
);
7509 // Add a method to the list of objects. This is not added to the
7510 // lookup table. This is so that we have a single list of objects
7511 // declared at the top level, which we walk through when it's time to
7512 // convert to trees.
7515 Bindings::add_method(Named_object
* method
)
7517 this->named_objects_
.push_back(method
);
7520 // Add a generic Named_object to a Contour.
7523 Bindings::add_named_object_to_contour(Contour
* contour
,
7524 Named_object
* named_object
)
7526 go_assert(named_object
== named_object
->resolve());
7527 const std::string
& name(named_object
->name());
7528 go_assert(!Gogo::is_sink_name(name
));
7530 std::pair
<Contour::iterator
, bool> ins
=
7531 contour
->insert(std::make_pair(name
, named_object
));
7534 // The name was already there.
7535 if (named_object
->package() != NULL
7536 && ins
.first
->second
->package() == named_object
->package()
7537 && (ins
.first
->second
->classification()
7538 == named_object
->classification()))
7540 // This is a second import of the same object.
7541 return ins
.first
->second
;
7543 ins
.first
->second
= this->new_definition(ins
.first
->second
,
7545 return ins
.first
->second
;
7549 // Don't push declarations on the list. We push them on when
7550 // and if we find the definitions. That way we genericize the
7551 // functions in order.
7552 if (!named_object
->is_type_declaration()
7553 && !named_object
->is_function_declaration()
7554 && !named_object
->is_unknown())
7555 this->named_objects_
.push_back(named_object
);
7556 return named_object
;
7560 // We had an existing named object OLD_OBJECT, and we've seen a new
7561 // one NEW_OBJECT with the same name. FIXME: This does not free the
7562 // new object when we don't need it.
7565 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
7567 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
7571 switch (old_object
->classification())
7574 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
7577 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7580 case Named_object::NAMED_OBJECT_UNKNOWN
:
7582 Named_object
* real
= old_object
->unknown_value()->real_named_object();
7584 return this->new_definition(real
, new_object
);
7585 go_assert(!new_object
->is_unknown());
7586 old_object
->unknown_value()->set_real_named_object(new_object
);
7587 if (!new_object
->is_type_declaration()
7588 && !new_object
->is_function_declaration())
7589 this->named_objects_
.push_back(new_object
);
7593 case Named_object::NAMED_OBJECT_CONST
:
7596 case Named_object::NAMED_OBJECT_TYPE
:
7597 if (new_object
->is_type_declaration())
7601 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7602 if (new_object
->is_type_declaration())
7604 if (new_object
->is_type())
7606 old_object
->set_type_value(new_object
->type_value());
7607 new_object
->type_value()->set_named_object(old_object
);
7608 this->named_objects_
.push_back(old_object
);
7613 case Named_object::NAMED_OBJECT_VAR
:
7614 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7615 // We have already given an error in the parser for cases where
7616 // one parameter or result variable redeclares another one.
7617 if ((new_object
->is_variable()
7618 && new_object
->var_value()->is_parameter())
7619 || new_object
->is_result_variable())
7623 case Named_object::NAMED_OBJECT_SINK
:
7626 case Named_object::NAMED_OBJECT_FUNC
:
7627 if (new_object
->is_function_declaration())
7629 if (!new_object
->func_declaration_value()->asm_name().empty())
7630 go_error_at(Linemap::unknown_location(),
7631 ("sorry, not implemented: "
7632 "__asm__ for function definitions"));
7633 Function_type
* old_type
= old_object
->func_value()->type();
7634 Function_type
* new_type
=
7635 new_object
->func_declaration_value()->type();
7636 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7641 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7643 if (new_object
->is_function())
7645 Function_type
* old_type
=
7646 old_object
->func_declaration_value()->type();
7647 Function_type
* new_type
= new_object
->func_value()->type();
7648 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7650 if (!old_object
->func_declaration_value()->asm_name().empty())
7651 go_error_at(Linemap::unknown_location(),
7652 ("sorry, not implemented: "
7653 "__asm__ for function definitions"));
7654 old_object
->set_function_value(new_object
->func_value());
7655 this->named_objects_
.push_back(old_object
);
7662 case Named_object::NAMED_OBJECT_PACKAGE
:
7666 std::string n
= old_object
->message_name();
7668 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
7670 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
7672 old_object
->set_is_redefinition();
7673 new_object
->set_is_redefinition();
7675 go_inform(old_object
->location(), "previous definition of %qs was here",
7681 // Add a named type.
7684 Bindings::add_named_type(Named_type
* named_type
)
7686 return this->add_named_object(named_type
->named_object());
7692 Bindings::add_function(const std::string
& name
, const Package
* package
,
7695 return this->add_named_object(Named_object::make_function(name
, package
,
7699 // Add a function declaration.
7702 Bindings::add_function_declaration(const std::string
& name
,
7703 const Package
* package
,
7704 Function_type
* type
,
7707 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
7709 return this->add_named_object(no
);
7712 // Define a type which was previously declared.
7715 Bindings::define_type(Named_object
* no
, Named_type
* type
)
7717 no
->set_type_value(type
);
7718 this->named_objects_
.push_back(no
);
7721 // Mark all local variables as used. This is used for some types of
7725 Bindings::mark_locals_used()
7727 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
7728 p
!= this->named_objects_
.end();
7730 if ((*p
)->is_variable())
7731 (*p
)->var_value()->set_is_used();
7734 // Traverse bindings.
7737 Bindings::traverse(Traverse
* traverse
, bool is_global
)
7739 unsigned int traverse_mask
= traverse
->traverse_mask();
7741 // We don't use an iterator because we permit the traversal to add
7742 // new global objects.
7743 const unsigned int e_or_t
= (Traverse::traverse_expressions
7744 | Traverse::traverse_types
);
7745 const unsigned int e_or_t_or_s
= (e_or_t
7746 | Traverse::traverse_statements
);
7747 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
7749 Named_object
* p
= this->named_objects_
[i
];
7750 int t
= TRAVERSE_CONTINUE
;
7751 switch (p
->classification())
7753 case Named_object::NAMED_OBJECT_CONST
:
7754 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
7755 t
= traverse
->constant(p
, is_global
);
7756 if (t
== TRAVERSE_CONTINUE
7757 && (traverse_mask
& e_or_t
) != 0)
7759 Type
* tc
= p
->const_value()->type();
7761 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
7762 return TRAVERSE_EXIT
;
7763 t
= p
->const_value()->traverse_expression(traverse
);
7767 case Named_object::NAMED_OBJECT_VAR
:
7768 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7769 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
7770 t
= traverse
->variable(p
);
7771 if (t
== TRAVERSE_CONTINUE
7772 && (traverse_mask
& e_or_t
) != 0)
7774 if (p
->is_result_variable()
7775 || p
->var_value()->has_type())
7777 Type
* tv
= (p
->is_variable()
7778 ? p
->var_value()->type()
7779 : p
->result_var_value()->type());
7781 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
7782 return TRAVERSE_EXIT
;
7785 if (t
== TRAVERSE_CONTINUE
7786 && (traverse_mask
& e_or_t_or_s
) != 0
7787 && p
->is_variable())
7788 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
7791 case Named_object::NAMED_OBJECT_FUNC
:
7792 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
7793 t
= traverse
->function(p
);
7795 if (t
== TRAVERSE_CONTINUE
7797 & (Traverse::traverse_variables
7798 | Traverse::traverse_constants
7799 | Traverse::traverse_functions
7800 | Traverse::traverse_blocks
7801 | Traverse::traverse_statements
7802 | Traverse::traverse_expressions
7803 | Traverse::traverse_types
)) != 0)
7804 t
= p
->func_value()->traverse(traverse
);
7807 case Named_object::NAMED_OBJECT_PACKAGE
:
7808 // These are traversed in Gogo::traverse.
7809 go_assert(is_global
);
7812 case Named_object::NAMED_OBJECT_TYPE
:
7813 if ((traverse_mask
& e_or_t
) != 0)
7814 t
= Type::traverse(p
->type_value(), traverse
);
7817 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7818 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7819 case Named_object::NAMED_OBJECT_UNKNOWN
:
7820 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7823 case Named_object::NAMED_OBJECT_SINK
:
7828 if (t
== TRAVERSE_EXIT
)
7829 return TRAVERSE_EXIT
;
7832 // If we need to traverse types, check the function declarations,
7833 // which have types. Also check any methods of a type declaration.
7834 if ((traverse_mask
& e_or_t
) != 0)
7836 for (Bindings::const_declarations_iterator p
=
7837 this->begin_declarations();
7838 p
!= this->end_declarations();
7841 if (p
->second
->is_function_declaration())
7843 if (Type::traverse(p
->second
->func_declaration_value()->type(),
7846 return TRAVERSE_EXIT
;
7848 else if (p
->second
->is_type_declaration())
7850 const std::vector
<Named_object
*>* methods
=
7851 p
->second
->type_declaration_value()->methods();
7852 for (std::vector
<Named_object
*>::const_iterator pm
=
7854 pm
!= methods
->end();
7857 Named_object
* no
= *pm
;
7859 if (no
->is_function())
7860 t
= no
->func_value()->type();
7861 else if (no
->is_function_declaration())
7862 t
= no
->func_declaration_value()->type();
7865 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
7866 return TRAVERSE_EXIT
;
7872 return TRAVERSE_CONTINUE
;
7877 // Clear any references to this label.
7882 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
7883 p
!= this->refs_
.end();
7886 this->refs_
.clear();
7889 // Get the backend representation for a label.
7892 Label::get_backend_label(Translate_context
* context
)
7894 if (this->blabel_
== NULL
)
7896 Function
* function
= context
->function()->func_value();
7897 Bfunction
* bfunction
= function
->get_decl();
7898 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
7901 return this->blabel_
;
7904 // Return an expression for the address of this label.
7907 Label::get_addr(Translate_context
* context
, Location location
)
7909 Blabel
* label
= this->get_backend_label(context
);
7910 return context
->backend()->label_address(label
, location
);
7913 // Return the dummy label that represents any instance of the blank label.
7916 Label::create_dummy_label()
7918 static Label
* dummy_label
;
7919 if (dummy_label
== NULL
)
7921 dummy_label
= new Label("_");
7922 dummy_label
->set_is_used();
7927 // Class Unnamed_label.
7929 // Get the backend representation for an unnamed label.
7932 Unnamed_label::get_blabel(Translate_context
* context
)
7934 if (this->blabel_
== NULL
)
7936 Function
* function
= context
->function()->func_value();
7937 Bfunction
* bfunction
= function
->get_decl();
7938 this->blabel_
= context
->backend()->label(bfunction
, "",
7941 return this->blabel_
;
7944 // Return a statement which defines this unnamed label.
7947 Unnamed_label::get_definition(Translate_context
* context
)
7949 Blabel
* blabel
= this->get_blabel(context
);
7950 return context
->backend()->label_definition_statement(blabel
);
7953 // Return a goto statement to this unnamed label.
7956 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
7958 Blabel
* blabel
= this->get_blabel(context
);
7959 return context
->backend()->goto_statement(blabel
, location
);
7964 Package::Package(const std::string
& pkgpath
,
7965 const std::string
& pkgpath_symbol
, Location location
)
7966 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
7967 package_name_(), bindings_(new Bindings(NULL
)),
7970 go_assert(!pkgpath
.empty());
7973 // Set the package name.
7976 Package::set_package_name(const std::string
& package_name
, Location location
)
7978 go_assert(!package_name
.empty());
7979 if (this->package_name_
.empty())
7980 this->package_name_
= package_name
;
7981 else if (this->package_name_
!= package_name
)
7982 go_error_at(location
,
7983 ("saw two different packages with "
7984 "the same package path %s: %s, %s"),
7985 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
7986 package_name
.c_str());
7989 // Return the pkgpath symbol, which is a prefix for symbols defined in
7993 Package::pkgpath_symbol() const
7995 if (this->pkgpath_symbol_
.empty())
7996 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
7997 return this->pkgpath_symbol_
;
8000 // Set the package path symbol.
8003 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
8005 go_assert(!pkgpath_symbol
.empty());
8006 if (this->pkgpath_symbol_
.empty())
8007 this->pkgpath_symbol_
= pkgpath_symbol
;
8009 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
8012 // Note that symbol from this package was and qualified by ALIAS.
8015 Package::note_usage(const std::string
& alias
) const
8017 Aliases::const_iterator p
= this->aliases_
.find(alias
);
8018 go_assert(p
!= this->aliases_
.end());
8019 p
->second
->note_usage();
8022 // Forget a given usage. If forgetting this usage means this package becomes
8023 // unused, report that error.
8026 Package::forget_usage(Expression
* usage
) const
8028 if (this->fake_uses_
.empty())
8031 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
8032 go_assert(p
!= this->fake_uses_
.end());
8033 this->fake_uses_
.erase(p
);
8035 if (this->fake_uses_
.empty())
8036 go_error_at(this->location(), "imported and not used: %s",
8037 Gogo::message_name(this->package_name()).c_str());
8040 // Clear the used field for the next file. If the only usages of this package
8041 // are possibly fake, keep the fake usages for lowering.
8044 Package::clear_used()
8046 std::string dot_alias
= "." + this->package_name();
8047 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
8048 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
8049 this->fake_uses_
.clear();
8051 this->aliases_
.clear();
8055 Package::add_alias(const std::string
& alias
, Location location
)
8057 Aliases::const_iterator p
= this->aliases_
.find(alias
);
8058 if (p
== this->aliases_
.end())
8060 std::pair
<Aliases::iterator
, bool> ret
;
8061 ret
= this->aliases_
.insert(std::make_pair(alias
,
8062 new Package_alias(location
)));
8068 // Determine types of constants. Everything else in a package
8069 // (variables, function declarations) should already have a fixed
8070 // type. Constants may have abstract types.
8073 Package::determine_types()
8075 Bindings
* bindings
= this->bindings_
;
8076 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
8077 p
!= bindings
->end_definitions();
8080 if ((*p
)->is_const())
8081 (*p
)->const_value()->determine_type();
8089 Traverse::~Traverse()
8091 if (this->types_seen_
!= NULL
)
8092 delete this->types_seen_
;
8093 if (this->expressions_seen_
!= NULL
)
8094 delete this->expressions_seen_
;
8097 // Record that we are looking at a type, and return true if we have
8101 Traverse::remember_type(const Type
* type
)
8103 if (type
->is_error_type())
8105 go_assert((this->traverse_mask() & traverse_types
) != 0
8106 || (this->traverse_mask() & traverse_expressions
) != 0);
8107 // We mostly only have to remember named types. But it turns out
8108 // that an interface type can refer to itself without using a name
8109 // by relying on interface inheritance, as in
8110 // type I interface { F() interface{I} }
8111 if (type
->classification() != Type::TYPE_NAMED
8112 && type
->classification() != Type::TYPE_INTERFACE
)
8114 if (this->types_seen_
== NULL
)
8115 this->types_seen_
= new Types_seen();
8116 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
8120 // Record that we are looking at an expression, and return true if we
8121 // have already seen it. NB: this routine used to assert if the traverse
8122 // mask did not include expressions/types -- this is no longer the case,
8123 // since it can be useful to remember specific expressions during
8124 // walks that only cover statements.
8127 Traverse::remember_expression(const Expression
* expression
)
8129 if (this->expressions_seen_
== NULL
)
8130 this->expressions_seen_
= new Expressions_seen();
8131 std::pair
<Expressions_seen::iterator
, bool> ins
=
8132 this->expressions_seen_
->insert(expression
);
8136 // The default versions of these functions should never be called: the
8137 // traversal mask indicates which functions may be called.
8140 Traverse::variable(Named_object
*)
8146 Traverse::constant(Named_object
*, bool)
8152 Traverse::function(Named_object
*)
8158 Traverse::block(Block
*)
8164 Traverse::statement(Block
*, size_t*, Statement
*)
8170 Traverse::expression(Expression
**)
8176 Traverse::type(Type
*)
8181 // Class Statement_inserter.
8184 Statement_inserter::insert(Statement
* s
)
8186 if (this->block_
!= NULL
)
8188 go_assert(this->pindex_
!= NULL
);
8189 this->block_
->insert_statement_before(*this->pindex_
, s
);
8192 else if (this->var_
!= NULL
)
8193 this->var_
->add_preinit_statement(this->gogo_
, s
);
8195 go_assert(saw_errors());