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),
58 debug_optimization_(false),
59 nil_check_size_threshold_(4096),
63 specific_type_functions_(),
64 specific_type_functions_are_written_(false),
65 named_types_are_converted_(false),
69 imported_inlinable_functions_(),
70 imported_inline_functions_()
72 const Location loc
= Linemap::predeclared_location();
74 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
75 RUNTIME_TYPE_KIND_UINT8
);
76 this->add_named_type(uint8_type
);
77 this->add_named_type(Type::make_integer_type("uint16", true, 16,
78 RUNTIME_TYPE_KIND_UINT16
));
79 this->add_named_type(Type::make_integer_type("uint32", true, 32,
80 RUNTIME_TYPE_KIND_UINT32
));
81 this->add_named_type(Type::make_integer_type("uint64", true, 64,
82 RUNTIME_TYPE_KIND_UINT64
));
84 this->add_named_type(Type::make_integer_type("int8", false, 8,
85 RUNTIME_TYPE_KIND_INT8
));
86 this->add_named_type(Type::make_integer_type("int16", false, 16,
87 RUNTIME_TYPE_KIND_INT16
));
88 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
89 RUNTIME_TYPE_KIND_INT32
);
90 this->add_named_type(int32_type
);
91 this->add_named_type(Type::make_integer_type("int64", false, 64,
92 RUNTIME_TYPE_KIND_INT64
));
94 this->add_named_type(Type::make_float_type("float32", 32,
95 RUNTIME_TYPE_KIND_FLOAT32
));
96 this->add_named_type(Type::make_float_type("float64", 64,
97 RUNTIME_TYPE_KIND_FLOAT64
));
99 this->add_named_type(Type::make_complex_type("complex64", 64,
100 RUNTIME_TYPE_KIND_COMPLEX64
));
101 this->add_named_type(Type::make_complex_type("complex128", 128,
102 RUNTIME_TYPE_KIND_COMPLEX128
));
104 int int_type_size
= pointer_size
;
105 if (int_type_size
< 32)
107 this->add_named_type(Type::make_integer_type("uint", true,
109 RUNTIME_TYPE_KIND_UINT
));
110 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
111 RUNTIME_TYPE_KIND_INT
);
112 this->add_named_type(int_type
);
114 this->add_named_type(Type::make_integer_type("uintptr", true,
116 RUNTIME_TYPE_KIND_UINTPTR
));
118 // "byte" is an alias for "uint8".
119 uint8_type
->integer_type()->set_is_byte();
120 this->add_named_type(Type::make_integer_type_alias("byte", uint8_type
));
122 // "rune" is an alias for "int32".
123 int32_type
->integer_type()->set_is_rune();
124 this->add_named_type(Type::make_integer_type_alias("rune", int32_type
));
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
);
259 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
261 go_assert(!pkgpath
.empty());
262 return go_encode_id(pkgpath
);
265 // Return a hash code for a string, given a starting hash.
268 Gogo::hash_string(const std::string
& s
, unsigned int h
)
270 const char* p
= s
.data();
271 size_t len
= s
.length();
272 for (; len
> 0; --len
)
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 pd
=
491 bindings
->begin_declarations();
492 pd
!= bindings
->end_declarations();
494 this->add_dot_import_object(pd
->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
= new Import(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
));
532 // FIXME: we never delete imp; we may need it for inlinable functions.
536 Gogo::lookup_init(const std::string
& init_name
)
538 Import_init
tmp("", init_name
, -1);
539 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
540 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
543 // Add an import control function for an imported package to the list.
546 Gogo::add_import_init_fn(const std::string
& package_name
,
547 const std::string
& init_name
, int prio
)
549 for (Import_init_set::iterator p
=
550 this->imported_init_fns_
.begin();
551 p
!= this->imported_init_fns_
.end();
554 Import_init
*ii
= (*p
);
555 if (ii
->init_name() == init_name
)
557 // If a test of package P1, built as part of package P1,
558 // imports package P2, and P2 imports P1 (perhaps
559 // indirectly), then we will see the same import name with
560 // different import priorities. That is OK, so don't give
561 // an error about it.
562 if (ii
->package_name() != package_name
)
564 go_error_at(Linemap::unknown_location(),
565 "duplicate package initialization name %qs",
566 Gogo::message_name(init_name
).c_str());
567 go_inform(Linemap::unknown_location(), "used by package %qs",
568 Gogo::message_name(ii
->package_name()).c_str());
569 go_inform(Linemap::unknown_location(), " and by package %qs",
570 Gogo::message_name(package_name
).c_str());
572 ii
->set_priority(prio
);
577 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
578 this->imported_init_fns_
.insert(nii
);
581 // Return whether we are at the global binding level.
584 Gogo::in_global_scope() const
586 return this->functions_
.empty();
589 // Return the current binding contour.
592 Gogo::current_bindings()
594 if (!this->functions_
.empty())
595 return this->functions_
.back().blocks
.back()->bindings();
596 else if (this->package_
!= NULL
)
597 return this->package_
->bindings();
599 return this->globals_
;
603 Gogo::current_bindings() const
605 if (!this->functions_
.empty())
606 return this->functions_
.back().blocks
.back()->bindings();
607 else if (this->package_
!= NULL
)
608 return this->package_
->bindings();
610 return this->globals_
;
614 Gogo::update_init_priority(Import_init
* ii
,
615 std::set
<const Import_init
*>* visited
)
620 for (std::set
<std::string
>::const_iterator pci
=
621 ii
->precursors().begin();
622 pci
!= ii
->precursors().end();
625 Import_init
* succ
= this->lookup_init(*pci
);
626 if (visited
->find(succ
) == visited
->end())
627 update_init_priority(succ
, visited
);
628 succ_prior
= std::max(succ_prior
, succ
->priority());
630 if (ii
->priority() <= succ_prior
)
631 ii
->set_priority(succ_prior
+ 1);
635 Gogo::recompute_init_priorities()
637 std::set
<Import_init
*> nonroots
;
639 for (Import_init_set::const_iterator p
=
640 this->imported_init_fns_
.begin();
641 p
!= this->imported_init_fns_
.end();
644 const Import_init
*ii
= *p
;
645 for (std::set
<std::string
>::const_iterator pci
=
646 ii
->precursors().begin();
647 pci
!= ii
->precursors().end();
650 Import_init
* ii_init
= this->lookup_init(*pci
);
651 nonroots
.insert(ii_init
);
655 // Recursively update priorities starting at roots.
656 std::set
<const Import_init
*> visited
;
657 for (Import_init_set::iterator p
=
658 this->imported_init_fns_
.begin();
659 p
!= this->imported_init_fns_
.end();
662 Import_init
* ii
= *p
;
663 if (nonroots
.find(ii
) != nonroots
.end())
665 update_init_priority(ii
, &visited
);
669 // Add statements to INIT_STMTS which run the initialization
670 // functions for imported packages. This is only used for the "main"
674 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
676 go_assert(this->is_main_package());
678 if (this->imported_init_fns_
.empty())
681 Location unknown_loc
= Linemap::unknown_location();
682 Function_type
* func_type
=
683 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
684 Btype
* fntype
= func_type
->get_backend_fntype(this);
686 // Recompute init priorities based on a walk of the init graph.
687 recompute_init_priorities();
689 // We must call them in increasing priority order.
690 std::vector
<const Import_init
*> v
;
691 for (Import_init_set::const_iterator p
=
692 this->imported_init_fns_
.begin();
693 p
!= this->imported_init_fns_
.end();
696 // Don't include dummy inits. They are not real functions.
697 if ((*p
)->is_dummy())
699 if ((*p
)->priority() < 0)
700 go_error_at(Linemap::unknown_location(),
701 "internal error: failed to set init priority for %s",
702 (*p
)->package_name().c_str());
705 std::sort(v
.begin(), v
.end(), priority_compare
);
707 // We build calls to the init functions, which take no arguments.
708 std::vector
<Bexpression
*> empty_args
;
709 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
713 const Import_init
* ii
= *p
;
714 std::string user_name
= ii
->package_name() + ".init";
715 const std::string
& init_name(ii
->init_name());
716 const unsigned int flags
=
717 (Backend::function_is_visible
718 | Backend::function_is_declaration
719 | Backend::function_is_inlinable
);
720 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
722 Bexpression
* pfunc_code
=
723 this->backend()->function_code_expression(pfunc
, unknown_loc
);
724 Bexpression
* pfunc_call
=
725 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
727 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
732 // Register global variables with the garbage collector. We need to
733 // register all variables which can hold a pointer value. They become
734 // roots during the mark phase. We build a struct that is easy to
735 // hook into a list of roots.
737 // type gcRoot struct {
738 // decl unsafe.Pointer // Pointer to variable.
739 // size uintptr // Total size of variable.
740 // ptrdata uintptr // Length of variable's gcdata.
741 // gcdata *byte // Pointer mask.
744 // type gcRootList struct {
750 // The last entry in the roots array has a NULL decl field.
753 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
754 std::vector
<Bstatement
*>& init_stmts
,
757 if (var_gc
.empty() && this->gc_roots_
.empty())
760 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
761 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
762 Type
* byte_type
= Type::lookup_integer_type("byte");
763 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
764 Struct_type
* root_type
=
765 Type::make_builtin_struct_type(4,
767 "size", uintptr_type
,
768 "ptrdata", uintptr_type
,
769 "gcdata", pointer_byte_type
);
771 Location builtin_loc
= Linemap::predeclared_location();
772 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
773 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
775 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
776 root_array_type
->set_is_array_incomparable();
778 Type
* int_type
= Type::lookup_integer_type("int");
779 Struct_type
* root_list_type
=
780 Type::make_builtin_struct_type(3,
783 "roots", root_array_type
);
785 // Build an initializer for the roots array.
787 Expression_list
* roots_init
= new Expression_list();
789 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
793 Expression_list
* init
= new Expression_list();
795 Location no_loc
= (*p
)->location();
796 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
797 Expression
* decl_addr
=
798 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
799 decl_addr
->unary_expression()->set_does_not_escape();
800 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
801 init
->push_back(decl_addr
);
804 Expression::make_type_info(decl
->type(),
805 Expression::TYPE_INFO_SIZE
);
806 init
->push_back(size
);
808 Expression
* ptrdata
=
809 Expression::make_type_info(decl
->type(),
810 Expression::TYPE_INFO_BACKEND_PTRDATA
);
811 init
->push_back(ptrdata
);
813 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
814 init
->push_back(gcdata
);
816 Expression
* root_ctor
=
817 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
818 roots_init
->push_back(root_ctor
);
821 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
822 p
!= this->gc_roots_
.end();
825 Expression_list
*init
= new Expression_list();
827 Expression
* expr
= *p
;
828 Location eloc
= expr
->location();
829 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
831 Type
* type
= expr
->type()->points_to();
832 go_assert(type
!= NULL
);
835 Expression::make_type_info(type
,
836 Expression::TYPE_INFO_SIZE
);
837 init
->push_back(size
);
839 Expression
* ptrdata
=
840 Expression::make_type_info(type
,
841 Expression::TYPE_INFO_BACKEND_PTRDATA
);
842 init
->push_back(ptrdata
);
844 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
845 init
->push_back(gcdata
);
847 Expression
* root_ctor
=
848 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
849 roots_init
->push_back(root_ctor
);
852 // Build a constructor for the struct.
854 Expression_list
* root_list_init
= new Expression_list();
855 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
856 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
859 Expression
* roots_ctor
=
860 Expression::make_array_composite_literal(root_array_type
, roots_init
,
862 root_list_init
->push_back(roots_ctor
);
864 Expression
* root_list_ctor
=
865 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
868 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
870 root_addr
->unary_expression()->set_is_gc_root();
871 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
872 builtin_loc
, 1, root_addr
);
874 Translate_context
context(this, NULL
, NULL
, NULL
);
875 Bexpression
* bcall
= register_roots
->get_backend(&context
);
876 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
879 // Build the list of type descriptors defined in this package. This is to help
880 // the reflect package to find compiler-generated types.
882 // type typeDescriptorList struct {
884 // types [...]unsafe.Pointer
888 type_descriptor_list_type(unsigned long len
)
890 Location builtin_loc
= Linemap::predeclared_location();
891 Type
* int_type
= Type::lookup_integer_type("int");
892 Type
* ptr_type
= Type::make_pointer_type(Type::make_void_type());
893 // Avoid creating zero-length type.
894 unsigned long nelems
= (len
!= 0 ? len
: 1);
895 Expression
* len_expr
= Expression::make_integer_ul(nelems
, NULL
,
897 Array_type
* array_type
= Type::make_array_type(ptr_type
, len_expr
);
898 array_type
->set_is_array_incomparable();
899 Struct_type
* list_type
=
900 Type::make_builtin_struct_type(2, "count", int_type
,
901 "types", array_type
);
906 Gogo::build_type_descriptor_list()
908 // Create the list type
909 Location builtin_loc
= Linemap::predeclared_location();
910 unsigned long len
= this->type_descriptors_
.size();
911 Struct_type
* list_type
= type_descriptor_list_type(len
);
912 Btype
* bt
= list_type
->get_backend(this);
913 Btype
* bat
= list_type
->field(1)->type()->get_backend(this);
915 // Create the variable
916 std::string name
= this->type_descriptor_list_symbol(this->pkgpath_symbol());
917 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bt
,
921 // Build the initializer
922 std::vector
<unsigned long> indexes
;
923 std::vector
<Bexpression
*> vals
;
924 std::vector
<Type
*>::iterator p
= this->type_descriptors_
.begin();
925 for (unsigned long i
= 0; i
< len
; ++i
, ++p
)
927 Bexpression
* bexpr
= (*p
)->type_descriptor_pointer(this,
929 indexes
.push_back(i
);
930 vals
.push_back(bexpr
);
932 Bexpression
* barray
=
933 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
936 Translate_context
context(this, NULL
, NULL
, NULL
);
937 std::vector
<Bexpression
*> fields
;
938 Expression
* len_expr
= Expression::make_integer_ul(len
, NULL
,
940 fields
.push_back(len_expr
->get_backend(&context
));
941 fields
.push_back(barray
);
943 this->backend()->constructor_expression(bt
, fields
, builtin_loc
);
945 this->backend()->implicit_variable_set_init(bv
, name
, bt
, false,
949 // Register the type descriptors with the runtime. This is to help
950 // the reflect package to find compiler-generated types.
953 Gogo::register_type_descriptors(std::vector
<Bstatement
*>& init_stmts
,
956 // Create the list type
957 Location builtin_loc
= Linemap::predeclared_location();
958 Struct_type
* list_type
= type_descriptor_list_type(1);
959 Btype
* bt
= list_type
->get_backend(this);
961 // Collect type lists from transitive imports.
962 std::vector
<std::string
> list_names
;
963 for (Import_init_set::iterator it
= this->imported_init_fns_
.begin();
964 it
!= this->imported_init_fns_
.end();
967 std::string pkgpath_symbol
=
968 this->pkgpath_symbol_from_init_fn_name((*it
)->init_name());
969 list_names
.push_back(this->type_descriptor_list_symbol(pkgpath_symbol
));
971 // Add the main package itself.
972 list_names
.push_back(this->type_descriptor_list_symbol("main"));
974 // Build a list of lists.
975 std::vector
<unsigned long> indexes
;
976 std::vector
<Bexpression
*> vals
;
978 for (std::vector
<std::string
>::iterator p
= list_names
.begin();
979 p
!= list_names
.end();
983 this->backend()->implicit_variable_reference(*p
, *p
, bt
);
984 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
985 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
987 indexes
.push_back(i
);
988 vals
.push_back(bexpr
);
991 Expression
* len_expr
= Expression::make_integer_ul(i
, NULL
, builtin_loc
);
992 Type
* list_ptr_type
= Type::make_pointer_type(list_type
);
993 Type
* list_array_type
= Type::make_array_type(list_ptr_type
, len_expr
);
994 Btype
* bat
= list_array_type
->get_backend(this);
995 Bexpression
* barray
=
996 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
999 // Create a variable holding the list.
1000 std::string name
= this->typelists_symbol();
1001 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bat
,
1004 this->backend()->implicit_variable_set_init(bv
, name
, bat
, true, true,
1007 // Build the call in main package's init function.
1008 Translate_context
context(this, NULL
, NULL
, NULL
);
1009 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1010 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1011 Type
* array_ptr_type
= Type::make_pointer_type(list_array_type
);
1012 Expression
* expr
= Expression::make_backend(bexpr
, array_ptr_type
,
1014 expr
= Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS
,
1015 builtin_loc
, 2, len_expr
->copy(), expr
);
1016 Bexpression
* bcall
= expr
->get_backend(&context
);
1017 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
,
1021 // Build the decl for the initialization function.
1024 Gogo::initialization_function_decl()
1026 std::string name
= this->get_init_fn_name();
1027 Location loc
= this->package_
->location();
1029 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
1030 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
1031 return Named_object::make_function(name
, NULL
, initfn
);
1034 // Create the magic initialization function. CODE_STMT is the
1035 // code that it needs to run.
1038 Gogo::create_initialization_function(Named_object
* initfn
,
1039 Bstatement
* code_stmt
)
1041 // Make sure that we thought we needed an initialization function,
1042 // as otherwise we will not have reported it in the export data.
1043 go_assert(this->is_main_package() || this->need_init_fn_
);
1046 initfn
= this->initialization_function_decl();
1048 // Bind the initialization function code to a block.
1049 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
1050 Location pkg_loc
= this->package_
->location();
1051 std::vector
<Bvariable
*> vars
;
1052 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
1054 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
1056 go_assert(saw_errors());
1062 // Given an expression, collect all the global variables defined in
1063 // this package that it references.
1065 class Find_vars
: public Traverse
1068 // The list of variables we accumulate.
1069 typedef Unordered_set(Named_object
*) Vars
;
1071 // A hash table we use to avoid looping. The index is a
1072 // Named_object* or a Temporary_statement*. We only look through
1073 // objects defined in this package.
1074 typedef Unordered_set(const void*) Seen_objects
;
1078 : Traverse(traverse_expressions
),
1079 vars_(), seen_objects_()
1082 // An iterator through the variables found, after the traversal.
1083 typedef Vars::const_iterator const_iterator
;
1087 { return this->vars_
.begin(); }
1091 { return this->vars_
.end(); }
1094 expression(Expression
**);
1097 // Accumulated variables.
1099 // Objects we have already seen.
1100 Seen_objects seen_objects_
;
1103 // Collect global variables referenced by EXPR. Look through function
1104 // calls and variable initializations.
1107 Find_vars::expression(Expression
** pexpr
)
1109 Expression
* e
= *pexpr
;
1111 Var_expression
* ve
= e
->var_expression();
1114 Named_object
* v
= ve
->named_object();
1115 if (!v
->is_variable() || v
->package() != NULL
)
1117 // This is a result parameter or a variable defined in a
1118 // different package. Either way we don't care about it.
1119 return TRAVERSE_CONTINUE
;
1122 std::pair
<Seen_objects::iterator
, bool> ins
=
1123 this->seen_objects_
.insert(v
);
1126 // We've seen this variable before.
1127 return TRAVERSE_CONTINUE
;
1130 if (v
->var_value()->is_global())
1131 this->vars_
.insert(v
);
1133 Expression
* init
= v
->var_value()->init();
1136 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1137 return TRAVERSE_EXIT
;
1141 // We traverse the code of any function or bound method we see. Note that
1142 // this means that we will traverse the code of a function or bound method
1143 // whose address is taken even if it is not called.
1144 Func_expression
* fe
= e
->func_expression();
1145 Bound_method_expression
* bme
= e
->bound_method_expression();
1146 if (fe
!= NULL
|| bme
!= NULL
)
1148 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1149 if (f
->is_function() && f
->package() == NULL
)
1151 std::pair
<Seen_objects::iterator
, bool> ins
=
1152 this->seen_objects_
.insert(f
);
1155 // This is the first time we have seen this name.
1156 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1157 return TRAVERSE_EXIT
;
1162 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1165 Temporary_statement
* ts
= tre
->statement();
1166 Expression
* init
= ts
->init();
1169 std::pair
<Seen_objects::iterator
, bool> ins
=
1170 this->seen_objects_
.insert(ts
);
1173 // This is the first time we have seen this temporary
1175 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1176 return TRAVERSE_EXIT
;
1181 return TRAVERSE_CONTINUE
;
1184 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1187 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1190 Find_vars find_vars
;
1192 Expression::traverse(&expr
, &find_vars
);
1193 if (preinit
!= NULL
)
1194 preinit
->traverse(&find_vars
);
1197 Expression
* init
= dep
->var_value()->init();
1199 Expression::traverse(&init
, &find_vars
);
1200 if (dep
->var_value()->has_pre_init())
1201 dep
->var_value()->preinit()->traverse(&find_vars
);
1204 for (Find_vars::const_iterator p
= find_vars
.begin();
1205 p
!= find_vars
.end();
1214 // Sort variable initializations. If the initialization expression
1215 // for variable A refers directly or indirectly to the initialization
1216 // expression for variable B, then we must initialize B before A.
1222 : var_(NULL
), init_(NULL
), refs_(NULL
), dep_count_(0)
1225 Var_init(Named_object
* var
, Bstatement
* init
)
1226 : var_(var
), init_(init
), refs_(NULL
), dep_count_(0)
1229 // Return the variable.
1232 { return this->var_
; }
1234 // Return the initialization expression.
1237 { return this->init_
; }
1241 add_ref(Named_object
* var
);
1243 // The variables which this variable's initializers refer to.
1244 const std::vector
<Named_object
*>*
1246 { return this->refs_
; }
1248 // Clear the references, if any.
1252 // Return the number of remaining dependencies.
1255 { return this->dep_count_
; }
1257 // Increment the number of dependencies.
1260 { ++this->dep_count_
; }
1262 // Decrement the number of dependencies.
1265 { --this->dep_count_
; }
1268 // The variable being initialized.
1270 // The backend initialization statement.
1272 // Variables this refers to.
1273 std::vector
<Named_object
*>* refs_
;
1274 // The number of initializations this is dependent on. A variable
1275 // initialization should not be emitted if any of its dependencies
1276 // have not yet been resolved.
1283 Var_init::add_ref(Named_object
* var
)
1285 if (this->refs_
== NULL
)
1286 this->refs_
= new std::vector
<Named_object
*>;
1287 this->refs_
->push_back(var
);
1290 // Clear the references, if any.
1293 Var_init::clear_refs()
1295 if (this->refs_
!= NULL
)
1302 // For comparing Var_init keys in a map.
1305 operator<(const Var_init
& v1
, const Var_init
& v2
)
1306 { return v1
.var()->name() < v2
.var()->name(); }
1308 typedef std::list
<Var_init
> Var_inits
;
1310 // Sort the variable initializations. The rule we follow is that we
1311 // emit them in the order they appear in the array, except that if the
1312 // initialization expression for a variable V1 depends upon another
1313 // variable V2 then we initialize V1 after V2.
1316 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1318 if (var_inits
->empty())
1321 std::map
<Named_object
*, Var_init
*> var_to_init
;
1323 // A mapping from a variable initialization to a set of
1324 // variable initializations that depend on it.
1325 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1326 Init_deps init_deps
;
1327 bool init_loop
= false;
1329 // Compute all variable references.
1330 for (Var_inits::iterator pvar
= var_inits
->begin();
1331 pvar
!= var_inits
->end();
1334 Named_object
* var
= pvar
->var();
1335 var_to_init
[var
] = &*pvar
;
1337 Find_vars find_vars
;
1338 Expression
* init
= var
->var_value()->init();
1340 Expression::traverse(&init
, &find_vars
);
1341 if (var
->var_value()->has_pre_init())
1342 var
->var_value()->preinit()->traverse(&find_vars
);
1343 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1346 Expression
* dinit
= dep
->var_value()->init();
1348 Expression::traverse(&dinit
, &find_vars
);
1349 if (dep
->var_value()->has_pre_init())
1350 dep
->var_value()->preinit()->traverse(&find_vars
);
1352 for (Find_vars::const_iterator p
= find_vars
.begin();
1353 p
!= find_vars
.end();
1358 // Add dependencies to init_deps, and check for cycles.
1359 for (Var_inits::iterator pvar
= var_inits
->begin();
1360 pvar
!= var_inits
->end();
1363 Named_object
* var
= pvar
->var();
1365 const std::vector
<Named_object
*>* refs
= pvar
->refs();
1368 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1369 pdep
!= refs
->end();
1372 Named_object
* dep
= *pdep
;
1375 // This is a reference from a variable to itself, which
1376 // may indicate a loop. We only report an error if
1377 // there is an initializer and there is no dependency.
1378 // When there is no initializer, it means that the
1379 // preinitializer sets the variable, which will appear
1380 // to be a loop here.
1381 if (var
->var_value()->init() != NULL
1382 && gogo
->var_depends_on(var
->var_value()) == NULL
)
1383 go_error_at(var
->location(),
1384 ("initialization expression for %qs "
1385 "depends upon itself"),
1386 var
->message_name().c_str());
1391 Var_init
* dep_init
= var_to_init
[dep
];
1392 if (dep_init
== NULL
)
1394 // This is a dependency on some variable that doesn't
1395 // have an initializer, so for purposes of
1396 // initialization ordering this is irrelevant.
1400 init_deps
[*dep_init
].insert(&(*pvar
));
1401 pvar
->add_dependency();
1403 // Check for cycles.
1404 const std::vector
<Named_object
*>* deprefs
= dep_init
->refs();
1405 if (deprefs
== NULL
)
1407 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1409 pdepdep
!= deprefs
->end();
1412 if (*pdepdep
== var
)
1414 go_error_at(var
->location(),
1415 ("initialization expressions for %qs and "
1416 "%qs depend upon each other"),
1417 var
->message_name().c_str(),
1418 dep
->message_name().c_str());
1419 go_inform(dep
->location(), "%qs defined here",
1420 dep
->message_name().c_str());
1428 var_to_init
.clear();
1429 for (Var_inits::iterator pvar
= var_inits
->begin();
1430 pvar
!= var_inits
->end();
1434 // If there are no dependencies then the declaration order is sorted.
1435 if (!init_deps
.empty() && !init_loop
)
1437 // Otherwise, sort variable initializations by emitting all variables with
1438 // no dependencies in declaration order. VAR_INITS is already in
1439 // declaration order.
1441 while (!var_inits
->empty())
1443 Var_inits::iterator v1
;;
1444 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1446 if (v1
->dep_count() == 0)
1449 go_assert(v1
!= var_inits
->end());
1451 // V1 either has no dependencies or its dependencies have already
1452 // been emitted, add it to READY next. When V1 is emitted, remove
1453 // a dependency from each V that depends on V1.
1454 ready
.splice(ready
.end(), *var_inits
, v1
);
1456 Init_deps::iterator p1
= init_deps
.find(*v1
);
1457 if (p1
!= init_deps
.end())
1459 std::set
<Var_init
*> resolved
= p1
->second
;
1460 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1461 pv
!= resolved
.end();
1463 (*pv
)->remove_dependency();
1464 init_deps
.erase(p1
);
1467 var_inits
->swap(ready
);
1468 go_assert(init_deps
.empty());
1472 // Give an error if the initialization expression for VAR depends on
1473 // itself. We only check if INIT is not NULL and there is no
1474 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1475 // which we will interpret as a loop.
1478 Gogo::check_self_dep(Named_object
* var
)
1480 Expression
* init
= var
->var_value()->init();
1481 Block
* preinit
= var
->var_value()->preinit();
1482 Named_object
* dep
= this->var_depends_on(var
->var_value());
1485 && expression_requires(init
, preinit
, NULL
, var
))
1486 go_error_at(var
->location(),
1487 "initialization expression for %qs depends upon itself",
1488 var
->message_name().c_str());
1491 // Write out the global definitions.
1494 Gogo::write_globals()
1496 this->build_interface_method_tables();
1498 Bindings
* bindings
= this->current_bindings();
1500 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1501 p
!= bindings
->end_declarations();
1504 // If any function declarations needed a descriptor, make sure
1506 Named_object
* no
= p
->second
;
1507 if (no
->is_function_declaration())
1508 no
->func_declaration_value()->build_backend_descriptor(this);
1511 // Lists of globally declared types, variables, constants, and functions
1512 // that must be defined.
1513 std::vector
<Btype
*> type_decls
;
1514 std::vector
<Bvariable
*> var_decls
;
1515 std::vector
<Bexpression
*> const_decls
;
1516 std::vector
<Bfunction
*> func_decls
;
1518 // The init function declaration and associated Bfunction, if necessary.
1519 Named_object
* init_fndecl
= NULL
;
1520 Bfunction
* init_bfn
= NULL
;
1522 std::vector
<Bstatement
*> init_stmts
;
1523 std::vector
<Bstatement
*> var_init_stmts
;
1525 if (this->is_main_package())
1527 init_fndecl
= this->initialization_function_decl();
1528 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1531 // A list of variable initializations.
1532 Var_inits var_inits
;
1534 // A list of variables which need to be registered with the garbage
1536 size_t count_definitions
= bindings
->size_definitions();
1537 std::vector
<Named_object
*> var_gc
;
1538 var_gc
.reserve(count_definitions
);
1540 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1541 p
!= bindings
->end_definitions();
1544 Named_object
* no
= *p
;
1545 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1547 // There is nothing to do for a package.
1548 if (no
->is_package())
1551 // There is nothing to do for an object which was imported from
1552 // a different package into the global scope.
1553 if (no
->package() != NULL
)
1556 // Skip blank named functions and constants.
1557 if ((no
->is_function() && no
->func_value()->is_sink())
1558 || (no
->is_const() && no
->const_value()->is_sink()))
1561 // Skip global sink variables with static initializers. With
1562 // non-static initializers we have to evaluate for side effects,
1563 // and we wind up initializing a dummy variable. That is not
1564 // ideal but it works and it's a rare case.
1565 if (no
->is_variable()
1566 && no
->var_value()->is_global_sink()
1567 && !no
->var_value()->has_pre_init()
1568 && (no
->var_value()->init() == NULL
1569 || no
->var_value()->init()->is_static_initializer()))
1572 // There is nothing useful we can output for constants which
1573 // have ideal or non-integral type.
1576 Type
* type
= no
->const_value()->type();
1578 type
= no
->const_value()->expr()->type();
1579 if (type
->is_abstract() || !type
->is_numeric_type())
1583 if (!no
->is_variable())
1584 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1587 Variable
* var
= no
->var_value();
1588 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1589 var_decls
.push_back(bvar
);
1591 // Check for a sink variable, which may be used to run an
1592 // initializer purely for its side effects.
1593 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1595 Bstatement
* var_init_stmt
= NULL
;
1596 if (!var
->has_pre_init())
1598 // If the backend representation of the variable initializer is
1599 // constant, we can just set the initial value using
1600 // global_var_set_init instead of during the init() function.
1601 // The initializer is constant if it is the zero-value of the
1602 // variable's type or if the initial value is an immutable value
1603 // that is not copied to the heap.
1604 Expression
* init
= var
->init();
1606 // If we see "a = b; b = x", and x is a static
1607 // initializer, just set a to x.
1608 while (init
!= NULL
&& init
->var_expression() != NULL
)
1610 Named_object
* ino
= init
->var_expression()->named_object();
1611 if (!ino
->is_variable() || ino
->package() != NULL
)
1613 Expression
* ino_init
= ino
->var_value()->init();
1614 if (ino
->var_value()->has_pre_init()
1616 || !ino_init
->is_static_initializer())
1621 bool is_static_initializer
;
1623 is_static_initializer
= true;
1626 Type
* var_type
= var
->type();
1627 init
= Expression::make_cast(var_type
, init
, var
->location());
1628 is_static_initializer
= init
->is_static_initializer();
1631 // Non-constant variable initializations might need to create
1632 // temporary variables, which will need the initialization
1633 // function as context.
1634 Named_object
* var_init_fn
;
1635 if (is_static_initializer
)
1639 if (init_fndecl
== NULL
)
1641 init_fndecl
= this->initialization_function_decl();
1642 Function
* func
= init_fndecl
->func_value();
1643 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1645 var_init_fn
= init_fndecl
;
1648 Bexpression
* var_binit
;
1653 Translate_context
context(this, var_init_fn
, NULL
, NULL
);
1654 var_binit
= init
->get_backend(&context
);
1657 if (var_binit
== NULL
)
1659 else if (is_static_initializer
)
1661 if (expression_requires(var
->init(), NULL
,
1662 this->var_depends_on(var
), no
))
1663 go_error_at(no
->location(),
1664 "initialization expression for %qs depends "
1666 no
->message_name().c_str());
1667 this->backend()->global_variable_set_init(bvar
, var_binit
);
1671 this->backend()->expression_statement(init_bfn
, var_binit
);
1674 Location loc
= var
->location();
1675 Bexpression
* var_expr
=
1676 this->backend()->var_expression(bvar
, loc
);
1678 this->backend()->assignment_statement(init_bfn
, var_expr
,
1684 // We are going to create temporary variables which
1685 // means that we need an fndecl.
1686 if (init_fndecl
== NULL
)
1687 init_fndecl
= this->initialization_function_decl();
1689 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1690 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1693 if (var_init_stmt
!= NULL
)
1695 if (var
->init() == NULL
&& !var
->has_pre_init())
1696 var_init_stmts
.push_back(var_init_stmt
);
1698 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1700 else if (this->var_depends_on(var
) != NULL
)
1702 // This variable is initialized from something that is
1703 // not in its init or preinit. This variable needs to
1704 // participate in dependency analysis sorting, in case
1705 // some other variable depends on this one.
1706 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1707 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1708 Bstatement
* zero_stmt
=
1709 this->backend()->expression_statement(init_bfn
, zero
);
1710 var_inits
.push_back(Var_init(no
, zero_stmt
));
1713 // Collect a list of all global variables with pointers,
1714 // to register them for the garbage collector.
1715 if (!is_sink
&& var
->type()->has_pointer())
1717 // Avoid putting runtime.gcRoots itself on the list.
1718 if (this->compiling_runtime()
1719 && this->package_name() == "runtime"
1720 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1721 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1724 var_gc
.push_back(no
);
1729 // Output inline functions, which are in different packages.
1730 for (std::vector
<Named_object
*>::const_iterator p
=
1731 this->imported_inline_functions_
.begin();
1732 p
!= this->imported_inline_functions_
.end();
1734 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1736 // Build the list of type descriptors.
1737 this->build_type_descriptor_list();
1739 if (this->is_main_package())
1741 // Register the type descriptor lists, so that at run time
1742 // the reflect package can find compiler-created types, and
1743 // deduplicate if the same type is created with reflection.
1744 // This needs to be done before calling any package's init
1745 // function, as it may create type through reflection.
1746 this->register_type_descriptors(init_stmts
, init_bfn
);
1748 // Initialize imported packages.
1749 this->init_imports(init_stmts
, init_bfn
);
1752 // Register global variables with the garbage collector.
1753 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1755 // Simple variable initializations, after all variables are
1757 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1759 // Complete variable initializations, first sorting them into a
1761 if (!var_inits
.empty())
1763 sort_var_inits(this, &var_inits
);
1764 for (Var_inits::const_iterator p
= var_inits
.begin();
1765 p
!= var_inits
.end();
1767 init_stmts
.push_back(p
->init());
1770 // After all the variables are initialized, call the init
1771 // functions if there are any. Init functions take no arguments, so
1772 // we pass in EMPTY_ARGS to call them.
1773 std::vector
<Bexpression
*> empty_args
;
1774 for (std::vector
<Named_object
*>::const_iterator p
=
1775 this->init_functions_
.begin();
1776 p
!= this->init_functions_
.end();
1779 Location func_loc
= (*p
)->location();
1780 Function
* func
= (*p
)->func_value();
1781 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1782 Bexpression
* func_code
=
1783 this->backend()->function_code_expression(initfn
, func_loc
);
1784 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1787 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1788 init_stmts
.push_back(ist
);
1791 // Set up a magic function to do all the initialization actions.
1792 // This will be called if this package is imported.
1793 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1794 if (this->need_init_fn_
|| this->is_main_package())
1797 this->create_initialization_function(init_fndecl
, init_fncode
);
1798 if (init_fndecl
!= NULL
)
1799 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1802 // We should not have seen any new bindings created during the conversion.
1803 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1805 // Define all globally declared values.
1807 this->backend()->write_global_definitions(type_decls
, const_decls
,
1808 func_decls
, var_decls
);
1811 // Return the current block.
1814 Gogo::current_block()
1816 if (this->functions_
.empty())
1819 return this->functions_
.back().blocks
.back();
1822 // Look up a name in the current binding contour. If PFUNCTION is not
1823 // NULL, set it to the function in which the name is defined, or NULL
1824 // if the name is defined in global scope.
1827 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1829 if (pfunction
!= NULL
)
1832 if (Gogo::is_sink_name(name
))
1833 return Named_object::make_sink();
1835 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1836 p
!= this->functions_
.rend();
1839 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1842 if (pfunction
!= NULL
)
1843 *pfunction
= p
->function
;
1848 if (this->package_
!= NULL
)
1850 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1853 if (ret
->package() != NULL
)
1855 std::string dot_alias
= "." + ret
->package()->package_name();
1856 ret
->package()->note_usage(dot_alias
);
1862 // We do not look in the global namespace. If we did, the global
1863 // namespace would effectively hide names which were defined in
1864 // package scope which we have not yet seen. Instead,
1865 // define_global_names is called after parsing is over to connect
1866 // undefined names at package scope with names defined at global
1872 // Look up a name in the current block, without searching enclosing
1876 Gogo::lookup_in_block(const std::string
& name
) const
1878 go_assert(!this->functions_
.empty());
1879 go_assert(!this->functions_
.back().blocks
.empty());
1880 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1883 // Look up a name in the global namespace.
1886 Gogo::lookup_global(const char* name
) const
1888 return this->globals_
->lookup(name
);
1891 // Add an imported package.
1894 Gogo::add_imported_package(const std::string
& real_name
,
1895 const std::string
& alias_arg
,
1896 bool is_alias_exported
,
1897 const std::string
& pkgpath
,
1898 const std::string
& pkgpath_symbol
,
1900 bool* padd_to_globals
)
1902 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1903 ret
->set_package_name(real_name
, location
);
1905 *padd_to_globals
= false;
1907 if (alias_arg
== "_")
1909 else if (alias_arg
== ".")
1911 *padd_to_globals
= true;
1912 std::string dot_alias
= "." + real_name
;
1913 ret
->add_alias(dot_alias
, location
);
1917 std::string alias
= alias_arg
;
1921 is_alias_exported
= Lex::is_exported_name(alias
);
1923 ret
->add_alias(alias
, location
);
1924 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1925 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1926 if (!no
->is_package())
1933 // Register a package. This package may or may not be imported. This
1934 // returns the Package structure for the package, creating if it
1935 // necessary. LOCATION is the location of the import statement that
1936 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1937 // for names in the package; it may be the empty string, in which case
1938 // we either get it later or make a guess when we need it.
1941 Gogo::register_package(const std::string
& pkgpath
,
1942 const std::string
& pkgpath_symbol
, Location location
)
1944 Package
* package
= NULL
;
1945 std::pair
<Packages::iterator
, bool> ins
=
1946 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1949 // We have seen this package name before.
1950 package
= ins
.first
->second
;
1951 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1952 if (!pkgpath_symbol
.empty())
1953 package
->set_pkgpath_symbol(pkgpath_symbol
);
1954 if (Linemap::is_unknown_location(package
->location()))
1955 package
->set_location(location
);
1959 // First time we have seen this package name.
1960 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1961 go_assert(ins
.first
->second
== NULL
);
1962 ins
.first
->second
= package
;
1968 // Return the pkgpath symbol for a package, given the pkgpath.
1971 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1973 Packages::iterator p
= this->packages_
.find(pkgpath
);
1974 go_assert(p
!= this->packages_
.end());
1975 return p
->second
->pkgpath_symbol();
1978 // Start compiling a function.
1981 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1982 bool add_method_to_type
, Location location
)
1984 bool at_top_level
= this->functions_
.empty();
1986 Block
* block
= new Block(NULL
, location
);
1988 Named_object
* enclosing
= (at_top_level
1990 : this->functions_
.back().function
);
1992 Function
* function
= new Function(type
, enclosing
, block
, location
);
1994 if (type
->is_method())
1996 const Typed_identifier
* receiver
= type
->receiver();
1997 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1998 true, true, location
);
1999 std::string rname
= receiver
->name();
2000 unsigned rcounter
= 0;
2002 // We need to give a nameless receiver parameter a synthesized name to
2003 // avoid having it clash with some other nameless param. FIXME.
2004 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
2006 block
->bindings()->add_variable(rname
, NULL
, this_param
);
2009 const Typed_identifier_list
* parameters
= type
->parameters();
2010 bool is_varargs
= type
->is_varargs();
2011 unsigned pcounter
= 0;
2012 if (parameters
!= NULL
)
2014 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
2015 p
!= parameters
->end();
2018 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
2020 if (is_varargs
&& p
+ 1 == parameters
->end())
2021 param
->set_is_varargs_parameter();
2023 std::string pname
= p
->name();
2025 // We need to give each nameless parameter a non-empty name to avoid
2026 // having it clash with some other nameless param. FIXME.
2027 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
2029 block
->bindings()->add_variable(pname
, NULL
, param
);
2033 function
->create_result_variables(this);
2035 const std::string
* pname
;
2036 std::string nested_name
;
2037 bool is_init
= false;
2038 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
2040 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
2041 || (type
->results() != NULL
&& !type
->results()->empty()))
2042 go_error_at(location
,
2043 "func init must have no arguments and no return values");
2044 // There can be multiple "init" functions, so give them each a
2046 nested_name
= this->init_function_name();
2047 pname
= &nested_name
;
2050 else if (!name
.empty())
2054 // Invent a name for a nested function.
2055 nested_name
= this->nested_function_name(enclosing
);
2056 pname
= &nested_name
;
2060 if (Gogo::is_sink_name(*pname
))
2062 std::string
sname(this->sink_function_name());
2063 ret
= Named_object::make_function(sname
, NULL
, function
);
2064 ret
->func_value()->set_is_sink();
2066 if (!type
->is_method())
2067 ret
= this->package_
->bindings()->add_named_object(ret
);
2068 else if (add_method_to_type
)
2070 // We should report errors even for sink methods.
2071 Type
* rtype
= type
->receiver()->type();
2072 // Avoid points_to and deref to avoid getting an error if
2073 // the type is not yet defined.
2074 if (rtype
->classification() == Type::TYPE_POINTER
)
2075 rtype
= rtype
->points_to();
2076 while (rtype
->named_type() != NULL
2077 && rtype
->named_type()->is_alias())
2078 rtype
= rtype
->named_type()->real_type()->forwarded();
2079 if (rtype
->is_error_type())
2081 else if (rtype
->named_type() != NULL
)
2083 if (rtype
->named_type()->named_object()->package() != NULL
)
2084 go_error_at(type
->receiver()->location(),
2085 "may not define methods on non-local type");
2087 else if (rtype
->forward_declaration_type() != NULL
)
2089 // Go ahead and add the method in case we need to report
2090 // an error when we see the definition.
2091 rtype
->forward_declaration_type()->add_existing_method(ret
);
2094 go_error_at(type
->receiver()->location(),
2095 ("invalid receiver type "
2096 "(receiver must be a named type)"));
2099 else if (!type
->is_method())
2101 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
2102 if (!ret
->is_function() || ret
->func_value() != function
)
2104 // Redefinition error. Invent a name to avoid knockon
2106 std::string
rname(this->redefined_function_name());
2107 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
2112 if (!add_method_to_type
)
2113 ret
= Named_object::make_function(name
, NULL
, function
);
2116 go_assert(at_top_level
);
2117 Type
* rtype
= type
->receiver()->type();
2119 while (rtype
->named_type() != NULL
2120 && rtype
->named_type()->is_alias())
2121 rtype
= rtype
->named_type()->real_type()->forwarded();
2123 // We want to look through the pointer created by the
2124 // parser, without getting an error if the type is not yet
2126 if (rtype
->classification() == Type::TYPE_POINTER
)
2127 rtype
= rtype
->points_to();
2129 while (rtype
->named_type() != NULL
2130 && rtype
->named_type()->is_alias())
2131 rtype
= rtype
->named_type()->real_type()->forwarded();
2133 if (rtype
->is_error_type())
2134 ret
= Named_object::make_function(name
, NULL
, function
);
2135 else if (rtype
->named_type() != NULL
)
2137 if (rtype
->named_type()->named_object()->package() != NULL
)
2139 go_error_at(type
->receiver()->location(),
2140 "may not define methods on non-local type");
2141 ret
= Named_object::make_function(name
, NULL
, function
);
2145 ret
= rtype
->named_type()->add_method(name
, function
);
2146 if (!ret
->is_function())
2148 // Redefinition error.
2149 ret
= Named_object::make_function(name
, NULL
, function
);
2153 else if (rtype
->forward_declaration_type() != NULL
)
2155 Named_object
* type_no
=
2156 rtype
->forward_declaration_type()->named_object();
2157 if (type_no
->is_unknown())
2159 // If we are seeing methods it really must be a
2160 // type. Declare it as such. An alternative would
2161 // be to support lists of methods for unknown
2162 // expressions. Either way the error messages if
2163 // this is not a type are going to get confusing.
2164 Named_object
* declared
=
2165 this->declare_package_type(type_no
->name(),
2166 type_no
->location());
2168 == type_no
->unknown_value()->real_named_object());
2170 ret
= rtype
->forward_declaration_type()->add_method(name
,
2175 go_error_at(type
->receiver()->location(),
2176 ("invalid receiver type (receiver must "
2177 "be a named type)"));
2178 ret
= Named_object::make_function(name
, NULL
, function
);
2181 this->package_
->bindings()->add_method(ret
);
2184 this->functions_
.resize(this->functions_
.size() + 1);
2185 Open_function
& of(this->functions_
.back());
2187 of
.blocks
.push_back(block
);
2191 this->init_functions_
.push_back(ret
);
2192 this->need_init_fn_
= true;
2198 // Finish compiling a function.
2201 Gogo::finish_function(Location location
)
2203 this->finish_block(location
);
2204 go_assert(this->functions_
.back().blocks
.empty());
2205 this->functions_
.pop_back();
2208 // Return the current function.
2211 Gogo::current_function() const
2213 go_assert(!this->functions_
.empty());
2214 return this->functions_
.back().function
;
2217 // Start a new block.
2220 Gogo::start_block(Location location
)
2222 go_assert(!this->functions_
.empty());
2223 Block
* block
= new Block(this->current_block(), location
);
2224 this->functions_
.back().blocks
.push_back(block
);
2230 Gogo::finish_block(Location location
)
2232 go_assert(!this->functions_
.empty());
2233 go_assert(!this->functions_
.back().blocks
.empty());
2234 Block
* block
= this->functions_
.back().blocks
.back();
2235 this->functions_
.back().blocks
.pop_back();
2236 block
->set_end_location(location
);
2240 // Add an erroneous name.
2243 Gogo::add_erroneous_name(const std::string
& name
)
2245 return this->package_
->bindings()->add_erroneous_name(name
);
2248 // Add an unknown name.
2251 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2253 return this->package_
->bindings()->add_unknown_name(name
, location
);
2256 // Declare a function.
2259 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2262 if (!type
->is_method())
2263 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2267 // We don't bother to add this to the list of global
2269 Type
* rtype
= type
->receiver()->type();
2271 while (rtype
->named_type() != NULL
2272 && rtype
->named_type()->is_alias())
2273 rtype
= rtype
->named_type()->real_type()->forwarded();
2275 // We want to look through the pointer created by the
2276 // parser, without getting an error if the type is not yet
2278 if (rtype
->classification() == Type::TYPE_POINTER
)
2279 rtype
= rtype
->points_to();
2281 while (rtype
->named_type() != NULL
2282 && rtype
->named_type()->is_alias())
2283 rtype
= rtype
->named_type()->real_type()->forwarded();
2285 if (rtype
->is_error_type())
2287 else if (rtype
->named_type() != NULL
)
2288 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2290 else if (rtype
->forward_declaration_type() != NULL
)
2292 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2293 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2297 go_error_at(type
->receiver()->location(),
2298 "invalid receiver type (receiver must be a named type)");
2299 return Named_object::make_erroneous_name(name
);
2304 // Add a label definition.
2307 Gogo::add_label_definition(const std::string
& label_name
,
2310 go_assert(!this->functions_
.empty());
2311 Function
* func
= this->functions_
.back().function
->func_value();
2312 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2313 this->add_statement(Statement::make_label_statement(label
, location
));
2317 // Add a label reference.
2320 Gogo::add_label_reference(const std::string
& label_name
,
2321 Location location
, bool issue_goto_errors
)
2323 go_assert(!this->functions_
.empty());
2324 Function
* func
= this->functions_
.back().function
->func_value();
2325 return func
->add_label_reference(this, label_name
, location
,
2329 // Return the current binding state.
2332 Gogo::bindings_snapshot(Location location
)
2334 return new Bindings_snapshot(this->current_block(), location
);
2340 Gogo::add_statement(Statement
* statement
)
2342 go_assert(!this->functions_
.empty()
2343 && !this->functions_
.back().blocks
.empty());
2344 this->functions_
.back().blocks
.back()->add_statement(statement
);
2350 Gogo::add_block(Block
* block
, Location location
)
2352 go_assert(!this->functions_
.empty()
2353 && !this->functions_
.back().blocks
.empty());
2354 Statement
* statement
= Statement::make_block_statement(block
, location
);
2355 this->functions_
.back().blocks
.back()->add_statement(statement
);
2361 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2364 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2370 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2372 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2374 if (!this->in_global_scope() && no
->is_type())
2376 Named_object
* f
= this->functions_
.back().function
;
2378 if (f
->is_function())
2379 index
= f
->func_value()->new_local_type_index();
2382 no
->type_value()->set_in_function(f
, index
);
2386 // Add a named type.
2389 Gogo::add_named_type(Named_type
* type
)
2391 go_assert(this->in_global_scope());
2392 this->current_bindings()->add_named_type(type
);
2398 Gogo::declare_type(const std::string
& name
, Location location
)
2400 Bindings
* bindings
= this->current_bindings();
2401 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2402 if (!this->in_global_scope() && no
->is_type_declaration())
2404 Named_object
* f
= this->functions_
.back().function
;
2406 if (f
->is_function())
2407 index
= f
->func_value()->new_local_type_index();
2410 no
->type_declaration_value()->set_in_function(f
, index
);
2415 // Declare a type at the package level.
2418 Gogo::declare_package_type(const std::string
& name
, Location location
)
2420 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2423 // Declare a function at the package level.
2426 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2429 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2433 // Add a function declaration to the list of functions we may want to
2437 Gogo::add_imported_inlinable_function(Named_object
* no
)
2439 go_assert(no
->is_function_declaration());
2440 Function_declaration
* fd
= no
->func_declaration_value();
2441 if (fd
->is_on_inlinable_list())
2443 this->imported_inlinable_functions_
.push_back(no
);
2444 fd
->set_is_on_inlinable_list();
2447 // Define a type which was already declared.
2450 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2452 this->current_bindings()->define_type(no
, type
);
2458 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2460 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2463 // In a function the middle-end wants to see a DECL_EXPR node.
2465 && no
->is_variable()
2466 && !no
->var_value()->is_parameter()
2467 && !this->functions_
.empty())
2468 this->add_statement(Statement::make_variable_declaration(no
));
2474 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2476 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2479 go_assert(strlen(tag
) < 10);
2480 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2487 // Add a sink--a reference to the blank identifier _.
2492 return Named_object::make_sink();
2495 // Add a named object for a dot import.
2498 Gogo::add_dot_import_object(Named_object
* no
)
2500 // If the name already exists, then it was defined in some file seen
2501 // earlier. If the earlier name is just a declaration, don't add
2502 // this name, because that will cause the previous declaration to
2503 // merge to this imported name, which should not happen. Just add
2504 // this name to the list of file block names to get appropriate
2505 // errors if we see a later definition.
2506 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2507 if (e
!= NULL
&& e
->package() == NULL
)
2509 if (e
->is_unknown())
2511 if (e
->package() == NULL
2512 && (e
->is_type_declaration()
2513 || e
->is_function_declaration()
2514 || e
->is_unknown()))
2516 this->add_file_block_name(no
->name(), no
->location());
2521 this->current_bindings()->add_named_object(no
);
2524 // Add a linkname. This implements the go:linkname compiler directive.
2525 // We only support this for functions and function declarations.
2528 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2529 const std::string
& ext_name
, Location loc
)
2532 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2535 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2536 else if (no
->is_function())
2538 if (ext_name
.empty())
2539 no
->func_value()->set_is_exported_by_linkname();
2541 no
->func_value()->set_asm_name(ext_name
);
2543 else if (no
->is_function_declaration())
2545 if (ext_name
.empty())
2547 ("%<//go:linkname%> missing external name "
2548 "for declaration of %s"),
2551 no
->func_declaration_value()->set_asm_name(ext_name
);
2555 ("%s is not a function; "
2556 "%<//go:linkname%> is only supported for functions"),
2560 // Mark all local variables used. This is used when some types of
2561 // parse error occur.
2564 Gogo::mark_locals_used()
2566 for (Open_functions::iterator pf
= this->functions_
.begin();
2567 pf
!= this->functions_
.end();
2570 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2571 pb
!= pf
->blocks
.end();
2573 (*pb
)->bindings()->mark_locals_used();
2577 // Record that we've seen an interface type.
2580 Gogo::record_interface_type(Interface_type
* itype
)
2582 this->interface_types_
.push_back(itype
);
2585 // Define the global names. We do this only after parsing all the
2586 // input files, because the program might define the global names
2590 Gogo::define_global_names()
2592 if (this->is_main_package())
2594 // Every Go program has to import the runtime package, so that
2595 // it is properly initialized. We can't use
2596 // predeclared_location here as it will cause runtime functions
2597 // to appear to be builtin functions.
2598 this->import_package("runtime", "_", false, false,
2599 this->package_
->location());
2602 for (Bindings::const_declarations_iterator p
=
2603 this->globals_
->begin_declarations();
2604 p
!= this->globals_
->end_declarations();
2607 Named_object
* global_no
= p
->second
;
2608 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2609 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2613 if (no
->is_type_declaration())
2615 if (global_no
->is_type())
2617 if (no
->type_declaration_value()->has_methods())
2619 for (std::vector
<Named_object
*>::const_iterator pm
=
2620 no
->type_declaration_value()->methods()->begin();
2621 pm
!= no
->type_declaration_value()->methods()->end();
2623 go_error_at((*pm
)->location(),
2624 "may not define methods on non-local type");
2626 no
->set_type_value(global_no
->type_value());
2630 go_error_at(no
->location(), "expected type");
2631 Type
* errtype
= Type::make_error_type();
2633 Named_object::make_type("erroneous_type", NULL
, errtype
,
2634 Linemap::predeclared_location());
2635 no
->set_type_value(err
->type_value());
2638 else if (no
->is_unknown())
2639 no
->unknown_value()->set_real_named_object(global_no
);
2642 // Give an error if any name is defined in both the package block
2643 // and the file block. For example, this can happen if one file
2644 // imports "fmt" and another file defines a global variable fmt.
2645 for (Bindings::const_declarations_iterator p
=
2646 this->package_
->bindings()->begin_declarations();
2647 p
!= this->package_
->bindings()->end_declarations();
2650 if (p
->second
->is_unknown()
2651 && p
->second
->unknown_value()->real_named_object() == NULL
)
2653 // No point in warning about an undefined name, as we will
2654 // get other errors later anyhow.
2657 File_block_names::const_iterator pf
=
2658 this->file_block_names_
.find(p
->second
->name());
2659 if (pf
!= this->file_block_names_
.end())
2661 std::string n
= p
->second
->message_name();
2662 go_error_at(p
->second
->location(),
2663 "%qs defined as both imported name and global name",
2665 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2668 // No package scope identifier may be named "init".
2669 if (!p
->second
->is_function()
2670 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2672 go_error_at(p
->second
->location(),
2673 "cannot declare init - must be func");
2678 // Clear out names in file scope.
2681 Gogo::clear_file_scope()
2683 this->package_
->bindings()->clear_file_scope(this);
2685 // Warn about packages which were imported but not used.
2686 bool quiet
= saw_errors();
2687 for (Packages::iterator p
= this->packages_
.begin();
2688 p
!= this->packages_
.end();
2691 Package
* package
= p
->second
;
2692 if (package
!= this->package_
&& !quiet
)
2694 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2695 p1
!= package
->aliases().end();
2698 if (!p1
->second
->used())
2700 // Give a more refined error message if the alias name is known.
2701 std::string pkg_name
= package
->package_name();
2702 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2704 go_error_at(p1
->second
->location(),
2705 "imported and not used: %s as %s",
2706 Gogo::message_name(pkg_name
).c_str(),
2707 Gogo::message_name(p1
->first
).c_str());
2710 go_error_at(p1
->second
->location(),
2711 "imported and not used: %s",
2712 Gogo::message_name(pkg_name
).c_str());
2716 package
->clear_used();
2719 this->current_file_imported_unsafe_
= false;
2722 // Queue up a type-specific hash function for later writing. These
2723 // are written out in write_specific_type_functions, called after the
2724 // parse tree is lowered.
2727 Gogo::queue_hash_function(Type
* type
, int64_t size
, Backend_name
* bname
,
2728 Function_type
* hash_fntype
)
2730 go_assert(!this->specific_type_functions_are_written_
);
2731 go_assert(!this->in_global_scope());
2732 Specific_type_function::Specific_type_function_kind kind
=
2733 Specific_type_function::SPECIFIC_HASH
;
2734 Specific_type_function
* tsf
= new Specific_type_function(type
, NULL
, size
,
2737 this->specific_type_functions_
.push_back(tsf
);
2740 // Queue up a type-specific equal function for later writing. These
2741 // are written out in write_specific_type_functions, called after the
2742 // parse tree is lowered.
2745 Gogo::queue_equal_function(Type
* type
, Named_type
* name
, int64_t size
,
2746 Backend_name
* bname
, Function_type
* equal_fntype
)
2748 go_assert(!this->specific_type_functions_are_written_
);
2749 go_assert(!this->in_global_scope());
2750 Specific_type_function::Specific_type_function_kind kind
=
2751 Specific_type_function::SPECIFIC_EQUAL
;
2752 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2755 this->specific_type_functions_
.push_back(tsf
);
2758 // Look for types which need specific hash or equality functions.
2760 class Specific_type_functions
: public Traverse
2763 Specific_type_functions(Gogo
* gogo
)
2764 : Traverse(traverse_types
),
2776 Specific_type_functions::type(Type
* t
)
2778 switch (t
->classification())
2780 case Type::TYPE_NAMED
:
2782 Named_type
* nt
= t
->named_type();
2784 return TRAVERSE_CONTINUE
;
2785 if (t
->needs_specific_type_functions(this->gogo_
))
2786 t
->equal_function(this->gogo_
, nt
, NULL
);
2788 // If this is a struct type, we don't want to make functions
2789 // for the unnamed struct.
2790 Type
* rt
= nt
->real_type();
2791 if (rt
->struct_type() == NULL
)
2793 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2794 return TRAVERSE_EXIT
;
2798 // If this type is defined in another package, then we don't
2799 // need to worry about the unexported fields.
2800 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2801 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2802 for (Struct_field_list::const_iterator p
= fields
->begin();
2806 if (is_defined_elsewhere
2807 && Gogo::is_hidden_name(p
->field_name()))
2809 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2810 return TRAVERSE_EXIT
;
2814 return TRAVERSE_SKIP_COMPONENTS
;
2817 case Type::TYPE_STRUCT
:
2818 case Type::TYPE_ARRAY
:
2819 if (t
->needs_specific_type_functions(this->gogo_
))
2820 t
->equal_function(this->gogo_
, NULL
, NULL
);
2823 case Type::TYPE_MAP
:
2825 Type
* key_type
= t
->map_type()->key_type();
2826 if (key_type
->needs_specific_type_functions(this->gogo_
))
2827 key_type
->hash_function(this->gogo_
, NULL
);
2835 return TRAVERSE_CONTINUE
;
2838 // Write out type specific functions.
2841 Gogo::write_specific_type_functions()
2843 Specific_type_functions
stf(this);
2844 this->traverse(&stf
);
2846 while (!this->specific_type_functions_
.empty())
2848 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2849 this->specific_type_functions_
.pop_back();
2850 if (tsf
->kind
== Specific_type_function::SPECIFIC_HASH
)
2851 tsf
->type
->write_hash_function(this, tsf
->size
, &tsf
->bname
,
2854 tsf
->type
->write_equal_function(this, tsf
->name
, tsf
->size
,
2855 &tsf
->bname
, tsf
->fntype
);
2858 this->specific_type_functions_are_written_
= true;
2861 // Traverse the tree.
2864 Gogo::traverse(Traverse
* traverse
)
2866 // Traverse the current package first for consistency. The other
2867 // packages will only contain imported types, constants, and
2869 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2871 for (Packages::const_iterator p
= this->packages_
.begin();
2872 p
!= this->packages_
.end();
2875 if (p
->second
!= this->package_
)
2877 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2883 // Add a type to verify. This is used for types of sink variables, in
2884 // order to give appropriate error messages.
2887 Gogo::add_type_to_verify(Type
* type
)
2889 this->verify_types_
.push_back(type
);
2892 // Traversal class used to verify types.
2894 class Verify_types
: public Traverse
2898 : Traverse(traverse_types
)
2905 // Verify that a type is correct.
2908 Verify_types::type(Type
* t
)
2911 return TRAVERSE_SKIP_COMPONENTS
;
2912 return TRAVERSE_CONTINUE
;
2915 // Verify that all types are correct.
2918 Gogo::verify_types()
2920 Verify_types traverse
;
2921 this->traverse(&traverse
);
2923 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2924 p
!= this->verify_types_
.end();
2927 this->verify_types_
.clear();
2930 // Traversal class used to lower parse tree.
2932 class Lower_parse_tree
: public Traverse
2935 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2936 : Traverse(traverse_variables
2937 | traverse_constants
2938 | traverse_functions
2939 | traverse_statements
2940 | traverse_expressions
),
2941 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2945 set_inserter(const Statement_inserter
* inserter
)
2946 { this->inserter_
= *inserter
; }
2949 variable(Named_object
*);
2952 constant(Named_object
*, bool);
2955 function(Named_object
*);
2958 statement(Block
*, size_t* pindex
, Statement
*);
2961 expression(Expression
**);
2966 // The function we are traversing.
2967 Named_object
* function_
;
2968 // Value to use for the predeclared constant iota.
2970 // Current statement inserter for use by expressions.
2971 Statement_inserter inserter_
;
2977 Lower_parse_tree::variable(Named_object
* no
)
2979 if (!no
->is_variable())
2980 return TRAVERSE_CONTINUE
;
2982 if (no
->is_variable() && no
->var_value()->is_global())
2984 // Global variables can have loops in their initialization
2985 // expressions. This is handled in lower_init_expression.
2986 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2988 return TRAVERSE_CONTINUE
;
2991 // This is a local variable. We are going to return
2992 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2993 // initialization expression when we reach the variable declaration
2994 // statement. However, that means that we need to traverse the type
2996 if (no
->var_value()->has_type())
2998 Type
* type
= no
->var_value()->type();
3001 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
3002 return TRAVERSE_EXIT
;
3005 go_assert(!no
->var_value()->has_pre_init());
3007 return TRAVERSE_SKIP_COMPONENTS
;
3010 // Lower constants. We handle constants specially so that we can set
3011 // the right value for the predeclared constant iota. This works in
3012 // conjunction with the way we lower Const_expression objects.
3015 Lower_parse_tree::constant(Named_object
* no
, bool)
3017 Named_constant
* nc
= no
->const_value();
3019 // Don't get into trouble if the constant's initializer expression
3020 // refers to the constant itself.
3022 return TRAVERSE_CONTINUE
;
3025 go_assert(this->iota_value_
== -1);
3026 this->iota_value_
= nc
->iota_value();
3027 nc
->traverse_expression(this);
3028 this->iota_value_
= -1;
3030 nc
->clear_lowering();
3032 // We will traverse the expression a second time, but that will be
3035 return TRAVERSE_CONTINUE
;
3038 // Lower the body of a function, and set the closure type. Record the
3039 // function while lowering it, so that we can pass it down when
3040 // lowering an expression.
3043 Lower_parse_tree::function(Named_object
* no
)
3045 no
->func_value()->set_closure_type();
3047 go_assert(this->function_
== NULL
);
3048 this->function_
= no
;
3049 int t
= no
->func_value()->traverse(this);
3050 this->function_
= NULL
;
3052 if (t
== TRAVERSE_EXIT
)
3054 return TRAVERSE_SKIP_COMPONENTS
;
3057 // Lower statement parse trees.
3060 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3062 // Because we explicitly traverse the statement's contents
3063 // ourselves, we want to skip block statements here. There is
3064 // nothing to lower in a block statement.
3065 if (sorig
->is_block_statement())
3066 return TRAVERSE_CONTINUE
;
3068 Statement_inserter
hold_inserter(this->inserter_
);
3069 this->inserter_
= Statement_inserter(block
, pindex
);
3071 // Lower the expressions first.
3072 int t
= sorig
->traverse_contents(this);
3073 if (t
== TRAVERSE_EXIT
)
3075 this->inserter_
= hold_inserter
;
3079 // Keep lowering until nothing changes.
3080 Statement
* s
= sorig
;
3083 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
3088 t
= s
->traverse_contents(this);
3089 if (t
== TRAVERSE_EXIT
)
3091 this->inserter_
= hold_inserter
;
3097 block
->replace_statement(*pindex
, s
);
3099 this->inserter_
= hold_inserter
;
3100 return TRAVERSE_SKIP_COMPONENTS
;
3103 // Lower expression parse trees.
3106 Lower_parse_tree::expression(Expression
** pexpr
)
3108 // We have to lower all subexpressions first, so that we can get
3109 // their type if necessary. This is awkward, because we don't have
3110 // a postorder traversal pass.
3111 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3112 return TRAVERSE_EXIT
;
3113 // Keep lowering until nothing changes.
3116 Expression
* e
= *pexpr
;
3117 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
3118 &this->inserter_
, this->iota_value_
);
3121 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3122 return TRAVERSE_EXIT
;
3126 // Lower the type of this expression before the parent looks at it,
3127 // in case the type contains an array that has expressions in its
3128 // length. Skip an Unknown_expression, as at this point that means
3129 // a composite literal key that does not have a type.
3130 if ((*pexpr
)->unknown_expression() == NULL
)
3131 Type::traverse((*pexpr
)->type(), this);
3133 return TRAVERSE_SKIP_COMPONENTS
;
3136 // Lower the parse tree. This is called after the parse is complete,
3137 // when all names should be resolved.
3140 Gogo::lower_parse_tree()
3142 Lower_parse_tree
lower_parse_tree(this, NULL
);
3143 this->traverse(&lower_parse_tree
);
3145 // If we found any functions defined in other packages that are
3146 // inlinables, import their bodies and turn them into functions.
3148 // Note that as we import inlinable functions we may find more
3149 // inlinable functions, so don't use an iterator.
3150 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
3152 Named_object
* no
= this->imported_inlinable_functions_
[i
];
3153 no
->func_declaration_value()->import_function_body(this, no
);
3156 // There might be type definitions that involve expressions such as the
3157 // array length. Make sure to lower these expressions as well. Otherwise,
3158 // errors hidden within a type can introduce unexpected errors into later
3160 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
3161 p
!= this->verify_types_
.end();
3163 Type::traverse(*p
, &lower_parse_tree
);
3169 Gogo::lower_block(Named_object
* function
, Block
* block
)
3171 Lower_parse_tree
lower_parse_tree(this, function
);
3172 block
->traverse(&lower_parse_tree
);
3175 // Lower an expression. INSERTER may be NULL, in which case the
3176 // expression had better not need to create any temporaries.
3179 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
3182 Lower_parse_tree
lower_parse_tree(this, function
);
3183 if (inserter
!= NULL
)
3184 lower_parse_tree
.set_inserter(inserter
);
3185 lower_parse_tree
.expression(pexpr
);
3188 // Lower a constant. This is called when lowering a reference to a
3189 // constant. We have to make sure that the constant has already been
3193 Gogo::lower_constant(Named_object
* no
)
3195 go_assert(no
->is_const());
3196 Lower_parse_tree
lower(this, NULL
);
3197 lower
.constant(no
, false);
3200 // Make implicit type conversions explicit. Currently only does for
3201 // interface conversions, so the escape analysis can see them and
3204 class Add_conversions
: public Traverse
3208 : Traverse(traverse_statements
3209 | traverse_expressions
)
3213 statement(Block
*, size_t* pindex
, Statement
*);
3216 expression(Expression
**);
3219 // Add explicit conversions in a statement.
3222 Add_conversions::statement(Block
*, size_t*, Statement
* sorig
)
3224 sorig
->add_conversions();
3225 return TRAVERSE_CONTINUE
;
3228 // Add explicit conversions in an expression.
3231 Add_conversions::expression(Expression
** pexpr
)
3233 (*pexpr
)->add_conversions();
3234 return TRAVERSE_CONTINUE
;
3238 Gogo::add_conversions()
3240 Add_conversions add_conversions
;
3241 this->traverse(&add_conversions
);
3245 Gogo::add_conversions_in_block(Block
*b
)
3247 Add_conversions add_conversions
;
3248 b
->traverse(&add_conversions
);
3251 // Traversal class for simple deadcode elimination.
3253 class Remove_deadcode
: public Traverse
3257 : Traverse(traverse_statements
3258 | traverse_expressions
)
3262 statement(Block
*, size_t* pindex
, Statement
*);
3265 expression(Expression
**);
3268 // Remove deadcode in a statement.
3271 Remove_deadcode::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3273 Location loc
= sorig
->location();
3274 If_statement
* ifs
= sorig
->if_statement();
3277 // Remove the dead branch of an if statement.
3279 if (ifs
->condition()->boolean_constant_value(&bval
))
3283 s
= Statement::make_block_statement(ifs
->then_block(),
3286 if (ifs
->else_block() != NULL
)
3287 s
= Statement::make_block_statement(ifs
->else_block(),
3290 // Make a dummy statement.
3291 s
= Statement::make_statement(Expression::make_boolean(false, loc
),
3294 block
->replace_statement(*pindex
, s
);
3297 return TRAVERSE_CONTINUE
;
3300 // Remove deadcode in an expression.
3303 Remove_deadcode::expression(Expression
** pexpr
)
3305 // Discard the right arm of a shortcut expression of constant value.
3306 Binary_expression
* be
= (*pexpr
)->binary_expression();
3309 && be
->boolean_constant_value(&bval
)
3310 && (be
->op() == OPERATOR_ANDAND
3311 || be
->op() == OPERATOR_OROR
))
3313 *pexpr
= Expression::make_boolean(bval
, be
->location());
3314 Type_context
context(NULL
, false);
3315 (*pexpr
)->determine_type(&context
);
3317 return TRAVERSE_CONTINUE
;
3323 Gogo::remove_deadcode()
3325 Remove_deadcode remove_deadcode
;
3326 this->traverse(&remove_deadcode
);
3329 // Traverse the tree to create function descriptors as needed.
3331 class Create_function_descriptors
: public Traverse
3334 Create_function_descriptors(Gogo
* gogo
)
3335 : Traverse(traverse_functions
| traverse_expressions
),
3340 function(Named_object
*);
3343 expression(Expression
**);
3349 // Create a descriptor for every top-level exported function and every
3350 // function referenced by an inline function.
3353 Create_function_descriptors::function(Named_object
* no
)
3355 if (no
->is_function()
3356 && no
->func_value()->enclosing() == NULL
3357 && !no
->func_value()->is_method()
3358 && ((!Gogo::is_hidden_name(no
->name())
3359 && !Gogo::is_thunk(no
))
3360 || no
->func_value()->is_referenced_by_inline()))
3361 no
->func_value()->descriptor(this->gogo_
, no
);
3363 return TRAVERSE_CONTINUE
;
3366 // If we see a function referenced in any way other than calling it,
3367 // create a descriptor for it.
3370 Create_function_descriptors::expression(Expression
** pexpr
)
3372 Expression
* expr
= *pexpr
;
3374 Func_expression
* fe
= expr
->func_expression();
3377 // We would not get here for a call to this function, so this is
3378 // a reference to a function other than calling it. We need a
3380 if (fe
->closure() != NULL
)
3381 return TRAVERSE_CONTINUE
;
3382 Named_object
* no
= fe
->named_object();
3383 if (no
->is_function() && !no
->func_value()->is_method())
3384 no
->func_value()->descriptor(this->gogo_
, no
);
3385 else if (no
->is_function_declaration()
3386 && !no
->func_declaration_value()->type()->is_method()
3387 && !Linemap::is_predeclared_location(no
->location()))
3388 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3389 return TRAVERSE_CONTINUE
;
3392 Bound_method_expression
* bme
= expr
->bound_method_expression();
3395 // We would not get here for a call to this method, so this is a
3396 // method value. We need to create a thunk.
3397 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3399 return TRAVERSE_CONTINUE
;
3402 Interface_field_reference_expression
* ifre
=
3403 expr
->interface_field_reference_expression();
3406 // We would not get here for a call to this interface method, so
3407 // this is a method value. We need to create a thunk.
3408 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3410 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3412 return TRAVERSE_CONTINUE
;
3415 Call_expression
* ce
= expr
->call_expression();
3418 Expression
* fn
= ce
->fn();
3419 if (fn
->func_expression() != NULL
3420 || fn
->bound_method_expression() != NULL
3421 || fn
->interface_field_reference_expression() != NULL
)
3423 // Traverse the arguments but not the function.
3424 Expression_list
* args
= ce
->args();
3427 if (args
->traverse(this) == TRAVERSE_EXIT
)
3428 return TRAVERSE_EXIT
;
3430 return TRAVERSE_SKIP_COMPONENTS
;
3434 return TRAVERSE_CONTINUE
;
3437 // Create function descriptors as needed. We need a function
3438 // descriptor for all exported functions and for all functions that
3439 // are referenced without being called.
3442 Gogo::create_function_descriptors()
3444 // Create a function descriptor for any exported function that is
3445 // declared in this package. This is so that we have a descriptor
3446 // for functions written in assembly. Gather the descriptors first
3447 // so that we don't add declarations while looping over them.
3448 std::vector
<Named_object
*> fndecls
;
3449 Bindings
* b
= this->package_
->bindings();
3450 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3451 p
!= b
->end_declarations();
3454 Named_object
* no
= p
->second
;
3455 if (no
->is_function_declaration()
3456 && !no
->func_declaration_value()->type()->is_method()
3457 && !Linemap::is_predeclared_location(no
->location())
3458 && !Gogo::is_hidden_name(no
->name()))
3459 fndecls
.push_back(no
);
3461 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3464 (*p
)->func_declaration_value()->descriptor(this, *p
);
3467 Create_function_descriptors
cfd(this);
3468 this->traverse(&cfd
);
3471 // Finalize the methods of an interface type.
3474 Finalize_methods::type(Type
* t
)
3476 // Check the classification so that we don't finalize the methods
3477 // twice for a named interface type.
3478 switch (t
->classification())
3480 case Type::TYPE_INTERFACE
:
3481 t
->interface_type()->finalize_methods();
3484 case Type::TYPE_NAMED
:
3486 Named_type
* nt
= t
->named_type();
3489 return TRAVERSE_CONTINUE
;
3491 Type
* rt
= nt
->real_type();
3492 if (rt
->classification() != Type::TYPE_STRUCT
)
3494 // Finalize the methods of the real type first.
3495 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3496 return TRAVERSE_EXIT
;
3498 // Finalize the methods of this type.
3499 nt
->finalize_methods(this->gogo_
);
3503 // We don't want to finalize the methods of a named struct
3504 // type, as the methods should be attached to the named
3505 // type, not the struct type. We just want to finalize
3508 // It is possible that a field type refers indirectly to
3509 // this type, such as via a field with function type with
3510 // an argument or result whose type is this type. To
3511 // avoid the cycle, first finalize the methods of any
3512 // embedded types, which are the only types we need to
3513 // know to finalize the methods of this type.
3514 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3517 for (Struct_field_list::const_iterator pf
= fields
->begin();
3518 pf
!= fields
->end();
3521 if (pf
->is_anonymous())
3523 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3524 return TRAVERSE_EXIT
;
3529 // Finalize the methods of this type.
3530 nt
->finalize_methods(this->gogo_
);
3532 // Finalize all the struct fields.
3533 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3534 return TRAVERSE_EXIT
;
3537 // If this type is defined in a different package, then finalize the
3538 // types of all the methods, since we won't see them otherwise.
3539 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3541 const Methods
* methods
= nt
->methods();
3542 for (Methods::const_iterator p
= methods
->begin();
3543 p
!= methods
->end();
3546 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3547 return TRAVERSE_EXIT
;
3551 // Finalize the types of all methods that are declared but not
3552 // defined, since we won't see the declarations otherwise.
3553 if (nt
->named_object()->package() == NULL
3554 && nt
->local_methods() != NULL
)
3556 const Bindings
* methods
= nt
->local_methods();
3557 for (Bindings::const_declarations_iterator p
=
3558 methods
->begin_declarations();
3559 p
!= methods
->end_declarations();
3562 if (p
->second
->is_function_declaration())
3564 Type
* mt
= p
->second
->func_declaration_value()->type();
3565 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3566 return TRAVERSE_EXIT
;
3571 return TRAVERSE_SKIP_COMPONENTS
;
3574 case Type::TYPE_STRUCT
:
3575 // Traverse the field types first in case there is an embedded
3576 // field with methods that the struct should inherit.
3577 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3578 return TRAVERSE_EXIT
;
3579 t
->struct_type()->finalize_methods(this->gogo_
);
3580 return TRAVERSE_SKIP_COMPONENTS
;
3586 return TRAVERSE_CONTINUE
;
3589 // Finalize method lists and build stub methods for types.
3592 Gogo::finalize_methods()
3594 Finalize_methods
finalize(this);
3595 this->traverse(&finalize
);
3598 // Finalize the method list for a type. This is called when a type is
3599 // parsed for an inlined function body, which happens after the
3600 // finalize_methods pass.
3603 Gogo::finalize_methods_for_type(Type
* type
)
3605 Finalize_methods
finalize(this);
3606 Type::traverse(type
, &finalize
);
3609 // Set types for unspecified variables and constants.
3612 Gogo::determine_types()
3614 Bindings
* bindings
= this->current_bindings();
3615 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3616 p
!= bindings
->end_definitions();
3619 if ((*p
)->is_function())
3620 (*p
)->func_value()->determine_types();
3621 else if ((*p
)->is_variable())
3622 (*p
)->var_value()->determine_type();
3623 else if ((*p
)->is_const())
3624 (*p
)->const_value()->determine_type();
3626 // See if a variable requires us to build an initialization
3627 // function. We know that we will see all global variables
3629 if (!this->need_init_fn_
&& (*p
)->is_variable())
3631 Variable
* variable
= (*p
)->var_value();
3633 // If this is a global variable which requires runtime
3634 // initialization, we need an initialization function.
3635 if (!variable
->is_global())
3637 else if (variable
->init() == NULL
)
3639 else if (variable
->type()->interface_type() != NULL
)
3640 this->need_init_fn_
= true;
3641 else if (variable
->init()->is_constant())
3643 else if (!variable
->init()->is_composite_literal())
3644 this->need_init_fn_
= true;
3645 else if (variable
->init()->is_nonconstant_composite_literal())
3646 this->need_init_fn_
= true;
3648 // If this is a global variable which holds a pointer value,
3649 // then we need an initialization function to register it as a
3651 if (variable
->is_global() && variable
->type()->has_pointer())
3652 this->need_init_fn_
= true;
3656 // Determine the types of constants in packages.
3657 for (Packages::const_iterator p
= this->packages_
.begin();
3658 p
!= this->packages_
.end();
3660 p
->second
->determine_types();
3663 // Traversal class used for type checking.
3665 class Check_types_traverse
: public Traverse
3668 Check_types_traverse(Gogo
* gogo
)
3669 : Traverse(traverse_variables
3670 | traverse_constants
3671 | traverse_functions
3672 | traverse_statements
3673 | traverse_expressions
),
3678 variable(Named_object
*);
3681 constant(Named_object
*, bool);
3684 function(Named_object
*);
3687 statement(Block
*, size_t* pindex
, Statement
*);
3690 expression(Expression
**);
3697 // Check that a variable initializer has the right type.
3700 Check_types_traverse::variable(Named_object
* named_object
)
3702 if (named_object
->is_variable())
3704 Variable
* var
= named_object
->var_value();
3706 // Give error if variable type is not defined.
3707 var
->type()->base();
3709 Expression
* init
= var
->init();
3712 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3715 go_error_at(var
->location(), "incompatible type in initialization");
3717 go_error_at(var
->location(),
3718 "incompatible type in initialization (%s)",
3720 init
= Expression::make_error(named_object
->location());
3723 else if (init
!= NULL
3724 && init
->func_expression() != NULL
)
3726 Named_object
* no
= init
->func_expression()->named_object();
3727 Function_type
* fntype
;
3728 if (no
->is_function())
3729 fntype
= no
->func_value()->type();
3730 else if (no
->is_function_declaration())
3731 fntype
= no
->func_declaration_value()->type();
3735 // Builtin functions cannot be used as function values for variable
3737 if (fntype
->is_builtin())
3739 go_error_at(init
->location(),
3740 "invalid use of special built-in function %qs; "
3742 no
->message_name().c_str());
3746 && !var
->is_global()
3747 && !var
->is_parameter()
3748 && !var
->is_receiver()
3749 && !var
->type()->is_error()
3750 && (init
== NULL
|| !init
->is_error_expression())
3751 && !Lex::is_invalid_identifier(named_object
->name()))
3752 go_error_at(var
->location(), "%qs declared but not used",
3753 named_object
->message_name().c_str());
3755 return TRAVERSE_CONTINUE
;
3758 // Check that a constant initializer has the right type.
3761 Check_types_traverse::constant(Named_object
* named_object
, bool)
3763 Named_constant
* constant
= named_object
->const_value();
3764 Type
* ctype
= constant
->type();
3765 if (ctype
->integer_type() == NULL
3766 && ctype
->float_type() == NULL
3767 && ctype
->complex_type() == NULL
3768 && !ctype
->is_boolean_type()
3769 && !ctype
->is_string_type())
3771 if (ctype
->is_nil_type())
3772 go_error_at(constant
->location(), "const initializer cannot be nil");
3773 else if (!ctype
->is_error())
3774 go_error_at(constant
->location(), "invalid constant type");
3775 constant
->set_error();
3777 else if (!constant
->expr()->is_constant())
3779 go_error_at(constant
->expr()->location(), "expression is not constant");
3780 constant
->set_error();
3782 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3785 go_error_at(constant
->location(),
3786 "initialization expression has wrong type");
3787 constant
->set_error();
3789 return TRAVERSE_CONTINUE
;
3792 // There are no types to check in a function, but this is where we
3793 // issue warnings about labels which are defined but not referenced.
3796 Check_types_traverse::function(Named_object
* no
)
3798 no
->func_value()->check_labels();
3799 return TRAVERSE_CONTINUE
;
3802 // Check that types are valid in a statement.
3805 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3807 s
->check_types(this->gogo_
);
3808 return TRAVERSE_CONTINUE
;
3811 // Check that types are valid in an expression.
3814 Check_types_traverse::expression(Expression
** expr
)
3816 (*expr
)->check_types(this->gogo_
);
3817 return TRAVERSE_CONTINUE
;
3820 // Check that types are valid.
3825 Check_types_traverse
traverse(this);
3826 this->traverse(&traverse
);
3828 Bindings
* bindings
= this->current_bindings();
3829 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3830 p
!= bindings
->end_declarations();
3833 // Also check the types in a function declaration's signature.
3834 Named_object
* no
= p
->second
;
3835 if (no
->is_function_declaration())
3836 no
->func_declaration_value()->check_types();
3840 // Check the types in a single block.
3843 Gogo::check_types_in_block(Block
* block
)
3845 Check_types_traverse
traverse(this);
3846 block
->traverse(&traverse
);
3849 // A traversal class which finds all the expressions which must be
3850 // evaluated in order within a statement or larger expression. This
3851 // is used to implement the rules about order of evaluation.
3853 class Find_eval_ordering
: public Traverse
3856 typedef std::vector
<Expression
**> Expression_pointers
;
3859 Find_eval_ordering()
3860 : Traverse(traverse_blocks
3861 | traverse_statements
3862 | traverse_expressions
),
3868 { return this->exprs_
.size(); }
3870 typedef Expression_pointers::const_iterator const_iterator
;
3874 { return this->exprs_
.begin(); }
3878 { return this->exprs_
.end(); }
3883 { return TRAVERSE_SKIP_COMPONENTS
; }
3886 statement(Block
*, size_t*, Statement
*)
3887 { return TRAVERSE_SKIP_COMPONENTS
; }
3890 expression(Expression
**);
3893 // A list of pointers to expressions with side-effects.
3894 Expression_pointers exprs_
;
3897 // If an expression must be evaluated in order, put it on the list.
3900 Find_eval_ordering::expression(Expression
** expression_pointer
)
3902 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3904 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3906 // Shortcut expressions may potentially have side effects which need
3907 // to be ordered, so add them to the list.
3908 // We don't order its subexpressions here since they may be evaluated
3909 // conditionally. This is handled in remove_shortcuts.
3910 this->exprs_
.push_back(expression_pointer
);
3911 return TRAVERSE_SKIP_COMPONENTS
;
3914 // We have to look at subexpressions before this one.
3915 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3916 return TRAVERSE_EXIT
;
3917 if ((*expression_pointer
)->must_eval_in_order())
3918 this->exprs_
.push_back(expression_pointer
);
3919 return TRAVERSE_SKIP_COMPONENTS
;
3922 // A traversal class for ordering evaluations.
3924 class Order_eval
: public Traverse
3927 Order_eval(Gogo
* gogo
)
3928 : Traverse(traverse_variables
3929 | traverse_statements
),
3934 variable(Named_object
*);
3937 statement(Block
*, size_t*, Statement
*);
3944 // Implement the order of evaluation rules for a statement.
3947 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3949 // FIXME: This approach doesn't work for switch statements, because
3950 // we add the new statements before the whole switch when we need to
3951 // instead add them just before the switch expression. The right
3952 // fix is probably to lower switch statements with nonconstant cases
3953 // to a series of conditionals.
3954 if (stmt
->switch_statement() != NULL
)
3955 return TRAVERSE_CONTINUE
;
3957 Find_eval_ordering find_eval_ordering
;
3959 // If S is a variable declaration, then ordinary traversal won't do
3960 // anything. We want to explicitly traverse the initialization
3961 // expression if there is one.
3962 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
3963 Expression
* init
= NULL
;
3964 Expression
* orig_init
= NULL
;
3966 stmt
->traverse_contents(&find_eval_ordering
);
3969 init
= vds
->var()->var_value()->init();
3971 return TRAVERSE_CONTINUE
;
3974 // It might seem that this could be
3975 // init->traverse_subexpressions. Unfortunately that can fail
3978 // newvar, err := call(arg())
3979 // Here newvar will have an init of call result 0 of
3980 // call(arg()). If we only traverse subexpressions, we will
3981 // only find arg(), and we won't bother to move anything out.
3982 // Then we get to the assignment to err, we will traverse the
3983 // whole statement, and this time we will find both call() and
3984 // arg(), and so we will move them out. This will cause them to
3985 // be put into temporary variables before the assignment to err
3986 // but after the declaration of newvar. To avoid that problem,
3987 // we traverse the entire expression here.
3988 Expression::traverse(&init
, &find_eval_ordering
);
3991 size_t c
= find_eval_ordering
.size();
3993 return TRAVERSE_CONTINUE
;
3995 // If there is only one expression with a side-effect, we can
3996 // usually leave it in place.
3999 switch (stmt
->classification())
4001 case Statement::STATEMENT_ASSIGNMENT
:
4002 // For an assignment statement, we need to evaluate an
4003 // expression on the right hand side before we evaluate any
4004 // index expression on the left hand side, so for that case
4005 // we always move the expression. Otherwise we mishandle
4006 // m[0] = len(m) where m is a map.
4009 case Statement::STATEMENT_EXPRESSION
:
4011 // If this is a call statement that doesn't return any
4012 // values, it will not have been counted as a value to
4013 // move. We need to move any subexpressions in case they
4014 // are themselves call statements that require passing a
4016 Expression
* expr
= stmt
->expression_statement()->expr();
4017 if (expr
->call_expression() != NULL
4018 && expr
->call_expression()->result_count() == 0)
4020 return TRAVERSE_CONTINUE
;
4024 // We can leave the expression in place.
4025 return TRAVERSE_CONTINUE
;
4029 bool is_thunk
= stmt
->thunk_statement() != NULL
;
4030 Expression_statement
* es
= stmt
->expression_statement();
4031 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4032 p
!= find_eval_ordering
.end();
4035 Expression
** pexpr
= *p
;
4037 // The last expression in a thunk will be the call passed to go
4038 // or defer, which we must not evaluate early.
4039 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
4042 Location loc
= (*pexpr
)->location();
4044 if ((*pexpr
)->call_expression() == NULL
4045 || (*pexpr
)->call_expression()->result_count() < 2)
4047 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4050 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4054 // A call expression which returns multiple results needs to
4055 // be handled specially. We can't create a temporary
4056 // because there is no type to give it. Any actual uses of
4057 // the values will be done via Call_result_expressions.
4059 // Since a given call expression can be shared by multiple
4060 // Call_result_expressions, avoid hoisting the call the
4061 // second time we see it here. In addition, don't try to
4062 // hoist the top-level multi-return call in the statement,
4063 // since doing this would result a tree with more than one copy
4065 if (this->remember_expression(*pexpr
))
4067 else if (es
!= NULL
&& *pexpr
== es
->expr())
4070 s
= Statement::make_statement(*pexpr
, true);
4075 block
->insert_statement_before(*pindex
, s
);
4080 if (init
!= orig_init
)
4081 vds
->var()->var_value()->set_init(init
);
4083 return TRAVERSE_CONTINUE
;
4086 // Implement the order of evaluation rules for the initializer of a
4090 Order_eval::variable(Named_object
* no
)
4092 if (no
->is_result_variable())
4093 return TRAVERSE_CONTINUE
;
4094 Variable
* var
= no
->var_value();
4095 Expression
* init
= var
->init();
4096 if (!var
->is_global() || init
== NULL
)
4097 return TRAVERSE_CONTINUE
;
4099 Find_eval_ordering find_eval_ordering
;
4100 Expression::traverse(&init
, &find_eval_ordering
);
4102 if (find_eval_ordering
.size() <= 1)
4104 // If there is only one expression with a side-effect, we can
4105 // leave it in place.
4106 return TRAVERSE_SKIP_COMPONENTS
;
4109 Expression
* orig_init
= init
;
4111 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4112 p
!= find_eval_ordering
.end();
4115 Expression
** pexpr
= *p
;
4116 Location loc
= (*pexpr
)->location();
4118 if ((*pexpr
)->call_expression() == NULL
4119 || (*pexpr
)->call_expression()->result_count() < 2)
4121 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4124 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4128 // A call expression which returns multiple results needs to
4129 // be handled specially.
4130 s
= Statement::make_statement(*pexpr
, true);
4132 var
->add_preinit_statement(this->gogo_
, s
);
4135 if (init
!= orig_init
)
4136 var
->set_init(init
);
4138 return TRAVERSE_SKIP_COMPONENTS
;
4141 // Use temporary variables to implement the order of evaluation rules.
4144 Gogo::order_evaluations()
4146 Order_eval
order_eval(this);
4147 this->traverse(&order_eval
);
4150 // Order evaluations in a block.
4153 Gogo::order_block(Block
* block
)
4155 Order_eval
order_eval(this);
4156 block
->traverse(&order_eval
);
4159 // A traversal class used to find a single shortcut operator within an
4162 class Find_shortcut
: public Traverse
4166 : Traverse(traverse_blocks
4167 | traverse_statements
4168 | traverse_expressions
),
4172 // A pointer to the expression which was found, or NULL if none was
4176 { return this->found_
; }
4181 { return TRAVERSE_SKIP_COMPONENTS
; }
4184 statement(Block
*, size_t*, Statement
*)
4185 { return TRAVERSE_SKIP_COMPONENTS
; }
4188 expression(Expression
**);
4191 Expression
** found_
;
4194 // Find a shortcut expression.
4197 Find_shortcut::expression(Expression
** pexpr
)
4199 Expression
* expr
= *pexpr
;
4200 Binary_expression
* be
= expr
->binary_expression();
4202 return TRAVERSE_CONTINUE
;
4203 Operator op
= be
->op();
4204 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
4205 return TRAVERSE_CONTINUE
;
4206 go_assert(this->found_
== NULL
);
4207 this->found_
= pexpr
;
4208 return TRAVERSE_EXIT
;
4211 // A traversal class used to turn shortcut operators into explicit if
4214 class Shortcuts
: public Traverse
4217 Shortcuts(Gogo
* gogo
)
4218 : Traverse(traverse_variables
4219 | traverse_statements
),
4225 variable(Named_object
*);
4228 statement(Block
*, size_t*, Statement
*);
4231 // Convert a shortcut operator.
4233 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
4239 // Remove shortcut operators in a single statement.
4242 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
4244 // FIXME: This approach doesn't work for switch statements, because
4245 // we add the new statements before the whole switch when we need to
4246 // instead add them just before the switch expression. The right
4247 // fix is probably to lower switch statements with nonconstant cases
4248 // to a series of conditionals.
4249 if (s
->switch_statement() != NULL
)
4250 return TRAVERSE_CONTINUE
;
4254 Find_shortcut find_shortcut
;
4256 // If S is a variable declaration, then ordinary traversal won't
4257 // do anything. We want to explicitly traverse the
4258 // initialization expression if there is one.
4259 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
4260 Expression
* init
= NULL
;
4262 s
->traverse_contents(&find_shortcut
);
4265 init
= vds
->var()->var_value()->init();
4267 return TRAVERSE_CONTINUE
;
4268 init
->traverse(&init
, &find_shortcut
);
4270 Expression
** pshortcut
= find_shortcut
.found();
4271 if (pshortcut
== NULL
)
4272 return TRAVERSE_CONTINUE
;
4274 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
4275 block
->insert_statement_before(*pindex
, snew
);
4278 if (pshortcut
== &init
)
4279 vds
->var()->var_value()->set_init(init
);
4283 // Remove shortcut operators in the initializer of a global variable.
4286 Shortcuts::variable(Named_object
* no
)
4288 if (no
->is_result_variable())
4289 return TRAVERSE_CONTINUE
;
4290 Variable
* var
= no
->var_value();
4291 Expression
* init
= var
->init();
4292 if (!var
->is_global() || init
== NULL
)
4293 return TRAVERSE_CONTINUE
;
4297 Find_shortcut find_shortcut
;
4298 init
->traverse(&init
, &find_shortcut
);
4299 Expression
** pshortcut
= find_shortcut
.found();
4300 if (pshortcut
== NULL
)
4301 return TRAVERSE_CONTINUE
;
4303 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
4304 var
->add_preinit_statement(this->gogo_
, snew
);
4305 if (pshortcut
== &init
)
4306 var
->set_init(init
);
4310 // Given an expression which uses a shortcut operator, return a
4311 // statement which implements it, and update *PSHORTCUT accordingly.
4314 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
4316 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
4317 Expression
* left
= shortcut
->left();
4318 Expression
* right
= shortcut
->right();
4319 Location loc
= shortcut
->location();
4321 Block
* retblock
= new Block(enclosing
, loc
);
4322 retblock
->set_end_location(loc
);
4324 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
4326 retblock
->add_statement(ts
);
4328 Block
* block
= new Block(retblock
, loc
);
4329 block
->set_end_location(loc
);
4330 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4331 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4332 block
->add_statement(assign
);
4334 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4335 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4336 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4338 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4340 retblock
->add_statement(if_statement
);
4342 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4346 // Now convert any shortcut operators in LEFT and RIGHT.
4347 // LEFT and RIGHT were skipped in the top level
4348 // Gogo::order_evaluations. We need to order their
4349 // components first.
4350 Order_eval
order_eval(this->gogo_
);
4351 retblock
->traverse(&order_eval
);
4352 Shortcuts
shortcuts(this->gogo_
);
4353 retblock
->traverse(&shortcuts
);
4355 return Statement::make_block_statement(retblock
, loc
);
4358 // Turn shortcut operators into explicit if statements. Doing this
4359 // considerably simplifies the order of evaluation rules.
4362 Gogo::remove_shortcuts()
4364 Shortcuts
shortcuts(this);
4365 this->traverse(&shortcuts
);
4368 // Turn shortcut operators into explicit if statements in a block.
4371 Gogo::remove_shortcuts_in_block(Block
* block
)
4373 Shortcuts
shortcuts(this);
4374 block
->traverse(&shortcuts
);
4377 // Traversal to flatten parse tree after order of evaluation rules are applied.
4379 class Flatten
: public Traverse
4382 Flatten(Gogo
* gogo
, Named_object
* function
)
4383 : Traverse(traverse_variables
4384 | traverse_functions
4385 | traverse_statements
4386 | traverse_expressions
),
4387 gogo_(gogo
), function_(function
), inserter_()
4391 set_inserter(const Statement_inserter
* inserter
)
4392 { this->inserter_
= *inserter
; }
4395 variable(Named_object
*);
4398 function(Named_object
*);
4401 statement(Block
*, size_t* pindex
, Statement
*);
4404 expression(Expression
**);
4409 // The function we are traversing.
4410 Named_object
* function_
;
4411 // Current statement inserter for use by expressions.
4412 Statement_inserter inserter_
;
4415 // Flatten variables.
4418 Flatten::variable(Named_object
* no
)
4420 if (!no
->is_variable())
4421 return TRAVERSE_CONTINUE
;
4423 if (no
->is_variable() && no
->var_value()->is_global())
4425 // Global variables can have loops in their initialization
4426 // expressions. This is handled in flatten_init_expression.
4427 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4429 return TRAVERSE_CONTINUE
;
4432 if (!no
->var_value()->is_parameter()
4433 && !no
->var_value()->is_receiver()
4434 && !no
->var_value()->is_closure()
4435 && no
->var_value()->is_non_escaping_address_taken()
4436 && !no
->var_value()->is_in_heap()
4437 && no
->var_value()->toplevel_decl() == NULL
)
4439 // Local variable that has address taken but not escape.
4440 // It needs to be live beyond its lexical scope. So we
4441 // create a top-level declaration for it.
4442 // No need to do it if it is already in the top level.
4443 Block
* top_block
= function_
->func_value()->block();
4444 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4446 Variable
* var
= no
->var_value();
4447 Temporary_statement
* ts
=
4448 Statement::make_temporary(var
->type(), NULL
, var
->location());
4449 ts
->set_is_address_taken();
4450 top_block
->add_statement_at_front(ts
);
4451 var
->set_toplevel_decl(ts
);
4455 go_assert(!no
->var_value()->has_pre_init());
4457 return TRAVERSE_SKIP_COMPONENTS
;
4460 // Flatten the body of a function. Record the function while flattening it,
4461 // so that we can pass it down when flattening an expression.
4464 Flatten::function(Named_object
* no
)
4466 go_assert(this->function_
== NULL
);
4467 this->function_
= no
;
4468 int t
= no
->func_value()->traverse(this);
4469 this->function_
= NULL
;
4471 if (t
== TRAVERSE_EXIT
)
4473 return TRAVERSE_SKIP_COMPONENTS
;
4476 // Flatten statement parse trees.
4479 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4481 // Because we explicitly traverse the statement's contents
4482 // ourselves, we want to skip block statements here. There is
4483 // nothing to flatten in a block statement.
4484 if (sorig
->is_block_statement())
4485 return TRAVERSE_CONTINUE
;
4487 Statement_inserter
hold_inserter(this->inserter_
);
4488 this->inserter_
= Statement_inserter(block
, pindex
);
4490 // Flatten the expressions first.
4491 int t
= sorig
->traverse_contents(this);
4492 if (t
== TRAVERSE_EXIT
)
4494 this->inserter_
= hold_inserter
;
4498 // Keep flattening until nothing changes.
4499 Statement
* s
= sorig
;
4502 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4507 t
= s
->traverse_contents(this);
4508 if (t
== TRAVERSE_EXIT
)
4510 this->inserter_
= hold_inserter
;
4516 block
->replace_statement(*pindex
, s
);
4518 this->inserter_
= hold_inserter
;
4519 return TRAVERSE_SKIP_COMPONENTS
;
4522 // Flatten expression parse trees.
4525 Flatten::expression(Expression
** pexpr
)
4527 // Keep flattening until nothing changes.
4530 Expression
* e
= *pexpr
;
4531 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4532 return TRAVERSE_EXIT
;
4534 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4540 return TRAVERSE_SKIP_COMPONENTS
;
4546 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4548 Flatten
flatten(this, function
);
4549 block
->traverse(&flatten
);
4552 // Flatten an expression. INSERTER may be NULL, in which case the
4553 // expression had better not need to create any temporaries.
4556 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4559 Flatten
flatten(this, function
);
4560 if (inserter
!= NULL
)
4561 flatten
.set_inserter(inserter
);
4562 flatten
.expression(pexpr
);
4568 Flatten
flatten(this, NULL
);
4569 this->traverse(&flatten
);
4572 // Traversal to convert calls to the predeclared recover function to
4573 // pass in an argument indicating whether it can recover from a panic
4576 class Convert_recover
: public Traverse
4579 Convert_recover(Named_object
* arg
)
4580 : Traverse(traverse_expressions
),
4586 expression(Expression
**);
4589 // The argument to pass to the function.
4593 // Convert calls to recover.
4596 Convert_recover::expression(Expression
** pp
)
4598 Call_expression
* ce
= (*pp
)->call_expression();
4599 if (ce
!= NULL
&& ce
->is_recover_call())
4600 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4602 return TRAVERSE_CONTINUE
;
4605 // Traversal for build_recover_thunks.
4607 class Build_recover_thunks
: public Traverse
4610 Build_recover_thunks(Gogo
* gogo
)
4611 : Traverse(traverse_functions
),
4616 function(Named_object
*);
4620 can_recover_arg(Location
);
4626 // If this function calls recover, turn it into a thunk.
4629 Build_recover_thunks::function(Named_object
* orig_no
)
4631 Function
* orig_func
= orig_no
->func_value();
4632 if (!orig_func
->calls_recover()
4633 || orig_func
->is_recover_thunk()
4634 || orig_func
->has_recover_thunk())
4635 return TRAVERSE_CONTINUE
;
4637 Gogo
* gogo
= this->gogo_
;
4638 Location location
= orig_func
->location();
4643 Function_type
* orig_fntype
= orig_func
->type();
4644 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4645 std::string receiver_name
;
4646 if (orig_fntype
->is_method())
4648 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4649 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4651 receiver_name
= buf
;
4652 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4653 receiver
->location()));
4655 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4656 if (orig_params
!= NULL
&& !orig_params
->empty())
4658 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4659 p
!= orig_params
->end();
4662 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4664 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4668 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4670 std::string can_recover_name
= buf
;
4671 new_params
->push_back(Typed_identifier(can_recover_name
,
4672 Type::lookup_bool_type(),
4673 orig_fntype
->location()));
4675 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4676 Typed_identifier_list
* new_results
;
4677 if (orig_results
== NULL
|| orig_results
->empty())
4681 new_results
= new Typed_identifier_list();
4682 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4683 p
!= orig_results
->end();
4685 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4688 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4690 orig_fntype
->location());
4691 if (orig_fntype
->is_varargs())
4692 new_fntype
->set_is_varargs();
4695 if (orig_fntype
->is_method())
4696 rtype
= orig_fntype
->receiver()->type();
4697 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4698 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4700 Function
*new_func
= new_no
->func_value();
4701 if (orig_func
->enclosing() != NULL
)
4702 new_func
->set_enclosing(orig_func
->enclosing());
4704 // We build the code for the original function attached to the new
4705 // function, and then swap the original and new function bodies.
4706 // This means that existing references to the original function will
4707 // then refer to the new function. That makes this code a little
4708 // confusing, in that the reference to NEW_NO really refers to the
4709 // other function, not the one we are building.
4711 Expression
* closure
= NULL
;
4712 if (orig_func
->needs_closure())
4714 // For the new function we are creating, declare a new parameter
4715 // variable NEW_CLOSURE_NO and set it to be the closure variable
4716 // of the function. This will be set to the closure value
4717 // passed in by the caller. Then pass a reference to this
4718 // variable as the closure value when calling the original
4719 // function. In other words, simply pass the closure value
4720 // through the thunk we are creating.
4721 Named_object
* orig_closure_no
= orig_func
->closure_var();
4722 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4723 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4724 false, false, location
);
4725 new_var
->set_is_closure();
4726 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4728 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4730 new_func
->set_closure_var(new_closure_no
);
4731 closure
= Expression::make_var_reference(new_closure_no
, location
);
4734 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4736 Expression_list
* args
= new Expression_list();
4737 if (new_params
!= NULL
)
4739 // Note that we skip the last parameter, which is the boolean
4740 // indicating whether recover can succed.
4741 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4742 p
+ 1 != new_params
->end();
4745 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4746 go_assert(p_no
!= NULL
4747 && p_no
->is_variable()
4748 && p_no
->var_value()->is_parameter());
4749 args
->push_back(Expression::make_var_reference(p_no
, location
));
4752 args
->push_back(this->can_recover_arg(location
));
4754 gogo
->start_block(location
);
4756 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4758 // Any varargs call has already been lowered.
4759 call
->set_varargs_are_lowered();
4761 Statement
* s
= Statement::make_return_from_call(call
, location
);
4762 s
->determine_types();
4763 gogo
->add_statement(s
);
4765 Block
* b
= gogo
->finish_block(location
);
4767 gogo
->add_block(b
, location
);
4769 // Lower the call in case it returns multiple results.
4770 gogo
->lower_block(new_no
, b
);
4772 gogo
->finish_function(location
);
4774 // Swap the function bodies and types.
4775 new_func
->swap_for_recover(orig_func
);
4776 orig_func
->set_is_recover_thunk();
4777 new_func
->set_calls_recover();
4778 new_func
->set_has_recover_thunk();
4780 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4781 Bindings
* new_bindings
= new_func
->block()->bindings();
4782 if (orig_fntype
->is_method())
4784 // We changed the receiver to be a regular parameter. We have
4785 // to update the binding accordingly in both functions.
4786 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4787 go_assert(orig_rec_no
!= NULL
4788 && orig_rec_no
->is_variable()
4789 && !orig_rec_no
->var_value()->is_receiver());
4790 orig_rec_no
->var_value()->set_is_receiver();
4792 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4793 if (new_receiver_name
.empty())
4795 // Find the receiver. It was named "r.NNN" in
4796 // Gogo::start_function.
4797 for (Bindings::const_definitions_iterator p
=
4798 new_bindings
->begin_definitions();
4799 p
!= new_bindings
->end_definitions();
4802 const std::string
& pname((*p
)->name());
4803 if (pname
[0] == 'r' && pname
[1] == '.')
4805 new_receiver_name
= pname
;
4809 go_assert(!new_receiver_name
.empty());
4811 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4812 if (new_rec_no
== NULL
)
4813 go_assert(saw_errors());
4816 go_assert(new_rec_no
->is_variable()
4817 && new_rec_no
->var_value()->is_receiver());
4818 new_rec_no
->var_value()->set_is_not_receiver();
4822 // Because we flipped blocks but not types, the can_recover
4823 // parameter appears in the (now) old bindings as a parameter.
4824 // Change it to a local variable, whereupon it will be discarded.
4825 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4826 go_assert(can_recover_no
!= NULL
4827 && can_recover_no
->is_variable()
4828 && can_recover_no
->var_value()->is_parameter());
4829 orig_bindings
->remove_binding(can_recover_no
);
4831 // Add the can_recover argument to the (now) new bindings, and
4832 // attach it to any recover statements.
4833 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4834 false, true, false, location
);
4835 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4837 Convert_recover
convert_recover(can_recover_no
);
4838 new_func
->traverse(&convert_recover
);
4840 // Update the function pointers in any named results.
4841 new_func
->update_result_variables();
4842 orig_func
->update_result_variables();
4844 return TRAVERSE_CONTINUE
;
4847 // Return the expression to pass for the .can_recover parameter to the
4848 // new function. This indicates whether a call to recover may return
4849 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4852 Build_recover_thunks::can_recover_arg(Location location
)
4854 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4855 static Named_object
* can_recover
;
4856 if (can_recover
== NULL
)
4858 const Location bloc
= Linemap::predeclared_location();
4859 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4860 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4861 Type
* boolean_type
= Type::lookup_bool_type();
4862 Typed_identifier_list
* results
= new Typed_identifier_list();
4863 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4864 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4867 Named_object::make_function_declaration("runtime_canrecover",
4868 NULL
, fntype
, bloc
);
4869 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4872 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4873 Expression
* call
= Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS
,
4874 location
, 1, zexpr
);
4875 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4877 Expression_list
* args
= new Expression_list();
4878 args
->push_back(call
);
4880 Expression
* fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4881 return Expression::make_call(fn
, args
, false, location
);
4884 // Build thunks for functions which call recover. We build a new
4885 // function with an extra parameter, which is whether a call to
4886 // recover can succeed. We then move the body of this function to
4887 // that one. We then turn this function into a thunk which calls the
4888 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4889 // The function will be marked as not splitting the stack. This will
4890 // cooperate with the implementation of defer to make recover do the
4894 Gogo::build_recover_thunks()
4896 Build_recover_thunks
build_recover_thunks(this);
4897 this->traverse(&build_recover_thunks
);
4900 // Look for named types to see whether we need to create an interface
4903 class Build_method_tables
: public Traverse
4906 Build_method_tables(Gogo
* gogo
,
4907 const std::vector
<Interface_type
*>& interfaces
)
4908 : Traverse(traverse_types
),
4909 gogo_(gogo
), interfaces_(interfaces
)
4918 // A list of locally defined interfaces which have hidden methods.
4919 const std::vector
<Interface_type
*>& interfaces_
;
4922 // Build all required interface method tables for types. We need to
4923 // ensure that we have an interface method table for every interface
4924 // which has a hidden method, for every named type which implements
4925 // that interface. Normally we can just build interface method tables
4926 // as we need them. However, in some cases we can require an
4927 // interface method table for an interface defined in a different
4928 // package for a type defined in that package. If that interface and
4929 // type both use a hidden method, that is OK. However, we will not be
4930 // able to build that interface method table when we need it, because
4931 // the type's hidden method will be static. So we have to build it
4932 // here, and just refer it from other packages as needed.
4935 Gogo::build_interface_method_tables()
4940 std::vector
<Interface_type
*> hidden_interfaces
;
4941 hidden_interfaces
.reserve(this->interface_types_
.size());
4942 for (std::vector
<Interface_type
*>::const_iterator pi
=
4943 this->interface_types_
.begin();
4944 pi
!= this->interface_types_
.end();
4947 const Typed_identifier_list
* methods
= (*pi
)->methods();
4948 if (methods
== NULL
)
4950 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4951 pm
!= methods
->end();
4954 if (Gogo::is_hidden_name(pm
->name()))
4956 hidden_interfaces
.push_back(*pi
);
4962 if (!hidden_interfaces
.empty())
4964 // Now traverse the tree looking for all named types.
4965 Build_method_tables
bmt(this, hidden_interfaces
);
4966 this->traverse(&bmt
);
4969 // We no longer need the list of interfaces.
4971 this->interface_types_
.clear();
4974 // This is called for each type. For a named type, for each of the
4975 // interfaces with hidden methods that it implements, create the
4979 Build_method_tables::type(Type
* type
)
4981 Named_type
* nt
= type
->named_type();
4982 Struct_type
* st
= type
->struct_type();
4983 if (nt
!= NULL
|| st
!= NULL
)
4985 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4986 for (std::vector
<Interface_type
*>::const_iterator p
=
4987 this->interfaces_
.begin();
4988 p
!= this->interfaces_
.end();
4991 // We ask whether a pointer to the named type implements the
4992 // interface, because a pointer can implement more methods
4996 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4999 nt
->interface_method_table(*p
, false)->get_backend(&context
);
5000 nt
->interface_method_table(*p
, true)->get_backend(&context
);
5005 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
5008 st
->interface_method_table(*p
, false)->get_backend(&context
);
5009 st
->interface_method_table(*p
, true)->get_backend(&context
);
5014 return TRAVERSE_CONTINUE
;
5017 // Return an expression which allocates memory to hold values of type TYPE.
5020 Gogo::allocate_memory(Type
* type
, Location location
)
5022 Expression
* td
= Expression::make_type_descriptor(type
, location
);
5023 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
5026 // Traversal class used to check for return statements.
5028 class Check_return_statements_traverse
: public Traverse
5031 Check_return_statements_traverse()
5032 : Traverse(traverse_functions
)
5036 function(Named_object
*);
5039 // Check that a function has a return statement if it needs one.
5042 Check_return_statements_traverse::function(Named_object
* no
)
5044 Function
* func
= no
->func_value();
5045 const Function_type
* fntype
= func
->type();
5046 const Typed_identifier_list
* results
= fntype
->results();
5048 // We only need a return statement if there is a return value.
5049 if (results
== NULL
|| results
->empty())
5050 return TRAVERSE_CONTINUE
;
5052 if (func
->block()->may_fall_through())
5053 go_error_at(func
->block()->end_location(),
5054 "missing return at end of function");
5056 return TRAVERSE_CONTINUE
;
5059 // Check return statements.
5062 Gogo::check_return_statements()
5064 Check_return_statements_traverse traverse
;
5065 this->traverse(&traverse
);
5068 // Traversal class to decide whether a function body is less than the
5069 // inlining budget. This adjusts *available as it goes, and stops the
5070 // traversal if it goes negative.
5072 class Inline_within_budget
: public Traverse
5075 Inline_within_budget(int* available
)
5076 : Traverse(traverse_statements
5077 | traverse_expressions
),
5078 available_(available
)
5082 statement(Block
*, size_t*, Statement
*);
5085 expression(Expression
**);
5088 // Pointer to remaining budget.
5092 // Adjust the budget for the inlining cost of a statement.
5095 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
5097 if (*this->available_
< 0)
5098 return TRAVERSE_EXIT
;
5099 *this->available_
-= s
->inlining_cost();
5100 return TRAVERSE_CONTINUE
;
5103 // Adjust the budget for the inlining cost of an expression.
5106 Inline_within_budget::expression(Expression
** pexpr
)
5108 if (*this->available_
< 0)
5109 return TRAVERSE_EXIT
;
5110 *this->available_
-= (*pexpr
)->inlining_cost();
5111 return TRAVERSE_CONTINUE
;
5114 // Traversal class to find functions whose body should be exported for
5115 // inlining by other packages.
5117 class Mark_inline_candidates
: public Traverse
5120 Mark_inline_candidates(Unordered_set(Named_object
*)* marked
)
5121 : Traverse(traverse_functions
5123 marked_functions_(marked
)
5127 function(Named_object
*);
5133 // We traverse the function body trying to determine how expensive
5134 // it is for inlining. We start with a budget, and decrease that
5135 // budget for each statement and expression. If the budget goes
5136 // negative, we do not export the function body. The value of this
5137 // budget is a heuristic. In the usual GCC spirit, we could
5138 // consider setting this via a command line option.
5139 const int budget_heuristic
= 80;
5141 // Set of named objects that are marked as inline candidates.
5142 Unordered_set(Named_object
*)* marked_functions_
;
5145 // Mark a function if it is an inline candidate.
5148 Mark_inline_candidates::function(Named_object
* no
)
5150 Function
* func
= no
->func_value();
5151 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5152 return TRAVERSE_CONTINUE
;
5153 int budget
= budget_heuristic
;
5154 Inline_within_budget
iwb(&budget
);
5155 func
->block()->traverse(&iwb
);
5158 func
->set_export_for_inlining();
5159 this->marked_functions_
->insert(no
);
5161 return TRAVERSE_CONTINUE
;
5164 // Mark methods if they are inline candidates.
5167 Mark_inline_candidates::type(Type
* t
)
5169 Named_type
* nt
= t
->named_type();
5170 if (nt
== NULL
|| nt
->is_alias())
5171 return TRAVERSE_CONTINUE
;
5172 const Bindings
* methods
= nt
->local_methods();
5173 if (methods
== NULL
)
5174 return TRAVERSE_CONTINUE
;
5175 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
5176 p
!= methods
->end_definitions();
5179 Named_object
* no
= *p
;
5180 go_assert(no
->is_function());
5181 Function
*func
= no
->func_value();
5182 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5184 int budget
= budget_heuristic
;
5185 Inline_within_budget
iwb(&budget
);
5186 func
->block()->traverse(&iwb
);
5189 func
->set_export_for_inlining();
5190 this->marked_functions_
->insert(no
);
5193 return TRAVERSE_CONTINUE
;
5196 // Export identifiers as requested.
5204 // Mark any functions whose body should be exported for inlining by
5206 Unordered_set(Named_object
*) marked_functions
;
5207 Mark_inline_candidates
mic(&marked_functions
);
5208 this->traverse(&mic
);
5210 // For now we always stream to a section. Later we may want to
5211 // support streaming to a separate file.
5212 Stream_to_section
stream(this->backend());
5214 // Write out either the prefix or pkgpath depending on how we were
5217 std::string pkgpath
;
5218 if (this->pkgpath_from_option_
)
5219 pkgpath
= this->pkgpath_
;
5220 else if (this->prefix_from_option_
)
5221 prefix
= this->prefix_
;
5222 else if (this->is_main_package())
5227 std::string init_fn_name
;
5228 if (this->is_main_package())
5230 else if (this->need_init_fn_
)
5231 init_fn_name
= this->get_init_fn_name();
5233 init_fn_name
= this->dummy_init_fn_name();
5235 Export
exp(&stream
);
5236 exp
.register_builtin_types(this);
5237 exp
.export_globals(this->package_name(),
5243 this->imported_init_fns_
,
5244 this->package_
->bindings(),
5247 if (!this->c_header_
.empty() && !saw_errors())
5248 this->write_c_header();
5251 // Write the top level named struct types in C format to a C header
5252 // file. This is used when building the runtime package, to share
5253 // struct definitions between C and Go.
5256 Gogo::write_c_header()
5259 out
.open(this->c_header_
.c_str());
5262 go_error_at(Linemap::unknown_location(),
5263 "cannot open %s: %m", this->c_header_
.c_str());
5267 std::list
<Named_object
*> types
;
5268 Bindings
* top
= this->package_
->bindings();
5269 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
5270 p
!= top
->end_definitions();
5273 Named_object
* no
= *p
;
5275 // Skip names that start with underscore followed by something
5276 // other than an uppercase letter, as when compiling the runtime
5277 // package they are mostly types defined by mkrsysinfo.sh based
5278 // on the C system header files. We don't need to translate
5279 // types to C and back to Go. But do accept the special cases
5280 // _defer, _panic, and _type.
5281 std::string name
= Gogo::unpack_hidden_name(no
->name());
5283 && (name
[1] < 'A' || name
[1] > 'Z')
5284 && (name
!= "_defer" && name
!= "_panic" && name
!= "_type"))
5287 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
5288 types
.push_back(no
);
5290 && no
->const_value()->type()->integer_type() != NULL
5291 && !no
->const_value()->is_sink())
5293 Numeric_constant nc
;
5295 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
5296 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
5298 out
<< "#define " << no
->message_name() << ' ' << val
5304 std::vector
<const Named_object
*> written
;
5306 while (!types
.empty())
5308 Named_object
* no
= types
.front();
5311 std::vector
<const Named_object
*> requires
;
5312 std::vector
<const Named_object
*> declare
;
5313 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
5318 for (std::vector
<const Named_object
*>::const_iterator pr
5320 pr
!= requires
.end() && ok
;
5323 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5324 pt
!= types
.end() && ok
;
5334 // This should be impossible since the code parsed and
5339 types
.push_back(no
);
5343 for (std::vector
<const Named_object
*>::const_iterator pd
5345 pd
!= declare
.end();
5351 std::vector
<const Named_object
*> drequires
;
5352 std::vector
<const Named_object
*> ddeclare
;
5353 if (!(*pd
)->type_value()->struct_type()->
5354 can_write_to_c_header(&drequires
, &ddeclare
))
5358 for (std::vector
<const Named_object
*>::const_iterator pw
5360 pw
!= written
.end();
5372 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5373 written
.push_back(*pd
);
5378 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5379 no
->type_value()->struct_type()->write_to_c_header(out
);
5380 out
<< "};" << std::endl
;
5381 written
.push_back(no
);
5386 go_error_at(Linemap::unknown_location(),
5387 "error writing to %s: %m", this->c_header_
.c_str());
5390 // Find the blocks in order to convert named types defined in blocks.
5392 class Convert_named_types
: public Traverse
5395 Convert_named_types(Gogo
* gogo
)
5396 : Traverse(traverse_blocks
),
5402 block(Block
* block
);
5409 Convert_named_types::block(Block
* block
)
5411 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5412 return TRAVERSE_CONTINUE
;
5415 // Convert all named types to the backend representation. Since named
5416 // types can refer to other types, this needs to be done in the right
5417 // sequence, which is handled by Named_type::convert. Here we arrange
5418 // to call that for each named type.
5421 Gogo::convert_named_types()
5423 this->convert_named_types_in_bindings(this->globals_
);
5424 for (Packages::iterator p
= this->packages_
.begin();
5425 p
!= this->packages_
.end();
5428 Package
* package
= p
->second
;
5429 this->convert_named_types_in_bindings(package
->bindings());
5432 Convert_named_types
cnt(this);
5433 this->traverse(&cnt
);
5435 // Make all the builtin named types used for type descriptors, and
5436 // then convert them. They will only be written out if they are
5438 Type::make_type_descriptor_type();
5439 Type::make_type_descriptor_ptr_type();
5440 Function_type::make_function_type_descriptor_type();
5441 Pointer_type::make_pointer_type_descriptor_type();
5442 Struct_type::make_struct_type_descriptor_type();
5443 Array_type::make_array_type_descriptor_type();
5444 Array_type::make_slice_type_descriptor_type();
5445 Map_type::make_map_type_descriptor_type();
5446 Channel_type::make_chan_type_descriptor_type();
5447 Interface_type::make_interface_type_descriptor_type();
5448 Expression::make_func_descriptor_type();
5449 Type::convert_builtin_named_types(this);
5451 Runtime::convert_types(this);
5453 this->named_types_are_converted_
= true;
5455 Type::finish_pointer_types(this);
5458 // Convert all names types in a set of bindings.
5461 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5463 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5464 p
!= bindings
->end_definitions();
5467 if ((*p
)->is_type())
5468 (*p
)->type_value()->convert(this);
5473 debug_go_gogo(Gogo
* gogo
)
5482 std::cerr
<< "Packages:\n";
5483 for (Packages::const_iterator p
= this->packages_
.begin();
5484 p
!= this->packages_
.end();
5487 const char *tag
= " ";
5488 if (p
->second
== this->package_
)
5490 std::cerr
<< tag
<< "'" << p
->first
<< "' "
5491 << p
->second
->pkgpath() << " " << ((void*)p
->second
) << "\n";
5497 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5499 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5500 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5501 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5502 pragmas_(0), nested_functions_(0), is_sink_(false),
5503 results_are_named_(false), is_unnamed_type_stub_method_(false),
5504 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5505 calls_defer_retaddr_(false), is_type_specific_function_(false),
5506 in_unique_section_(false), export_for_inlining_(false),
5507 is_inline_only_(false), is_referenced_by_inline_(false),
5508 is_exported_by_linkname_(false)
5512 // Create the named result variables.
5515 Function::create_result_variables(Gogo
* gogo
)
5517 const Typed_identifier_list
* results
= this->type_
->results();
5518 if (results
== NULL
|| results
->empty())
5521 if (!results
->front().name().empty())
5522 this->results_are_named_
= true;
5524 this->results_
= new Results();
5525 this->results_
->reserve(results
->size());
5527 Block
* block
= this->block_
;
5529 for (Typed_identifier_list::const_iterator p
= results
->begin();
5530 p
!= results
->end();
5533 std::string name
= p
->name();
5534 if (name
.empty() || Gogo::is_sink_name(name
))
5536 static int result_counter
;
5538 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5540 name
= gogo
->pack_hidden_name(buf
, false);
5542 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5544 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5545 if (no
->is_result_variable())
5546 this->results_
->push_back(no
);
5549 static int dummy_result_count
;
5551 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5552 ++dummy_result_count
;
5553 name
= gogo
->pack_hidden_name(buf
, false);
5554 no
= block
->bindings()->add_result_variable(name
, result
);
5555 go_assert(no
->is_result_variable());
5556 this->results_
->push_back(no
);
5561 // Update the named result variables when cloning a function which
5565 Function::update_result_variables()
5567 if (this->results_
== NULL
)
5570 for (Results::iterator p
= this->results_
->begin();
5571 p
!= this->results_
->end();
5573 (*p
)->result_var_value()->set_function(this);
5576 // Whether this method should not be included in the type descriptor.
5579 Function::nointerface() const
5581 go_assert(this->is_method());
5582 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5585 // Record that this method should not be included in the type
5589 Function::set_nointerface()
5591 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5594 // Return the closure variable, creating it if necessary.
5597 Function::closure_var()
5599 if (this->closure_var_
== NULL
)
5601 go_assert(this->descriptor_
== NULL
);
5602 // We don't know the type of the variable yet. We add fields as
5604 Location loc
= this->type_
->location();
5605 Struct_field_list
* sfl
= new Struct_field_list
;
5606 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5607 struct_type
->set_is_struct_incomparable();
5608 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5609 NULL
, false, false, false, loc
);
5611 var
->set_is_closure();
5612 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5613 // Note that the new variable is not in any binding contour.
5615 return this->closure_var_
;
5618 // Set the type of the closure variable.
5621 Function::set_closure_type()
5623 if (this->closure_var_
== NULL
)
5625 Named_object
* closure
= this->closure_var_
;
5626 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5628 // The first field of a closure is always a pointer to the function
5630 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5631 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5634 unsigned int index
= 1;
5635 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5636 p
!= this->closure_fields_
.end();
5639 Named_object
* no
= p
->first
;
5641 snprintf(buf
, sizeof buf
, "%u", index
);
5642 std::string n
= no
->name() + buf
;
5644 if (no
->is_variable())
5645 var_type
= no
->var_value()->type();
5647 var_type
= no
->result_var_value()->type();
5648 Type
* field_type
= Type::make_pointer_type(var_type
);
5649 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5653 // Return whether this function is a method.
5656 Function::is_method() const
5658 return this->type_
->is_method();
5661 // Add a label definition.
5664 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5667 Label
* lnull
= NULL
;
5668 std::pair
<Labels::iterator
, bool> ins
=
5669 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5671 if (label_name
== "_")
5673 label
= Label::create_dummy_label();
5675 ins
.first
->second
= label
;
5677 else if (ins
.second
)
5679 // This is a new label.
5680 label
= new Label(label_name
);
5681 ins
.first
->second
= label
;
5685 // The label was already in the hash table.
5686 label
= ins
.first
->second
;
5687 if (label
->is_defined())
5689 go_error_at(location
, "label %qs already defined",
5690 Gogo::message_name(label_name
).c_str());
5691 go_inform(label
->location(), "previous definition of %qs was here",
5692 Gogo::message_name(label_name
).c_str());
5693 return new Label(label_name
);
5697 label
->define(location
, gogo
->bindings_snapshot(location
));
5699 // Issue any errors appropriate for any previous goto's to this
5701 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5702 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5705 (*p
)->check_goto_to(gogo
->current_block());
5706 label
->clear_refs();
5711 // Add a reference to a label.
5714 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5715 Location location
, bool issue_goto_errors
)
5717 Label
* lnull
= NULL
;
5718 std::pair
<Labels::iterator
, bool> ins
=
5719 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5723 // The label was already in the hash table.
5724 label
= ins
.first
->second
;
5728 go_assert(ins
.first
->second
== NULL
);
5729 label
= new Label(label_name
);
5730 ins
.first
->second
= label
;
5733 label
->set_is_used();
5735 if (issue_goto_errors
)
5737 Bindings_snapshot
* snapshot
= label
->snapshot();
5738 if (snapshot
!= NULL
)
5739 snapshot
->check_goto_from(gogo
->current_block(), location
);
5741 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5747 // Warn about labels that are defined but not used.
5750 Function::check_labels() const
5752 for (Labels::const_iterator p
= this->labels_
.begin();
5753 p
!= this->labels_
.end();
5756 Label
* label
= p
->second
;
5757 if (!label
->is_used())
5758 go_error_at(label
->location(), "label %qs defined and not used",
5759 Gogo::message_name(label
->name()).c_str());
5763 // Swap one function with another. This is used when building the
5764 // thunk we use to call a function which calls recover. It may not
5765 // work for any other case.
5768 Function::swap_for_recover(Function
*x
)
5770 go_assert(this->enclosing_
== x
->enclosing_
);
5771 std::swap(this->results_
, x
->results_
);
5772 std::swap(this->closure_var_
, x
->closure_var_
);
5773 std::swap(this->block_
, x
->block_
);
5774 go_assert(this->location_
== x
->location_
);
5775 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5776 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5779 // Traverse the tree.
5782 Function::traverse(Traverse
* traverse
)
5784 unsigned int traverse_mask
= traverse
->traverse_mask();
5787 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5790 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5791 return TRAVERSE_EXIT
;
5794 // FIXME: We should check traverse_functions here if nested
5795 // functions are stored in block bindings.
5796 if (this->block_
!= NULL
5798 & (Traverse::traverse_variables
5799 | Traverse::traverse_constants
5800 | Traverse::traverse_blocks
5801 | Traverse::traverse_statements
5802 | Traverse::traverse_expressions
5803 | Traverse::traverse_types
)) != 0)
5805 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5806 return TRAVERSE_EXIT
;
5809 return TRAVERSE_CONTINUE
;
5812 // Work out types for unspecified variables and constants.
5815 Function::determine_types()
5817 if (this->block_
!= NULL
)
5818 this->block_
->determine_types();
5821 // Return the function descriptor, the value you get when you refer to
5822 // the function in Go code without calling it.
5825 Function::descriptor(Gogo
*, Named_object
* no
)
5827 go_assert(!this->is_method());
5828 go_assert(this->closure_var_
== NULL
);
5829 if (this->descriptor_
== NULL
)
5830 this->descriptor_
= Expression::make_func_descriptor(no
);
5831 return this->descriptor_
;
5834 // Get a pointer to the variable representing the defer stack for this
5835 // function, making it if necessary. The value of the variable is set
5836 // by the runtime routines to true if the function is returning,
5837 // rather than panicing through. A pointer to this variable is used
5838 // as a marker for the functions on the defer stack associated with
5839 // this function. A function-specific variable permits inlining a
5840 // function which uses defer.
5843 Function::defer_stack(Location location
)
5845 if (this->defer_stack_
== NULL
)
5847 Type
* t
= Type::lookup_bool_type();
5848 Expression
* n
= Expression::make_boolean(false, location
);
5849 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5850 this->defer_stack_
->set_is_address_taken();
5852 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5854 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5857 // Export the function.
5860 Function::export_func(Export
* exp
, const Named_object
* no
) const
5862 Block
* block
= NULL
;
5863 if (this->export_for_inlining())
5864 block
= this->block_
;
5865 Function::export_func_with_type(exp
, no
, this->type_
, this->results_
,
5866 this->is_method() && this->nointerface(),
5867 this->asm_name(), block
, this->location_
);
5870 // Export a function with a type.
5873 Function::export_func_with_type(Export
* exp
, const Named_object
* no
,
5874 const Function_type
* fntype
,
5875 Function::Results
* result_vars
,
5876 bool nointerface
, const std::string
& asm_name
,
5877 Block
* block
, Location loc
)
5879 exp
->write_c_string("func ");
5883 go_assert(fntype
->is_method());
5884 exp
->write_c_string("/*nointerface*/ ");
5887 if (!asm_name
.empty())
5889 exp
->write_c_string("/*asm ");
5890 exp
->write_string(asm_name
);
5891 exp
->write_c_string(" */ ");
5894 if (fntype
->is_method())
5896 exp
->write_c_string("(");
5897 const Typed_identifier
* receiver
= fntype
->receiver();
5898 exp
->write_name(receiver
->name());
5899 exp
->write_escape(receiver
->note());
5900 exp
->write_c_string(" ");
5901 exp
->write_type(receiver
->type());
5902 exp
->write_c_string(") ");
5905 if (no
->package() != NULL
&& !fntype
->is_method())
5908 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
5909 exp
->write_c_string(buf
);
5912 const std::string
& name(no
->name());
5913 if (!Gogo::is_hidden_name(name
))
5914 exp
->write_string(name
);
5917 exp
->write_c_string(".");
5918 exp
->write_string(Gogo::unpack_hidden_name(name
));
5921 exp
->write_c_string(" (");
5922 const Typed_identifier_list
* parameters
= fntype
->parameters();
5923 if (parameters
!= NULL
)
5926 bool is_varargs
= fntype
->is_varargs();
5928 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5929 p
!= parameters
->end();
5935 exp
->write_c_string(", ");
5936 exp
->write_name(p
->name());
5937 exp
->write_escape(p
->note());
5938 exp
->write_c_string(" ");
5939 if (!is_varargs
|| p
+ 1 != parameters
->end())
5940 exp
->write_type(p
->type());
5943 exp
->write_c_string("...");
5944 exp
->write_type(p
->type()->array_type()->element_type());
5948 exp
->write_c_string(")");
5950 const Typed_identifier_list
* result_decls
= fntype
->results();
5951 if (result_decls
!= NULL
)
5953 if (result_decls
->size() == 1
5954 && result_decls
->begin()->name().empty()
5957 exp
->write_c_string(" ");
5958 exp
->write_type(result_decls
->begin()->type());
5962 exp
->write_c_string(" (");
5964 Results::const_iterator pr
;
5965 if (result_vars
!= NULL
)
5966 pr
= result_vars
->begin();
5967 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
5968 pd
!= result_decls
->end();
5974 exp
->write_c_string(", ");
5975 // We only use pr->name, which may be artificial, if
5976 // need it for inlining.
5977 if (block
== NULL
|| result_vars
== NULL
)
5978 exp
->write_name(pd
->name());
5980 exp
->write_name((*pr
)->name());
5981 exp
->write_escape(pd
->note());
5982 exp
->write_c_string(" ");
5983 exp
->write_type(pd
->type());
5984 if (result_vars
!= NULL
)
5987 if (result_vars
!= NULL
)
5988 go_assert(pr
== result_vars
->end());
5989 exp
->write_c_string(")");
5994 exp
->write_c_string("\n");
5998 if (fntype
->is_method())
6001 Export_function_body
efb(exp
, indent
);
6004 efb
.write_c_string("// ");
6005 efb
.write_string(Linemap::location_to_file(block
->start_location()));
6006 efb
.write_char(':');
6008 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
6009 efb
.write_c_string(buf
);
6010 efb
.write_char('\n');
6011 block
->export_block(&efb
);
6013 const std::string
& body(efb
.body());
6015 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
6016 static_cast<unsigned long>(body
.length()));
6017 exp
->write_c_string(buf
);
6019 exp
->write_string(body
);
6023 // Import a function.
6026 Function::import_func(Import
* imp
, std::string
* pname
,
6027 Package
** ppkg
, bool* pis_exported
,
6028 Typed_identifier
** preceiver
,
6029 Typed_identifier_list
** pparameters
,
6030 Typed_identifier_list
** presults
,
6033 std::string
* asm_name
,
6036 imp
->require_c_string("func ");
6038 *nointerface
= false;
6039 while (imp
->match_c_string("/*"))
6042 if (imp
->match_c_string("nointerface"))
6044 imp
->require_c_string("nointerface*/ ");
6045 *nointerface
= true;
6047 else if (imp
->match_c_string("asm"))
6049 imp
->require_c_string("asm ");
6050 *asm_name
= imp
->read_identifier();
6051 imp
->require_c_string(" */ ");
6055 go_error_at(imp
->location(),
6056 "import error at %d: unrecognized function comment",
6064 // Only a method can be nointerface.
6065 go_assert(imp
->peek_char() == '(');
6069 if (imp
->peek_char() == '(')
6071 imp
->require_c_string("(");
6072 std::string name
= imp
->read_name();
6073 std::string escape_note
= imp
->read_escape();
6074 imp
->require_c_string(" ");
6075 Type
* rtype
= imp
->read_type();
6076 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
6077 (*preceiver
)->set_note(escape_note
);
6078 imp
->require_c_string(") ");
6081 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
6083 go_error_at(imp
->location(),
6084 "import error at %d: bad function name in export data",
6089 Typed_identifier_list
* parameters
;
6090 *is_varargs
= false;
6091 imp
->require_c_string(" (");
6092 if (imp
->peek_char() == ')')
6096 parameters
= new Typed_identifier_list();
6099 std::string name
= imp
->read_name();
6100 std::string escape_note
= imp
->read_escape();
6101 imp
->require_c_string(" ");
6103 if (imp
->match_c_string("..."))
6109 Type
* ptype
= imp
->read_type();
6111 ptype
= Type::make_array_type(ptype
, NULL
);
6112 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
6113 t
.set_note(escape_note
);
6114 parameters
->push_back(t
);
6115 if (imp
->peek_char() != ',')
6117 go_assert(!*is_varargs
);
6118 imp
->require_c_string(", ");
6121 imp
->require_c_string(")");
6122 *pparameters
= parameters
;
6124 Typed_identifier_list
* results
;
6125 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
6129 results
= new Typed_identifier_list();
6130 imp
->require_c_string(" ");
6131 if (imp
->peek_char() != '(')
6133 Type
* rtype
= imp
->read_type();
6134 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
6138 imp
->require_c_string("(");
6141 std::string name
= imp
->read_name();
6142 std::string note
= imp
->read_escape();
6143 imp
->require_c_string(" ");
6144 Type
* rtype
= imp
->read_type();
6145 Typed_identifier t
= Typed_identifier(name
, rtype
,
6148 results
->push_back(t
);
6149 if (imp
->peek_char() != ',')
6151 imp
->require_c_string(", ");
6153 imp
->require_c_string(")");
6156 *presults
= results
;
6158 if (!imp
->match_c_string(" <inl:"))
6160 imp
->require_semicolon_if_old_version();
6161 imp
->require_c_string("\n");
6166 imp
->require_c_string(" <inl:");
6171 c
= imp
->peek_char();
6172 if (c
< '0' || c
> '9')
6177 imp
->require_c_string(">\n");
6181 long llen
= strtol(lenstr
.c_str(), &end
, 10);
6184 || (llen
== LONG_MAX
&& errno
== ERANGE
))
6186 go_error_at(imp
->location(), "invalid inline function length %s",
6191 imp
->read(static_cast<size_t>(llen
), body
);
6197 // Get the backend name.
6200 Function::backend_name(Gogo
* gogo
, Named_object
* no
, Backend_name
*bname
)
6202 if (!this->asm_name_
.empty())
6203 bname
->set_asm_name(this->asm_name_
);
6204 else if (no
->package() == NULL
&& no
->name() == gogo
->get_init_fn_name())
6206 // These names appear in the export data and are used
6207 // directly in the assembler code. If we change this here
6208 // we need to change Gogo::init_imports.
6209 bname
->set_asm_name(no
->name());
6211 else if (this->enclosing_
!= NULL
)
6213 // Rewrite the nested name to use the enclosing function name.
6214 // We don't do this earlier because we just store simple names
6215 // in a Named_object, not Backend_names.
6217 // The name was set by nested_function_name, which always
6218 // appends ..funcNNN. We want that to be our suffix.
6219 size_t pos
= no
->name().find("..func");
6220 go_assert(pos
!= std::string::npos
);
6222 Named_object
* enclosing
= this->enclosing_
;
6225 Named_object
* parent
= enclosing
->func_value()->enclosing();
6232 if (enclosing
->func_value()->type()->is_method())
6233 rtype
= enclosing
->func_value()->type()->receiver()->type();
6234 gogo
->function_backend_name(enclosing
->name(), enclosing
->package(),
6236 bname
->append_suffix(no
->name().substr(pos
));
6241 if (this->type_
->is_method())
6242 rtype
= this->type_
->receiver()->type();
6243 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6247 // Get the backend representation.
6250 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6252 if (this->fndecl_
== NULL
)
6254 unsigned int flags
= 0;
6255 if (no
->package() != NULL
)
6257 // Functions defined in other packages must be visible.
6258 flags
|= Backend::function_is_visible
;
6260 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
6262 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
6263 && !this->type_
->is_method())
6265 else if (no
->name() == gogo
->get_init_fn_name())
6266 flags
|= Backend::function_is_visible
;
6267 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
6268 && gogo
->is_main_package())
6269 flags
|= Backend::function_is_visible
;
6270 // Methods have to be public even if they are hidden because
6271 // they can be pulled into type descriptors when using
6272 // anonymous fields.
6273 else if (!Gogo::is_hidden_name(no
->name())
6274 || this->type_
->is_method())
6276 if (!this->is_unnamed_type_stub_method_
)
6277 flags
|= Backend::function_is_visible
;
6280 if (!this->asm_name_
.empty())
6282 // If an assembler name is explicitly specified, there must
6283 // be some reason to refer to the symbol from a different
6285 flags
|= Backend::function_is_visible
;
6288 // If an inline body refers to this function, then it
6289 // needs to be visible in the symbol table.
6290 if (this->is_referenced_by_inline_
)
6291 flags
|= Backend::function_is_visible
;
6293 // A go:linkname directive can be used to force a function to be
6295 if (this->is_exported_by_linkname_
)
6296 flags
|= Backend::function_is_visible
;
6298 // If a function calls the predeclared recover function, we
6299 // can't inline it, because recover behaves differently in a
6300 // function passed directly to defer. If this is a recover
6301 // thunk that we built to test whether a function can be
6302 // recovered, we can't inline it, because that will mess up
6303 // our return address comparison.
6304 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
6306 // If a function calls __go_set_defer_retaddr, then mark it as
6307 // uninlinable. This prevents the GCC backend from splitting
6308 // the function; splitting the function is a bad idea because we
6309 // want the return address label to be in the same function as
6311 if (this->calls_defer_retaddr_
)
6312 is_inlinable
= false;
6314 // Check the //go:noinline compiler directive.
6315 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
6316 is_inlinable
= false;
6319 flags
|= Backend::function_is_inlinable
;
6321 // If this is a thunk created to call a function which calls
6322 // the predeclared recover function, we need to disable
6323 // stack splitting for the thunk.
6324 bool disable_split_stack
= this->is_recover_thunk_
;
6326 // Check the //go:nosplit compiler directive.
6327 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
6328 disable_split_stack
= true;
6330 if (disable_split_stack
)
6331 flags
|= Backend::function_no_split_stack
;
6333 // This should go into a unique section if that has been
6334 // requested elsewhere, or if this is a nointerface function.
6335 // We want to put a nointerface function into a unique section
6336 // because there is a good chance that the linker garbage
6337 // collection can discard it.
6338 if (this->in_unique_section_
6339 || (this->is_method() && this->nointerface()))
6340 flags
|= Backend::function_in_unique_section
;
6342 if (this->is_inline_only_
)
6343 flags
|= Backend::function_only_inline
;
6345 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
6348 this->backend_name(gogo
, no
, &bname
);
6350 this->fndecl_
= gogo
->backend()->function(functype
,
6352 bname
.optional_asm_name(),
6356 return this->fndecl_
;
6359 // Get the backend name.
6362 Function_declaration::backend_name(Gogo
* gogo
, Named_object
* no
,
6363 Backend_name
* bname
)
6365 if (!this->asm_name_
.empty())
6366 bname
->set_asm_name(this->asm_name_
);
6370 if (this->fntype_
->is_method())
6371 rtype
= this->fntype_
->receiver()->type();
6372 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6376 // Get the backend representation.
6379 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6381 if (this->fndecl_
== NULL
)
6383 unsigned int flags
=
6384 (Backend::function_is_visible
6385 | Backend::function_is_declaration
6386 | Backend::function_is_inlinable
);
6388 // Let Go code use an asm declaration to pick up a builtin
6390 if (!this->asm_name_
.empty())
6392 Bfunction
* builtin_decl
=
6393 gogo
->backend()->lookup_builtin(this->asm_name_
);
6394 if (builtin_decl
!= NULL
)
6396 this->fndecl_
= builtin_decl
;
6397 return this->fndecl_
;
6400 if (this->asm_name_
== "runtime.gopanic"
6401 || this->asm_name_
.compare(0, 13, "runtime.panic") == 0
6402 || this->asm_name_
.compare(0, 15, "runtime.goPanic") == 0
6403 || this->asm_name_
== "runtime.block")
6404 flags
|= Backend::function_does_not_return
;
6407 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
6410 this->backend_name(gogo
, no
, &bname
);
6412 this->fndecl_
= gogo
->backend()->function(functype
,
6414 bname
.optional_asm_name(),
6419 return this->fndecl_
;
6422 // Build the descriptor for a function declaration. This won't
6423 // necessarily happen if the package has just a declaration for the
6424 // function and no other reference to it, but we may still need the
6425 // descriptor for references from other packages.
6427 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
6429 if (this->descriptor_
!= NULL
)
6431 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6432 this->descriptor_
->get_backend(&context
);
6436 // Check that the types used in this declaration's signature are defined.
6437 // Reports errors for any undefined type.
6440 Function_declaration::check_types() const
6442 // Calling Type::base will give errors for any undefined types.
6443 Function_type
* fntype
= this->type();
6444 if (fntype
->receiver() != NULL
)
6445 fntype
->receiver()->type()->base();
6446 if (fntype
->parameters() != NULL
)
6448 const Typed_identifier_list
* params
= fntype
->parameters();
6449 for (Typed_identifier_list::const_iterator p
= params
->begin();
6456 // Return the function's decl after it has been built.
6459 Function::get_decl() const
6461 go_assert(this->fndecl_
!= NULL
);
6462 return this->fndecl_
;
6465 // Build the backend representation for the function code.
6468 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6470 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6472 // A list of parameter variables for this function.
6473 std::vector
<Bvariable
*> param_vars
;
6475 // Variables that need to be declared for this function and their
6477 std::vector
<Bvariable
*> vars
;
6478 std::vector
<Expression
*> var_inits
;
6479 std::vector
<Statement
*> var_decls_stmts
;
6480 for (Bindings::const_definitions_iterator p
=
6481 this->block_
->bindings()->begin_definitions();
6482 p
!= this->block_
->bindings()->end_definitions();
6485 Location loc
= (*p
)->location();
6486 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6488 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6489 Bvariable
* parm_bvar
= bvar
;
6491 // We always pass the receiver to a method as a pointer. If
6492 // the receiver is declared as a non-pointer type, then we
6493 // copy the value into a local variable. For direct interface
6494 // type we pack the pointer into the type.
6495 if ((*p
)->var_value()->is_receiver()
6496 && (*p
)->var_value()->type()->points_to() == NULL
)
6498 std::string name
= (*p
)->name() + ".pointer";
6499 Type
* var_type
= (*p
)->var_value()->type();
6500 Variable
* parm_var
=
6501 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6503 Named_object
* parm_no
=
6504 Named_object::make_variable(name
, NULL
, parm_var
);
6505 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6507 vars
.push_back(bvar
);
6509 Expression
* parm_ref
=
6510 Expression::make_var_reference(parm_no
, loc
);
6511 Type
* recv_type
= (*p
)->var_value()->type();
6512 if (recv_type
->is_direct_iface_type())
6513 parm_ref
= Expression::pack_direct_iface(recv_type
, parm_ref
, loc
);
6516 Expression::make_dereference(parm_ref
,
6517 Expression::NIL_CHECK_NEEDED
,
6519 if ((*p
)->var_value()->is_in_heap())
6520 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6521 var_inits
.push_back(parm_ref
);
6523 else if ((*p
)->var_value()->is_in_heap())
6525 // If we take the address of a parameter, then we need
6526 // to copy it into the heap.
6527 std::string parm_name
= (*p
)->name() + ".param";
6528 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6529 false, true, false, loc
);
6530 Named_object
* parm_no
=
6531 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6532 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6534 vars
.push_back(bvar
);
6535 Expression
* var_ref
=
6536 Expression::make_var_reference(parm_no
, loc
);
6537 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6538 var_inits
.push_back(var_ref
);
6540 param_vars
.push_back(parm_bvar
);
6542 else if ((*p
)->is_result_variable())
6544 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6546 Type
* type
= (*p
)->result_var_value()->type();
6548 if (!(*p
)->result_var_value()->is_in_heap())
6550 Btype
* btype
= type
->get_backend(gogo
);
6551 Bexpression
* binit
= gogo
->backend()->zero_expression(btype
);
6552 init
= Expression::make_backend(binit
, type
, loc
);
6555 init
= Expression::make_allocation(type
, loc
);
6557 vars
.push_back(bvar
);
6558 var_inits
.push_back(init
);
6560 else if (this->defer_stack_
!= NULL
6561 && (*p
)->is_variable()
6562 && (*p
)->var_value()->is_non_escaping_address_taken()
6563 && !(*p
)->var_value()->is_in_heap())
6565 // Local variable captured by deferred closure needs to be live
6566 // until the end of the function. We create a top-level
6567 // declaration for it.
6568 // TODO: we don't need to do this if the variable is not captured
6569 // by the defer closure. There is no easy way to check it here,
6570 // so we do this for all address-taken variables for now.
6571 Variable
* var
= (*p
)->var_value();
6572 Temporary_statement
* ts
=
6573 Statement::make_temporary(var
->type(), NULL
, var
->location());
6574 ts
->set_is_address_taken();
6575 var
->set_toplevel_decl(ts
);
6576 var_decls_stmts
.push_back(ts
);
6579 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6581 go_assert(saw_errors());
6585 // If we need a closure variable, make sure to create it.
6586 // It gets installed in the function as a side effect of creation.
6587 if (this->closure_var_
!= NULL
)
6589 go_assert(this->closure_var_
->var_value()->is_closure());
6590 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6593 if (this->block_
!= NULL
)
6595 // Declare variables if necessary.
6596 Bblock
* var_decls
= NULL
;
6597 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6598 Bstatement
* defer_init
= NULL
;
6599 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6602 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6603 this->block_
->start_location(),
6604 this->block_
->end_location());
6606 if (this->defer_stack_
!= NULL
)
6608 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6610 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6611 var_decls_bstmt_list
.push_back(defer_init
);
6612 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6613 p
!= var_decls_stmts
.end();
6616 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6617 var_decls_bstmt_list
.push_back(bstmt
);
6622 // Build the backend representation for all the statements in the
6624 Translate_context
bcontext(gogo
, named_function
, NULL
, NULL
);
6625 Bblock
* code_block
= this->block_
->get_backend(&bcontext
);
6627 // Initialize variables if necessary.
6628 Translate_context
icontext(gogo
, named_function
, this->block_
,
6630 std::vector
<Bstatement
*> init
;
6631 go_assert(vars
.size() == var_inits
.size());
6632 for (size_t i
= 0; i
< vars
.size(); ++i
)
6634 Bexpression
* binit
= var_inits
[i
]->get_backend(&icontext
);
6635 Bstatement
* init_stmt
=
6636 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6638 init
.push_back(init_stmt
);
6640 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6642 // Initialize all variables before executing this code block.
6643 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6644 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6646 // If we have a defer stack, initialize it at the start of a
6648 Bstatement
* except
= NULL
;
6649 Bstatement
* fini
= NULL
;
6650 if (defer_init
!= NULL
)
6652 // Clean up the defer stack when we leave the function.
6653 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6655 // Wrap the code for this function in an exception handler to handle
6658 gogo
->backend()->exception_handler_statement(code_stmt
,
6663 // Stick the code into the block we built for the receiver, if
6665 if (var_decls
!= NULL
)
6667 var_decls_bstmt_list
.push_back(code_stmt
);
6668 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6669 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6672 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6674 go_assert(saw_errors());
6679 // If we created a descriptor for the function, make sure we emit it.
6680 if (this->descriptor_
!= NULL
)
6682 Translate_context
dcontext(gogo
, NULL
, NULL
, NULL
);
6683 this->descriptor_
->get_backend(&dcontext
);
6687 // Build the wrappers around function code needed if the function has
6688 // any defer statements. This sets *EXCEPT to an exception handler
6689 // and *FINI to a finally handler.
6692 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6693 Bstatement
** except
, Bstatement
** fini
)
6695 Location end_loc
= this->block_
->end_location();
6697 // Add an exception handler. This is used if a panic occurs. Its
6698 // purpose is to stop the stack unwinding if a deferred function
6699 // calls recover. There are more details in
6700 // libgo/runtime/go-unwind.c.
6702 std::vector
<Bstatement
*> stmts
;
6703 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6704 this->defer_stack(end_loc
));
6705 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6706 Bexpression
* defer
= call
->get_backend(&context
);
6707 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6709 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6710 if (ret_bstmt
!= NULL
)
6711 stmts
.push_back(ret_bstmt
);
6713 go_assert(*except
== NULL
);
6714 *except
= gogo
->backend()->statement_list(stmts
);
6716 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6717 this->defer_stack(end_loc
));
6718 defer
= call
->get_backend(&context
);
6720 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
6721 this->defer_stack(end_loc
));
6722 Bexpression
* undefer
= call
->get_backend(&context
);
6723 Bstatement
* function_defer
=
6724 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6726 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6727 if (this->type_
->results() != NULL
6728 && !this->type_
->results()->empty()
6729 && !this->type_
->results()->front().name().empty())
6731 // If the result variables are named, and we are returning from
6732 // this function rather than panicing through it, we need to
6733 // return them again, because they might have been changed by a
6734 // defer function. The runtime routines set the defer_stack
6735 // variable to true if we are returning from this function.
6737 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6738 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6740 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6742 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6743 Bexpression
* bref
= ref
->get_backend(&context
);
6744 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6745 NULL
, bref
, ret
, NULL
,
6747 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6750 go_assert(*fini
== NULL
);
6751 *fini
= gogo
->backend()->statement_list(stmts
);
6754 // Return the statement that assigns values to this function's result struct.
6757 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6758 Location location
) const
6760 const Typed_identifier_list
* results
= this->type_
->results();
6761 if (results
== NULL
|| results
->empty())
6764 go_assert(this->results_
!= NULL
);
6765 if (this->results_
->size() != results
->size())
6767 go_assert(saw_errors());
6768 return gogo
->backend()->error_statement();
6771 std::vector
<Bexpression
*> vals(results
->size());
6772 for (size_t i
= 0; i
< vals
.size(); ++i
)
6774 Named_object
* no
= (*this->results_
)[i
];
6775 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6776 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6777 if (no
->result_var_value()->is_in_heap())
6779 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6780 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6784 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6789 Block::Block(Block
* enclosing
, Location location
)
6790 : enclosing_(enclosing
), statements_(),
6791 bindings_(new Bindings(enclosing
== NULL
6793 : enclosing
->bindings())),
6794 start_location_(location
),
6795 end_location_(Linemap::unknown_location())
6799 // Add a statement to a block.
6802 Block::add_statement(Statement
* statement
)
6804 this->statements_
.push_back(statement
);
6807 // Add a statement to the front of a block. This is slow but is only
6808 // used for reference counts of parameters.
6811 Block::add_statement_at_front(Statement
* statement
)
6813 this->statements_
.insert(this->statements_
.begin(), statement
);
6816 // Replace a statement in a block.
6819 Block::replace_statement(size_t index
, Statement
* s
)
6821 go_assert(index
< this->statements_
.size());
6822 this->statements_
[index
] = s
;
6825 // Add a statement before another statement.
6828 Block::insert_statement_before(size_t index
, Statement
* s
)
6830 go_assert(index
< this->statements_
.size());
6831 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6834 // Add a statement after another statement.
6837 Block::insert_statement_after(size_t index
, Statement
* s
)
6839 go_assert(index
< this->statements_
.size());
6840 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6843 // Traverse the tree.
6846 Block::traverse(Traverse
* traverse
)
6848 unsigned int traverse_mask
= traverse
->traverse_mask();
6850 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6852 int t
= traverse
->block(this);
6853 if (t
== TRAVERSE_EXIT
)
6854 return TRAVERSE_EXIT
;
6855 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6856 return TRAVERSE_CONTINUE
;
6860 & (Traverse::traverse_variables
6861 | Traverse::traverse_constants
6862 | Traverse::traverse_expressions
6863 | Traverse::traverse_types
)) != 0)
6865 const unsigned int e_or_t
= (Traverse::traverse_expressions
6866 | Traverse::traverse_types
);
6867 const unsigned int e_or_t_or_s
= (e_or_t
6868 | Traverse::traverse_statements
);
6869 for (Bindings::const_definitions_iterator pb
=
6870 this->bindings_
->begin_definitions();
6871 pb
!= this->bindings_
->end_definitions();
6874 int t
= TRAVERSE_CONTINUE
;
6875 switch ((*pb
)->classification())
6877 case Named_object::NAMED_OBJECT_CONST
:
6878 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
6879 t
= traverse
->constant(*pb
, false);
6880 if (t
== TRAVERSE_CONTINUE
6881 && (traverse_mask
& e_or_t
) != 0)
6883 Type
* tc
= (*pb
)->const_value()->type();
6885 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
6886 return TRAVERSE_EXIT
;
6887 t
= (*pb
)->const_value()->traverse_expression(traverse
);
6891 case Named_object::NAMED_OBJECT_VAR
:
6892 case Named_object::NAMED_OBJECT_RESULT_VAR
:
6893 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
6894 t
= traverse
->variable(*pb
);
6895 if (t
== TRAVERSE_CONTINUE
6896 && (traverse_mask
& e_or_t
) != 0)
6898 if ((*pb
)->is_result_variable()
6899 || (*pb
)->var_value()->has_type())
6901 Type
* tv
= ((*pb
)->is_variable()
6902 ? (*pb
)->var_value()->type()
6903 : (*pb
)->result_var_value()->type());
6905 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
6906 return TRAVERSE_EXIT
;
6909 if (t
== TRAVERSE_CONTINUE
6910 && (traverse_mask
& e_or_t_or_s
) != 0
6911 && (*pb
)->is_variable())
6912 t
= (*pb
)->var_value()->traverse_expression(traverse
,
6916 case Named_object::NAMED_OBJECT_FUNC
:
6917 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
6920 case Named_object::NAMED_OBJECT_TYPE
:
6921 if ((traverse_mask
& e_or_t
) != 0)
6922 t
= Type::traverse((*pb
)->type_value(), traverse
);
6925 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
6926 case Named_object::NAMED_OBJECT_UNKNOWN
:
6927 case Named_object::NAMED_OBJECT_ERRONEOUS
:
6930 case Named_object::NAMED_OBJECT_PACKAGE
:
6931 case Named_object::NAMED_OBJECT_SINK
:
6938 if (t
== TRAVERSE_EXIT
)
6939 return TRAVERSE_EXIT
;
6943 // No point in checking traverse_mask here--if we got here we always
6944 // want to walk the statements. The traversal can insert new
6945 // statements before or after the current statement. Inserting
6946 // statements before the current statement requires updating I via
6947 // the pointer; those statements will not be traversed. Any new
6948 // statements inserted after the current statement will be traversed
6950 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6952 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6953 return TRAVERSE_EXIT
;
6956 return TRAVERSE_CONTINUE
;
6959 // Work out types for unspecified variables and constants.
6962 Block::determine_types()
6964 for (Bindings::const_definitions_iterator pb
=
6965 this->bindings_
->begin_definitions();
6966 pb
!= this->bindings_
->end_definitions();
6969 if ((*pb
)->is_variable())
6970 (*pb
)->var_value()->determine_type();
6971 else if ((*pb
)->is_const())
6972 (*pb
)->const_value()->determine_type();
6975 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6976 ps
!= this->statements_
.end();
6978 (*ps
)->determine_types();
6981 // Return true if the statements in this block may fall through.
6984 Block::may_fall_through() const
6986 if (this->statements_
.empty())
6988 return this->statements_
.back()->may_fall_through();
6991 // Write export data for a block.
6994 Block::export_block(Export_function_body
* efb
)
6996 for (Block::iterator p
= this->begin();
7002 efb
->increment_indent();
7003 (*p
)->export_statement(efb
);
7004 efb
->decrement_indent();
7006 Location loc
= (*p
)->location();
7007 if ((*p
)->is_block_statement())
7009 // For a block we put the start location on the first brace
7010 // in Block_statement::do_export_statement. Here we put the
7011 // end location on the final brace.
7012 loc
= (*p
)->block_statement()->block()->end_location();
7015 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
7016 efb
->write_c_string(buf
);
7020 // Add exported block data to SET, reading from BODY starting at OFF.
7021 // Returns whether the import succeeded.
7024 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
7026 Location eloc
= ifb
->location();
7027 Location sloc
= loc
;
7028 const std::string
& body(ifb
->body());
7029 size_t off
= ifb
->off();
7030 while (off
< body
.length())
7032 int indent
= ifb
->indent();
7033 if (off
+ indent
>= body
.length())
7036 "invalid export data for %qs: insufficient indentation",
7037 ifb
->name().c_str());
7040 for (int i
= 0; i
< indent
- 1; i
++)
7042 if (body
[off
+ i
] != ' ')
7045 "invalid export data for %qs: bad indentation",
7046 ifb
->name().c_str());
7051 bool at_end
= false;
7052 if (body
[off
+ indent
- 1] == '}')
7054 else if (body
[off
+ indent
- 1] != ' ')
7057 "invalid export data for %qs: bad indentation",
7058 ifb
->name().c_str());
7064 size_t nl
= body
.find('\n', off
);
7065 if (nl
== std::string::npos
)
7067 go_error_at(eloc
, "invalid export data for %qs: missing newline",
7068 ifb
->name().c_str());
7072 size_t lineno_pos
= body
.find(" //", off
);
7073 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
7075 go_error_at(eloc
, "invalid export data for %qs: missing line number",
7076 ifb
->name().c_str());
7080 unsigned int lineno
= 0;
7081 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
7084 if (c
< '0' || c
> '9')
7087 "invalid export data for %qs: invalid line number",
7088 ifb
->name().c_str());
7091 lineno
= lineno
* 10 + c
- '0';
7094 ifb
->gogo()->linemap()->start_line(lineno
, 1);
7095 sloc
= ifb
->gogo()->linemap()->get_location(0);
7099 // An if statement can have an "else" following the "}", in
7100 // which case we want to leave the offset where it is, just
7101 // after the "}". We don't get the block ending location
7102 // quite right for if statements.
7103 if (body
.compare(off
, 6, " else ") != 0)
7109 Statement
* s
= Statement::import_statement(ifb
, sloc
);
7113 set
->add_statement(s
);
7115 size_t at
= ifb
->off();
7123 set
->set_end_location(sloc
);
7127 // Convert a block to the backend representation.
7130 Block::get_backend(Translate_context
* context
)
7132 Gogo
* gogo
= context
->gogo();
7133 Named_object
* function
= context
->function();
7134 std::vector
<Bvariable
*> vars
;
7135 vars
.reserve(this->bindings_
->size_definitions());
7136 for (Bindings::const_definitions_iterator pv
=
7137 this->bindings_
->begin_definitions();
7138 pv
!= this->bindings_
->end_definitions();
7141 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
7142 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
7145 go_assert(function
!= NULL
);
7146 Bfunction
* bfunction
=
7147 function
->func_value()->get_or_make_decl(gogo
, function
);
7148 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
7149 vars
, this->start_location_
,
7150 this->end_location_
);
7152 Translate_context
subcontext(gogo
, function
, this, ret
);
7153 std::vector
<Bstatement
*> bstatements
;
7154 bstatements
.reserve(this->statements_
.size());
7155 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
7156 p
!= this->statements_
.end();
7158 bstatements
.push_back((*p
)->get_backend(&subcontext
));
7160 context
->backend()->block_add_statements(ret
, bstatements
);
7165 // Class Bindings_snapshot.
7167 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
7168 : block_(b
), counts_(), location_(location
)
7172 this->counts_
.push_back(b
->bindings()->size_definitions());
7177 // Report errors appropriate for a goto from B to this.
7180 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
7183 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
7185 this->check_goto_defs(loc
, this->block_
,
7186 this->block_
->bindings()->size_definitions(),
7190 // Report errors appropriate for a goto from this to B.
7193 Bindings_snapshot::check_goto_to(const Block
* b
)
7196 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
7198 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
7199 b
->bindings()->size_definitions());
7202 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7203 // Return true if all is well, false if we reported an error. If this
7204 // returns true, it sets *PINDEX to the number of blocks BTO is above
7208 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
7209 const Block
* bto
, size_t* pindex
)
7211 // It is an error if BTO is not either BFROM or above BFROM.
7213 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
7217 go_error_at(loc
, "goto jumps into block");
7218 go_inform(bto
->start_location(), "goto target block starts here");
7226 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7227 // CFROM is the number of names defined at the point of the goto and
7228 // CTO is the number of names defined at the point of the label.
7231 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
7232 size_t cfrom
, size_t cto
)
7236 Bindings::const_definitions_iterator p
=
7237 block
->bindings()->begin_definitions();
7238 for (size_t i
= 0; i
< cfrom
; ++i
)
7240 go_assert(p
!= block
->bindings()->end_definitions());
7243 go_assert(p
!= block
->bindings()->end_definitions());
7245 for (; p
!= block
->bindings()->end_definitions(); ++p
)
7247 if ((*p
)->is_variable())
7249 std::string n
= (*p
)->message_name();
7250 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
7251 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
7257 // Class Function_declaration.
7259 // Whether this declares a method.
7262 Function_declaration::is_method() const
7264 return this->fntype_
->is_method();
7267 // Whether this method should not be included in the type descriptor.
7270 Function_declaration::nointerface() const
7272 go_assert(this->is_method());
7273 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
7276 // Record that this method should not be included in the type
7280 Function_declaration::set_nointerface()
7282 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
7285 // Import an inlinable function. This is used for an inlinable
7286 // function whose body is recorded in the export data. Parse the
7287 // export data into a Block and create a regular function using that
7288 // Block as its body. Redeclare this function declaration as the
7292 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
7294 go_assert(no
->func_declaration_value() == this);
7295 go_assert(no
->package() != NULL
);
7296 const std::string
& body(this->imported_body_
);
7297 go_assert(!body
.empty());
7299 // Read the "//FILE:LINE" comment starts the export data.
7302 if (this->is_method())
7305 for (; i
< indent
; i
++)
7307 if (body
.at(i
) != ' ')
7309 go_error_at(this->location_
,
7310 "invalid export body for %qs: bad initial indentation",
7311 no
->message_name().c_str());
7316 if (body
.substr(i
, 2) != "//")
7318 go_error_at(this->location_
,
7319 "invalid export body for %qs: missing file comment",
7320 no
->message_name().c_str());
7324 size_t colon
= body
.find(':', i
+ 2);
7325 size_t nl
= body
.find('\n', i
+ 2);
7326 if (nl
== std::string::npos
)
7328 go_error_at(this->location_
,
7329 "invalid export body for %qs: missing file name",
7330 no
->message_name().c_str());
7333 if (colon
== std::string::npos
|| nl
< colon
)
7335 go_error_at(this->location_
,
7336 "invalid export body for %qs: missing initial line number",
7337 no
->message_name().c_str());
7341 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
7342 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
7344 long linenol
= strtol(linestr
.c_str(), &end
, 10);
7347 go_error_at(this->location_
,
7348 "invalid export body for %qs: invalid initial line number",
7349 no
->message_name().c_str());
7352 unsigned int lineno
= static_cast<unsigned int>(linenol
);
7354 // Turn the file/line into a location.
7356 char* alc
= new char[file
.length() + 1];
7357 memcpy(alc
, file
.data(), file
.length());
7358 alc
[file
.length()] = '\0';
7359 gogo
->linemap()->start_file(alc
, lineno
);
7360 gogo
->linemap()->start_line(lineno
, 1);
7361 Location start_loc
= gogo
->linemap()->get_location(0);
7363 // Define the function with an outer block that declares the
7366 Function_type
* fntype
= this->fntype_
;
7368 Block
* outer
= new Block(NULL
, start_loc
);
7370 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
7371 fn
->set_is_inline_only();
7373 if (fntype
->is_method())
7375 if (this->nointerface())
7376 fn
->set_nointerface();
7377 const Typed_identifier
* receiver
= fntype
->receiver();
7378 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
7379 true, true, start_loc
);
7381 std::string rname
= receiver
->name();
7382 unsigned rcounter
= 0;
7384 // We need to give a nameless receiver a name to avoid having it
7385 // clash with some other nameless param. FIXME.
7386 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
7388 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
7391 const Typed_identifier_list
* params
= fntype
->parameters();
7392 bool is_varargs
= fntype
->is_varargs();
7393 unsigned pcounter
= 0;
7396 for (Typed_identifier_list::const_iterator p
= params
->begin();
7400 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
7402 if (is_varargs
&& p
+ 1 == params
->end())
7403 param
->set_is_varargs_parameter();
7405 std::string pname
= p
->name();
7407 // We need to give each nameless parameter a non-empty name to avoid
7408 // having it clash with some other nameless param. FIXME.
7409 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
7411 outer
->bindings()->add_variable(pname
, NULL
, param
);
7415 fn
->create_result_variables(gogo
);
7417 if (!fntype
->is_method())
7419 const Package
* package
= no
->package();
7420 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
7424 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
7425 go_assert(rtype
!= NULL
);
7426 no
= rtype
->add_method(no
->name(), fn
);
7427 const Package
* package
= rtype
->named_object()->package();
7428 package
->bindings()->add_method(no
);
7431 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
7433 if (!Block::import_block(outer
, &ifb
, start_loc
))
7436 gogo
->lower_block(no
, outer
);
7437 outer
->determine_types();
7439 gogo
->add_imported_inline_function(no
);
7442 // Return the function descriptor.
7445 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
7447 go_assert(!this->fntype_
->is_method());
7448 if (this->descriptor_
== NULL
)
7449 this->descriptor_
= Expression::make_func_descriptor(no
);
7450 return this->descriptor_
;
7455 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
7456 bool is_parameter
, bool is_receiver
,
7458 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
7459 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
7460 is_closure_(false), is_receiver_(is_receiver
),
7461 is_varargs_parameter_(false), is_global_sink_(false), is_used_(false),
7462 is_address_taken_(false), is_non_escaping_address_taken_(false),
7463 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
7464 type_from_init_tuple_(false), type_from_range_index_(false),
7465 type_from_range_value_(false), type_from_chan_element_(false),
7466 is_type_switch_var_(false), determined_type_(false),
7467 in_unique_section_(false), is_referenced_by_inline_(false),
7468 toplevel_decl_(NULL
)
7470 go_assert(type
!= NULL
|| init
!= NULL
);
7471 go_assert(!is_parameter
|| init
== NULL
);
7474 // Traverse the initializer expression.
7477 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7479 if (this->preinit_
!= NULL
)
7481 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7482 return TRAVERSE_EXIT
;
7484 if (this->init_
!= NULL
7486 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7489 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7490 return TRAVERSE_EXIT
;
7492 return TRAVERSE_CONTINUE
;
7495 // Lower the initialization expression after parsing is complete.
7498 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7499 Statement_inserter
* inserter
)
7501 Named_object
* dep
= gogo
->var_depends_on(this);
7502 if (dep
!= NULL
&& dep
->is_variable())
7503 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7505 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7509 // We will give an error elsewhere, this is just to prevent
7510 // an infinite loop.
7515 Statement_inserter global_inserter
;
7516 if (this->is_global_
)
7518 global_inserter
= Statement_inserter(gogo
, this);
7519 inserter
= &global_inserter
;
7522 gogo
->lower_expression(function
, inserter
, &this->init_
);
7524 this->seen_
= false;
7526 this->init_is_lowered_
= true;
7530 // Flatten the initialization expression after ordering evaluations.
7533 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7534 Statement_inserter
* inserter
)
7536 Named_object
* dep
= gogo
->var_depends_on(this);
7537 if (dep
!= NULL
&& dep
->is_variable())
7538 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7540 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7544 // We will give an error elsewhere, this is just to prevent
7545 // an infinite loop.
7550 Statement_inserter global_inserter
;
7551 if (this->is_global_
)
7553 global_inserter
= Statement_inserter(gogo
, this);
7554 inserter
= &global_inserter
;
7557 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7559 // If an interface conversion is needed, we need a temporary
7561 if (this->type_
!= NULL
7562 && !Type::are_identical(this->type_
, this->init_
->type(),
7563 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7565 && this->init_
->type()->interface_type() != NULL
7566 && !this->init_
->is_variable())
7568 Temporary_statement
* temp
=
7569 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7570 inserter
->insert(temp
);
7571 this->init_
= Expression::make_temporary_reference(temp
,
7575 this->seen_
= false;
7576 this->init_is_flattened_
= true;
7580 // Get the preinit block.
7583 Variable::preinit_block(Gogo
* gogo
)
7585 go_assert(this->is_global_
);
7586 if (this->preinit_
== NULL
)
7587 this->preinit_
= new Block(NULL
, this->location());
7589 // If a global variable has a preinitialization statement, then we
7590 // need to have an initialization function.
7591 gogo
->set_need_init_fn();
7593 return this->preinit_
;
7596 // Add a statement to be run before the initialization expression.
7599 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7601 Block
* b
= this->preinit_block(gogo
);
7602 b
->add_statement(s
);
7603 b
->set_end_location(s
->location());
7606 // Whether this variable has a type.
7609 Variable::has_type() const
7611 if (this->type_
== NULL
)
7614 // A variable created in a type switch case nil does not actually
7615 // have a type yet. It will be changed to use the initializer's
7616 // type in determine_type.
7617 if (this->is_type_switch_var_
7618 && this->type_
->is_nil_constant_as_type())
7624 // In an assignment which sets a variable to a tuple of EXPR, return
7625 // the type of the first element of the tuple.
7628 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7630 if (expr
->map_index_expression() != NULL
)
7632 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
7634 return Type::make_error_type();
7635 return mt
->val_type();
7637 else if (expr
->receive_expression() != NULL
)
7639 Expression
* channel
= expr
->receive_expression()->channel();
7640 Type
* channel_type
= channel
->type();
7641 if (channel_type
->channel_type() == NULL
)
7642 return Type::make_error_type();
7643 return channel_type
->channel_type()->element_type();
7648 go_error_at(this->location(), "invalid tuple definition");
7649 return Type::make_error_type();
7653 // Given EXPR used in a range clause, return either the index type or
7654 // the value type of the range, depending upon GET_INDEX_TYPE.
7657 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7658 bool report_error
) const
7660 Type
* t
= expr
->type();
7661 if (t
->array_type() != NULL
7662 || (t
->points_to() != NULL
7663 && t
->points_to()->array_type() != NULL
7664 && !t
->points_to()->is_slice_type()))
7667 return Type::lookup_integer_type("int");
7669 return t
->deref()->array_type()->element_type();
7671 else if (t
->is_string_type())
7674 return Type::lookup_integer_type("int");
7676 return Type::lookup_integer_type("int32");
7678 else if (t
->map_type() != NULL
)
7681 return t
->map_type()->key_type();
7683 return t
->map_type()->val_type();
7685 else if (t
->channel_type() != NULL
)
7688 return t
->channel_type()->element_type();
7692 go_error_at(this->location(),
7693 ("invalid definition of value variable "
7694 "for channel range"));
7695 return Type::make_error_type();
7701 go_error_at(this->location(), "invalid type for range clause");
7702 return Type::make_error_type();
7706 // EXPR should be a channel. Return the channel's element type.
7709 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7711 Type
* t
= expr
->type();
7712 if (t
->channel_type() != NULL
)
7713 return t
->channel_type()->element_type();
7717 go_error_at(this->location(), "expected channel");
7718 return Type::make_error_type();
7722 // Return the type of the Variable. This may be called before
7723 // Variable::determine_type is called, which means that we may need to
7724 // get the type from the initializer. FIXME: If we combine lowering
7725 // with type determination, then this should be unnecessary.
7730 // A variable in a type switch with a nil case will have the wrong
7731 // type here. This gets fixed up in determine_type, below.
7732 Type
* type
= this->type_
;
7733 Expression
* init
= this->init_
;
7734 if (this->is_type_switch_var_
7736 && this->type_
->is_nil_constant_as_type())
7738 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7739 go_assert(tge
!= NULL
);
7746 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7748 go_error_at(this->location_
, "variable initializer refers to itself");
7749 this->type_
= Type::make_error_type();
7758 else if (this->type_from_init_tuple_
)
7759 type
= this->type_from_tuple(init
, false);
7760 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7761 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7762 else if (this->type_from_chan_element_
)
7763 type
= this->type_from_chan_element(init
, false);
7766 go_assert(init
!= NULL
);
7767 type
= init
->type();
7768 go_assert(type
!= NULL
);
7770 // Variables should not have abstract types.
7771 if (type
->is_abstract())
7772 type
= type
->make_non_abstract_type();
7774 if (type
->is_void_type())
7775 type
= Type::make_error_type();
7778 this->seen_
= false;
7783 // Fetch the type from a const pointer, in which case it should have
7784 // been set already.
7787 Variable::type() const
7789 go_assert(this->type_
!= NULL
);
7793 // Set the type if necessary.
7796 Variable::determine_type()
7798 if (this->determined_type_
)
7800 this->determined_type_
= true;
7802 if (this->preinit_
!= NULL
)
7803 this->preinit_
->determine_types();
7805 // A variable in a type switch with a nil case will have the wrong
7806 // type here. It will have an initializer which is a type guard.
7807 // We want to initialize it to the value without the type guard, and
7808 // use the type of that value as well.
7809 if (this->is_type_switch_var_
7810 && this->type_
!= NULL
7811 && this->type_
->is_nil_constant_as_type())
7813 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7814 go_assert(tge
!= NULL
);
7816 this->init_
= tge
->expr();
7819 if (this->init_
== NULL
)
7820 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7821 else if (this->type_from_init_tuple_
)
7823 Expression
*init
= this->init_
;
7824 init
->determine_type_no_context();
7825 this->type_
= this->type_from_tuple(init
, true);
7828 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7830 Expression
* init
= this->init_
;
7831 init
->determine_type_no_context();
7832 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7836 else if (this->type_from_chan_element_
)
7838 Expression
* init
= this->init_
;
7839 init
->determine_type_no_context();
7840 this->type_
= this->type_from_chan_element(init
, true);
7845 Type_context
context(this->type_
, false);
7846 this->init_
->determine_type(&context
);
7847 if (this->type_
== NULL
)
7849 Type
* type
= this->init_
->type();
7850 go_assert(type
!= NULL
);
7851 if (type
->is_abstract())
7852 type
= type
->make_non_abstract_type();
7854 if (type
->is_void_type())
7856 go_error_at(this->location_
, "variable has no type");
7857 type
= Type::make_error_type();
7859 else if (type
->is_nil_type())
7861 go_error_at(this->location_
, "variable defined to nil type");
7862 type
= Type::make_error_type();
7864 else if (type
->is_call_multiple_result_type())
7866 go_error_at(this->location_
,
7867 "single variable set to multiple-value function call");
7868 type
= Type::make_error_type();
7876 // Get the initial value of a variable. This does not
7877 // consider whether the variable is in the heap--it returns the
7878 // initial value as though it were always stored in the stack.
7881 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7883 go_assert(this->preinit_
== NULL
);
7884 Location loc
= this->location();
7885 if (this->init_
== NULL
)
7887 go_assert(!this->is_parameter_
);
7888 if (this->is_global_
|| this->is_in_heap())
7890 Btype
* btype
= this->type()->get_backend(gogo
);
7891 return gogo
->backend()->zero_expression(btype
);
7895 Translate_context
context(gogo
, function
, NULL
, NULL
);
7896 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7897 return init
->get_backend(&context
);
7901 // Get the initial value of a variable when a block is required.
7902 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7905 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7906 Bvariable
* var_decl
)
7908 go_assert(this->preinit_
!= NULL
);
7910 // We want to add the variable assignment to the end of the preinit
7913 Translate_context
context(gogo
, function
, NULL
, NULL
);
7914 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7915 Bfunction
* bfunction
=
7916 function
->func_value()->get_or_make_decl(gogo
, function
);
7918 // It's possible to have pre-init statements without an initializer
7919 // if the pre-init statements set the variable.
7920 Bstatement
* decl_init
= NULL
;
7921 if (this->init_
!= NULL
)
7923 if (var_decl
== NULL
)
7925 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7926 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7931 Location loc
= this->location();
7932 Expression
* val_expr
=
7933 Expression::make_cast(this->type(), this->init_
, loc
);
7934 Bexpression
* val
= val_expr
->get_backend(&context
);
7935 Bexpression
* var_ref
=
7936 gogo
->backend()->var_expression(var_decl
, loc
);
7937 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7941 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7942 if (decl_init
!= NULL
)
7943 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
7947 // Export the variable
7950 Variable::export_var(Export
* exp
, const Named_object
* no
) const
7952 go_assert(this->is_global_
);
7953 exp
->write_c_string("var ");
7954 if (no
->package() != NULL
)
7957 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
7958 exp
->write_c_string(buf
);
7961 if (!Gogo::is_hidden_name(no
->name()))
7962 exp
->write_string(no
->name());
7965 exp
->write_c_string(".");
7966 exp
->write_string(Gogo::unpack_hidden_name(no
->name()));
7969 exp
->write_c_string(" ");
7970 exp
->write_type(this->type());
7971 exp
->write_c_string("\n");
7974 // Import a variable.
7977 Variable::import_var(Import
* imp
, std::string
* pname
, Package
** ppkg
,
7978 bool* pis_exported
, Type
** ptype
)
7980 imp
->require_c_string("var ");
7981 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
7983 go_error_at(imp
->location(),
7984 "import error at %d: bad variable name in export data",
7988 imp
->require_c_string(" ");
7989 *ptype
= imp
->read_type();
7990 imp
->require_semicolon_if_old_version();
7991 imp
->require_c_string("\n");
7995 // Convert a variable to the backend representation.
7998 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7999 const Package
* package
, const std::string
& name
)
8001 if (this->backend_
== NULL
)
8003 Backend
* backend
= gogo
->backend();
8004 Type
* type
= this->type_
;
8005 if (type
->is_error_type()
8006 || (type
->is_undefined()
8007 && (!this->is_global_
|| package
== NULL
)))
8008 this->backend_
= backend
->error_variable();
8011 bool is_parameter
= this->is_parameter_
;
8012 if (this->is_receiver_
&& type
->points_to() == NULL
)
8013 is_parameter
= false;
8014 if (this->is_in_heap())
8016 is_parameter
= false;
8017 type
= Type::make_pointer_type(type
);
8020 Btype
* btype
= type
->get_backend(gogo
);
8023 if (Map_type::is_zero_value(this))
8024 bvar
= Map_type::backend_zero_value(gogo
);
8025 else if (this->is_global_
)
8028 gogo
->global_var_backend_name(name
, package
, &bname
);
8030 bool is_hidden
= Gogo::is_hidden_name(name
);
8031 // Hack to export runtime.writeBarrier. FIXME.
8032 // This is because go:linkname doesn't work on variables.
8033 if (gogo
->compiling_runtime()
8034 && bname
.name() == "runtime.writeBarrier")
8037 // If an inline body refers to this variable, then it
8038 // needs to be visible in the symbol table.
8039 if (this->is_referenced_by_inline_
)
8042 // If this variable is in a different package, then it
8043 // can't be treated as a hidden symbol. This case can
8044 // arise when an inlined function refers to a
8045 // package-scope unexported variable.
8046 if (package
!= NULL
)
8049 // For some reason asm_name can't be the empty string
8050 // for global_variable, so we call asm_name rather than
8051 // optional_asm_name here. FIXME.
8053 bvar
= backend
->global_variable(bname
.name(),
8058 this->in_unique_section_
,
8061 else if (function
== NULL
)
8063 go_assert(saw_errors());
8064 bvar
= backend
->error_variable();
8068 const std::string n
= Gogo::unpack_hidden_name(name
);
8069 Bfunction
* bfunction
= function
->func_value()->get_decl();
8070 bool is_address_taken
= (this->is_non_escaping_address_taken_
8071 && !this->is_in_heap());
8072 if (this->is_closure())
8073 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
8075 else if (is_parameter
)
8076 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
8081 Bvariable
* bvar_decl
= NULL
;
8082 if (this->toplevel_decl_
!= NULL
)
8084 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
8085 bvar_decl
= this->toplevel_decl_
->temporary_statement()
8086 ->get_backend_variable(&context
);
8088 bvar
= backend
->local_variable(bfunction
, n
, btype
,
8094 this->backend_
= bvar
;
8097 return this->backend_
;
8100 // Class Result_variable.
8102 // Convert a result variable to the backend representation.
8105 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8106 const std::string
& name
)
8108 if (this->backend_
== NULL
)
8110 Backend
* backend
= gogo
->backend();
8111 Type
* type
= this->type_
;
8112 if (type
->is_error())
8113 this->backend_
= backend
->error_variable();
8116 if (this->is_in_heap())
8117 type
= Type::make_pointer_type(type
);
8118 Btype
* btype
= type
->get_backend(gogo
);
8119 Bfunction
* bfunction
= function
->func_value()->get_decl();
8120 std::string n
= Gogo::unpack_hidden_name(name
);
8121 bool is_address_taken
= (this->is_non_escaping_address_taken_
8122 && !this->is_in_heap());
8123 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
8124 NULL
, is_address_taken
,
8128 return this->backend_
;
8131 // Class Named_constant.
8133 // Set the type of a named constant. This is only used to set the
8134 // type to an error type.
8137 Named_constant::set_type(Type
* t
)
8139 go_assert(this->type_
== NULL
|| t
->is_error_type());
8143 // Traverse the initializer expression.
8146 Named_constant::traverse_expression(Traverse
* traverse
)
8148 return Expression::traverse(&this->expr_
, traverse
);
8151 // Determine the type of the constant.
8154 Named_constant::determine_type()
8156 if (this->type_
!= NULL
)
8158 Type_context
context(this->type_
, false);
8159 this->expr_
->determine_type(&context
);
8163 // A constant may have an abstract type.
8164 Type_context
context(NULL
, true);
8165 this->expr_
->determine_type(&context
);
8166 this->type_
= this->expr_
->type();
8167 go_assert(this->type_
!= NULL
);
8171 // Indicate that we found and reported an error for this constant.
8174 Named_constant::set_error()
8176 this->type_
= Type::make_error_type();
8177 this->expr_
= Expression::make_error(this->location_
);
8180 // Export a constant.
8183 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
8185 exp
->write_c_string("const ");
8186 exp
->write_string(name
);
8187 exp
->write_c_string(" ");
8188 if (!this->type_
->is_abstract())
8190 exp
->write_type(this->type_
);
8191 exp
->write_c_string(" ");
8193 exp
->write_c_string("= ");
8195 Export_function_body
efb(exp
, 0);
8196 if (!this->type_
->is_abstract())
8197 efb
.set_type_context(this->type_
);
8198 this->expr()->export_expression(&efb
);
8199 exp
->write_string(efb
.body());
8201 exp
->write_c_string("\n");
8204 // Import a constant.
8207 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
8210 imp
->require_c_string("const ");
8211 *pname
= imp
->read_identifier();
8212 imp
->require_c_string(" ");
8213 if (imp
->peek_char() == '=')
8217 *ptype
= imp
->read_type();
8218 imp
->require_c_string(" ");
8220 imp
->require_c_string("= ");
8221 *pexpr
= Expression::import_expression(imp
, imp
->location());
8222 imp
->require_semicolon_if_old_version();
8223 imp
->require_c_string("\n");
8226 // Get the backend representation.
8229 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
8231 if (this->bconst_
== NULL
)
8233 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
8234 Type
* type
= this->type();
8235 Location loc
= this->location();
8237 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
8238 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
8239 if (type
!= NULL
&& type
->is_numeric_type())
8241 Btype
* btype
= type
->get_backend(gogo
);
8243 if (const_no
->package() == NULL
)
8244 name
= gogo
->pkgpath();
8246 name
= const_no
->package()->pkgpath();
8247 name
.push_back('.');
8248 name
.append(Gogo::unpack_hidden_name(const_no
->name()));
8250 gogo
->backend()->named_constant_expression(btype
, name
,
8253 this->bconst_
= const_decl
;
8255 return this->bconst_
;
8261 Type_declaration::add_method(const std::string
& name
, Function
* function
)
8263 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
8264 this->methods_
.push_back(ret
);
8268 // Add a method declaration.
8271 Type_declaration::add_method_declaration(const std::string
& name
,
8273 Function_type
* type
,
8276 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
8278 this->methods_
.push_back(ret
);
8282 // Return whether any methods are defined.
8285 Type_declaration::has_methods() const
8287 return !this->methods_
.empty();
8290 // Define methods for the real type.
8293 Type_declaration::define_methods(Named_type
* nt
)
8295 if (this->methods_
.empty())
8298 while (nt
->is_alias())
8300 Type
*t
= nt
->real_type()->forwarded();
8301 if (t
->named_type() != NULL
)
8302 nt
= t
->named_type();
8303 else if (t
->forward_declaration_type() != NULL
)
8305 Named_object
* no
= t
->forward_declaration_type()->named_object();
8306 Type_declaration
* td
= no
->type_declaration_value();
8307 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
8308 this->methods_
.end());
8309 this->methods_
.clear();
8314 for (std::vector
<Named_object
*>::const_iterator p
=
8315 this->methods_
.begin();
8316 p
!= this->methods_
.end();
8318 go_error_at((*p
)->location(),
8319 ("invalid receiver type "
8320 "(receiver must be a named type)"));
8325 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
8326 p
!= this->methods_
.end();
8329 if ((*p
)->is_function_declaration()
8330 || !(*p
)->func_value()->is_sink())
8331 nt
->add_existing_method(*p
);
8335 // We are using the type. Return true if we should issue a warning.
8338 Type_declaration::using_type()
8340 bool ret
= !this->issued_warning_
;
8341 this->issued_warning_
= true;
8345 // Class Unknown_name.
8347 // Set the real named object.
8350 Unknown_name::set_real_named_object(Named_object
* no
)
8352 go_assert(this->real_named_object_
== NULL
);
8353 go_assert(!no
->is_unknown());
8354 this->real_named_object_
= no
;
8357 // Class Named_object.
8359 Named_object::Named_object(const std::string
& name
,
8360 const Package
* package
,
8361 Classification classification
)
8362 : name_(name
), package_(package
), classification_(classification
),
8363 is_redefinition_(false)
8365 if (Gogo::is_sink_name(name
))
8366 go_assert(classification
== NAMED_OBJECT_SINK
);
8369 // Make an unknown name. This is used by the parser. The name must
8370 // be resolved later. Unknown names are only added in the current
8374 Named_object::make_unknown_name(const std::string
& name
,
8377 Named_object
* named_object
= new Named_object(name
, NULL
,
8378 NAMED_OBJECT_UNKNOWN
);
8379 Unknown_name
* value
= new Unknown_name(location
);
8380 named_object
->u_
.unknown_value
= value
;
8381 return named_object
;
8387 Named_object::make_constant(const Typed_identifier
& tid
,
8388 const Package
* package
, Expression
* expr
,
8391 Named_object
* named_object
= new Named_object(tid
.name(), package
,
8392 NAMED_OBJECT_CONST
);
8393 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
8396 named_object
->u_
.const_value
= named_constant
;
8397 return named_object
;
8400 // Make a named type.
8403 Named_object::make_type(const std::string
& name
, const Package
* package
,
8404 Type
* type
, Location location
)
8406 Named_object
* named_object
= new Named_object(name
, package
,
8408 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
8409 named_object
->u_
.type_value
= named_type
;
8410 return named_object
;
8413 // Make a type declaration.
8416 Named_object::make_type_declaration(const std::string
& name
,
8417 const Package
* package
,
8420 Named_object
* named_object
= new Named_object(name
, package
,
8421 NAMED_OBJECT_TYPE_DECLARATION
);
8422 Type_declaration
* type_declaration
= new Type_declaration(location
);
8423 named_object
->u_
.type_declaration
= type_declaration
;
8424 return named_object
;
8430 Named_object::make_variable(const std::string
& name
, const Package
* package
,
8433 Named_object
* named_object
= new Named_object(name
, package
,
8435 named_object
->u_
.var_value
= variable
;
8436 return named_object
;
8439 // Make a result variable.
8442 Named_object::make_result_variable(const std::string
& name
,
8443 Result_variable
* result
)
8445 Named_object
* named_object
= new Named_object(name
, NULL
,
8446 NAMED_OBJECT_RESULT_VAR
);
8447 named_object
->u_
.result_var_value
= result
;
8448 return named_object
;
8451 // Make a sink. This is used for the special blank identifier _.
8454 Named_object::make_sink()
8456 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
8459 // Make a named function.
8462 Named_object::make_function(const std::string
& name
, const Package
* package
,
8465 Named_object
* named_object
= new Named_object(name
, package
,
8467 named_object
->u_
.func_value
= function
;
8468 return named_object
;
8471 // Make a function declaration.
8474 Named_object::make_function_declaration(const std::string
& name
,
8475 const Package
* package
,
8476 Function_type
* fntype
,
8479 Named_object
* named_object
= new Named_object(name
, package
,
8480 NAMED_OBJECT_FUNC_DECLARATION
);
8481 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
8482 named_object
->u_
.func_declaration_value
= func_decl
;
8483 return named_object
;
8489 Named_object::make_package(const std::string
& alias
, Package
* package
)
8491 Named_object
* named_object
= new Named_object(alias
, NULL
,
8492 NAMED_OBJECT_PACKAGE
);
8493 named_object
->u_
.package_value
= package
;
8494 return named_object
;
8497 // Return the name to use in an error message.
8500 Named_object::message_name() const
8502 if (this->package_
== NULL
)
8503 return Gogo::message_name(this->name_
);
8505 if (this->package_
->has_package_name())
8506 ret
= this->package_
->package_name();
8508 ret
= this->package_
->pkgpath();
8509 ret
= Gogo::message_name(ret
);
8511 ret
+= Gogo::message_name(this->name_
);
8515 // Set the type when a declaration is defined.
8518 Named_object::set_type_value(Named_type
* named_type
)
8520 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8521 Type_declaration
* td
= this->u_
.type_declaration
;
8522 td
->define_methods(named_type
);
8524 Named_object
* in_function
= td
->in_function(&index
);
8525 if (in_function
!= NULL
)
8526 named_type
->set_in_function(in_function
, index
);
8528 this->classification_
= NAMED_OBJECT_TYPE
;
8529 this->u_
.type_value
= named_type
;
8532 // Define a function which was previously declared.
8535 Named_object::set_function_value(Function
* function
)
8537 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8538 if (this->func_declaration_value()->has_descriptor())
8540 Expression
* descriptor
=
8541 this->func_declaration_value()->descriptor(NULL
, NULL
);
8542 function
->set_descriptor(descriptor
);
8544 this->classification_
= NAMED_OBJECT_FUNC
;
8545 // FIXME: We should free the old value.
8546 this->u_
.func_value
= function
;
8549 // Declare an unknown object as a type declaration.
8552 Named_object::declare_as_type()
8554 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8555 Unknown_name
* unk
= this->u_
.unknown_value
;
8556 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8557 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8561 // Return the location of a named object.
8564 Named_object::location() const
8566 switch (this->classification_
)
8569 case NAMED_OBJECT_UNINITIALIZED
:
8572 case NAMED_OBJECT_ERRONEOUS
:
8573 return Linemap::unknown_location();
8575 case NAMED_OBJECT_UNKNOWN
:
8576 return this->unknown_value()->location();
8578 case NAMED_OBJECT_CONST
:
8579 return this->const_value()->location();
8581 case NAMED_OBJECT_TYPE
:
8582 return this->type_value()->location();
8584 case NAMED_OBJECT_TYPE_DECLARATION
:
8585 return this->type_declaration_value()->location();
8587 case NAMED_OBJECT_VAR
:
8588 return this->var_value()->location();
8590 case NAMED_OBJECT_RESULT_VAR
:
8591 return this->result_var_value()->location();
8593 case NAMED_OBJECT_SINK
:
8596 case NAMED_OBJECT_FUNC
:
8597 return this->func_value()->location();
8599 case NAMED_OBJECT_FUNC_DECLARATION
:
8600 return this->func_declaration_value()->location();
8602 case NAMED_OBJECT_PACKAGE
:
8603 return this->package_value()->location();
8607 // Export a named object.
8610 Named_object::export_named_object(Export
* exp
) const
8612 switch (this->classification_
)
8615 case NAMED_OBJECT_UNINITIALIZED
:
8616 case NAMED_OBJECT_UNKNOWN
:
8619 case NAMED_OBJECT_ERRONEOUS
:
8622 case NAMED_OBJECT_CONST
:
8623 this->const_value()->export_const(exp
, this->name_
);
8626 case NAMED_OBJECT_TYPE
:
8627 // Types are handled by export::write_types.
8630 case NAMED_OBJECT_TYPE_DECLARATION
:
8631 go_error_at(this->type_declaration_value()->location(),
8632 "attempt to export %<%s%> which was declared but not defined",
8633 this->message_name().c_str());
8636 case NAMED_OBJECT_FUNC_DECLARATION
:
8637 this->func_declaration_value()->export_func(exp
, this);
8640 case NAMED_OBJECT_VAR
:
8641 this->var_value()->export_var(exp
, this);
8644 case NAMED_OBJECT_RESULT_VAR
:
8645 case NAMED_OBJECT_SINK
:
8648 case NAMED_OBJECT_FUNC
:
8649 this->func_value()->export_func(exp
, this);
8654 // Convert a variable to the backend representation.
8657 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8659 if (this->classification_
== NAMED_OBJECT_VAR
)
8660 return this->var_value()->get_backend_variable(gogo
, function
,
8661 this->package_
, this->name_
);
8662 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8663 return this->result_var_value()->get_backend_variable(gogo
, function
,
8670 debug_go_named_object(Named_object
* no
)
8674 std::cerr
<< "<null>";
8677 std::cerr
<< "'" << no
->name() << "': ";
8679 switch (no
->classification())
8681 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8682 tag
= "uninitialized";
8684 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8687 case Named_object::NAMED_OBJECT_UNKNOWN
:
8690 case Named_object::NAMED_OBJECT_CONST
:
8693 case Named_object::NAMED_OBJECT_TYPE
:
8696 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8699 case Named_object::NAMED_OBJECT_VAR
:
8702 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8705 case Named_object::NAMED_OBJECT_SINK
:
8708 case Named_object::NAMED_OBJECT_FUNC
:
8711 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8714 case Named_object::NAMED_OBJECT_PACKAGE
:
8718 tag
= "<unknown named object classification>";
8721 std::cerr
<< tag
<< "\n";
8724 // Get the backend representation for this named object.
8727 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8728 std::vector
<Btype
*>& type_decls
,
8729 std::vector
<Bfunction
*>& func_decls
)
8731 // If this is a definition, avoid trying to get the backend
8732 // representation, as that can crash.
8733 if (this->is_redefinition_
)
8735 go_assert(saw_errors());
8739 switch (this->classification_
)
8741 case NAMED_OBJECT_CONST
:
8742 if (!Gogo::is_erroneous_name(this->name_
))
8743 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8746 case NAMED_OBJECT_TYPE
:
8748 Named_type
* named_type
= this->u_
.type_value
;
8750 // No need to do anything for aliases-- whatever has to be done
8751 // can be done for the alias target.
8752 if (named_type
->is_alias())
8755 if (!Gogo::is_erroneous_name(this->name_
))
8756 type_decls
.push_back(named_type
->get_backend(gogo
));
8758 // We need to produce a type descriptor for every named
8759 // type, and for a pointer to every named type, since
8760 // other files or packages might refer to them. We need
8761 // to do this even for hidden types, because they might
8762 // still be returned by some function. Simply calling the
8763 // type_descriptor method is enough to create the type
8764 // descriptor, even though we don't do anything with it.
8765 if (this->package_
== NULL
&& !saw_errors())
8768 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8769 named_type
->gc_symbol_pointer(gogo
);
8770 Type
* pn
= Type::make_pointer_type(named_type
);
8771 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8772 pn
->gc_symbol_pointer(gogo
);
8777 case NAMED_OBJECT_TYPE_DECLARATION
:
8778 go_error_at(Linemap::unknown_location(),
8779 "reference to undefined type %qs",
8780 this->message_name().c_str());
8783 case NAMED_OBJECT_VAR
:
8784 case NAMED_OBJECT_RESULT_VAR
:
8785 case NAMED_OBJECT_SINK
:
8788 case NAMED_OBJECT_FUNC
:
8790 Function
* func
= this->u_
.func_value
;
8791 if (!Gogo::is_erroneous_name(this->name_
))
8792 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
8794 if (func
->block() != NULL
)
8795 func
->build(gogo
, this);
8799 case NAMED_OBJECT_ERRONEOUS
:
8809 Bindings::Bindings(Bindings
* enclosing
)
8810 : enclosing_(enclosing
), named_objects_(), bindings_()
8817 Bindings::clear_file_scope(Gogo
* gogo
)
8819 Contour::iterator p
= this->bindings_
.begin();
8820 while (p
!= this->bindings_
.end())
8823 if (p
->second
->package() != NULL
)
8825 else if (p
->second
->is_package())
8827 else if (p
->second
->is_function()
8828 && !p
->second
->func_value()->type()->is_method()
8829 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
8838 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
8839 p
= this->bindings_
.erase(p
);
8844 // Look up a symbol.
8847 Bindings::lookup(const std::string
& name
) const
8849 Contour::const_iterator p
= this->bindings_
.find(name
);
8850 if (p
!= this->bindings_
.end())
8851 return p
->second
->resolve();
8852 else if (this->enclosing_
!= NULL
)
8853 return this->enclosing_
->lookup(name
);
8858 // Look up a symbol locally.
8861 Bindings::lookup_local(const std::string
& name
) const
8863 Contour::const_iterator p
= this->bindings_
.find(name
);
8864 if (p
== this->bindings_
.end())
8869 // Remove an object from a set of bindings. This is used for a
8870 // special case in thunks for functions which call recover.
8873 Bindings::remove_binding(Named_object
* no
)
8875 Contour::iterator pb
= this->bindings_
.find(no
->name());
8876 go_assert(pb
!= this->bindings_
.end());
8877 this->bindings_
.erase(pb
);
8878 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
8879 pn
!= this->named_objects_
.end();
8884 this->named_objects_
.erase(pn
);
8891 // Add a method to the list of objects. This is not added to the
8892 // lookup table. This is so that we have a single list of objects
8893 // declared at the top level, which we walk through when it's time to
8894 // convert to trees.
8897 Bindings::add_method(Named_object
* method
)
8899 this->named_objects_
.push_back(method
);
8902 // Add a generic Named_object to a Contour.
8905 Bindings::add_named_object_to_contour(Contour
* contour
,
8906 Named_object
* named_object
)
8908 go_assert(named_object
== named_object
->resolve());
8909 const std::string
& name(named_object
->name());
8910 go_assert(!Gogo::is_sink_name(name
));
8912 std::pair
<Contour::iterator
, bool> ins
=
8913 contour
->insert(std::make_pair(name
, named_object
));
8916 // The name was already there.
8917 if (named_object
->package() != NULL
8918 && ins
.first
->second
->package() == named_object
->package()
8919 && (ins
.first
->second
->classification()
8920 == named_object
->classification()))
8922 // This is a second import of the same object.
8923 return ins
.first
->second
;
8925 ins
.first
->second
= this->new_definition(ins
.first
->second
,
8927 return ins
.first
->second
;
8931 // Don't push declarations on the list. We push them on when
8932 // and if we find the definitions. That way we genericize the
8933 // functions in order.
8934 if (!named_object
->is_type_declaration()
8935 && !named_object
->is_function_declaration()
8936 && !named_object
->is_unknown())
8937 this->named_objects_
.push_back(named_object
);
8938 return named_object
;
8942 // We had an existing named object OLD_OBJECT, and we've seen a new
8943 // one NEW_OBJECT with the same name. FIXME: This does not free the
8944 // new object when we don't need it.
8947 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
8949 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
8953 switch (old_object
->classification())
8956 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8959 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8962 case Named_object::NAMED_OBJECT_UNKNOWN
:
8964 Named_object
* real
= old_object
->unknown_value()->real_named_object();
8966 return this->new_definition(real
, new_object
);
8967 go_assert(!new_object
->is_unknown());
8968 old_object
->unknown_value()->set_real_named_object(new_object
);
8969 if (!new_object
->is_type_declaration()
8970 && !new_object
->is_function_declaration())
8971 this->named_objects_
.push_back(new_object
);
8975 case Named_object::NAMED_OBJECT_CONST
:
8978 case Named_object::NAMED_OBJECT_TYPE
:
8979 if (new_object
->is_type_declaration())
8983 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8984 if (new_object
->is_type_declaration())
8986 if (new_object
->is_type())
8988 old_object
->set_type_value(new_object
->type_value());
8989 new_object
->type_value()->set_named_object(old_object
);
8990 this->named_objects_
.push_back(old_object
);
8995 case Named_object::NAMED_OBJECT_VAR
:
8996 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8997 // We have already given an error in the parser for cases where
8998 // one parameter or result variable redeclares another one.
8999 if ((new_object
->is_variable()
9000 && new_object
->var_value()->is_parameter())
9001 || new_object
->is_result_variable())
9005 case Named_object::NAMED_OBJECT_SINK
:
9008 case Named_object::NAMED_OBJECT_FUNC
:
9011 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
9013 // We declare the hash and equality functions before defining
9014 // them, because we sometimes see that we need the declaration
9015 // while we are in the middle of a different function.
9017 // We declare the main function before the user defines it, to
9018 // give better error messages.
9020 // We declare inline functions before we define them, as we
9021 // only define them if we need them.
9022 if (new_object
->is_function()
9023 && ((Linemap::is_predeclared_location(old_object
->location())
9024 && Linemap::is_predeclared_location(new_object
->location()))
9025 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
9026 && Linemap::is_unknown_location(old_object
->location()))
9027 || (new_object
->package() != NULL
9028 && old_object
->func_declaration_value()->has_imported_body()
9029 && new_object
->func_value()->is_inline_only())))
9031 Function_type
* old_type
=
9032 old_object
->func_declaration_value()->type();
9033 Function_type
* new_type
= new_object
->func_value()->type();
9034 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
9036 Function_declaration
* fd
=
9037 old_object
->func_declaration_value();
9038 go_assert(fd
->asm_name().empty());
9039 old_object
->set_function_value(new_object
->func_value());
9040 this->named_objects_
.push_back(old_object
);
9047 case Named_object::NAMED_OBJECT_PACKAGE
:
9051 std::string n
= old_object
->message_name();
9053 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
9055 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
9057 old_object
->set_is_redefinition();
9058 new_object
->set_is_redefinition();
9060 if (!Linemap::is_unknown_location(old_object
->location())
9061 && !Linemap::is_predeclared_location(old_object
->location()))
9062 go_inform(old_object
->location(), "previous definition of %qs was here",
9068 // Add a named type.
9071 Bindings::add_named_type(Named_type
* named_type
)
9073 return this->add_named_object(named_type
->named_object());
9079 Bindings::add_function(const std::string
& name
, const Package
* package
,
9082 return this->add_named_object(Named_object::make_function(name
, package
,
9086 // Add a function declaration.
9089 Bindings::add_function_declaration(const std::string
& name
,
9090 const Package
* package
,
9091 Function_type
* type
,
9094 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
9096 return this->add_named_object(no
);
9099 // Define a type which was previously declared.
9102 Bindings::define_type(Named_object
* no
, Named_type
* type
)
9104 no
->set_type_value(type
);
9105 this->named_objects_
.push_back(no
);
9108 // Mark all local variables as used. This is used for some types of
9112 Bindings::mark_locals_used()
9114 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
9115 p
!= this->named_objects_
.end();
9117 if ((*p
)->is_variable())
9118 (*p
)->var_value()->set_is_used();
9121 // Traverse bindings.
9124 Bindings::traverse(Traverse
* traverse
, bool is_global
)
9126 unsigned int traverse_mask
= traverse
->traverse_mask();
9128 // We don't use an iterator because we permit the traversal to add
9129 // new global objects.
9130 const unsigned int e_or_t
= (Traverse::traverse_expressions
9131 | Traverse::traverse_types
);
9132 const unsigned int e_or_t_or_s
= (e_or_t
9133 | Traverse::traverse_statements
);
9134 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9136 Named_object
* p
= this->named_objects_
[i
];
9137 int t
= TRAVERSE_CONTINUE
;
9138 switch (p
->classification())
9140 case Named_object::NAMED_OBJECT_CONST
:
9141 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
9142 t
= traverse
->constant(p
, is_global
);
9143 if (t
== TRAVERSE_CONTINUE
9144 && (traverse_mask
& e_or_t
) != 0)
9146 Type
* tc
= p
->const_value()->type();
9148 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
9149 return TRAVERSE_EXIT
;
9150 t
= p
->const_value()->traverse_expression(traverse
);
9154 case Named_object::NAMED_OBJECT_VAR
:
9155 case Named_object::NAMED_OBJECT_RESULT_VAR
:
9156 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
9157 t
= traverse
->variable(p
);
9158 if (t
== TRAVERSE_CONTINUE
9159 && (traverse_mask
& e_or_t
) != 0)
9161 if (p
->is_result_variable()
9162 || p
->var_value()->has_type())
9164 Type
* tv
= (p
->is_variable()
9165 ? p
->var_value()->type()
9166 : p
->result_var_value()->type());
9168 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
9169 return TRAVERSE_EXIT
;
9172 if (t
== TRAVERSE_CONTINUE
9173 && (traverse_mask
& e_or_t_or_s
) != 0
9174 && p
->is_variable())
9175 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
9178 case Named_object::NAMED_OBJECT_FUNC
:
9179 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
9180 t
= traverse
->function(p
);
9182 if (t
== TRAVERSE_CONTINUE
9184 & (Traverse::traverse_variables
9185 | Traverse::traverse_constants
9186 | Traverse::traverse_functions
9187 | Traverse::traverse_blocks
9188 | Traverse::traverse_statements
9189 | Traverse::traverse_expressions
9190 | Traverse::traverse_types
)) != 0)
9191 t
= p
->func_value()->traverse(traverse
);
9194 case Named_object::NAMED_OBJECT_PACKAGE
:
9195 // These are traversed in Gogo::traverse.
9196 go_assert(is_global
);
9199 case Named_object::NAMED_OBJECT_TYPE
:
9200 if ((traverse_mask
& e_or_t
) != 0)
9201 t
= Type::traverse(p
->type_value(), traverse
);
9204 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
9205 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
9206 case Named_object::NAMED_OBJECT_UNKNOWN
:
9207 case Named_object::NAMED_OBJECT_ERRONEOUS
:
9210 case Named_object::NAMED_OBJECT_SINK
:
9215 if (t
== TRAVERSE_EXIT
)
9216 return TRAVERSE_EXIT
;
9219 // If we need to traverse types, check the function declarations,
9220 // which have types. Also check any methods of a type declaration.
9221 if ((traverse_mask
& e_or_t
) != 0)
9223 for (Bindings::const_declarations_iterator p
=
9224 this->begin_declarations();
9225 p
!= this->end_declarations();
9228 if (p
->second
->is_function_declaration())
9230 if (Type::traverse(p
->second
->func_declaration_value()->type(),
9233 return TRAVERSE_EXIT
;
9235 else if (p
->second
->is_type_declaration())
9237 const std::vector
<Named_object
*>* methods
=
9238 p
->second
->type_declaration_value()->methods();
9239 for (std::vector
<Named_object
*>::const_iterator pm
=
9241 pm
!= methods
->end();
9244 Named_object
* no
= *pm
;
9246 if (no
->is_function())
9247 t
= no
->func_value()->type();
9248 else if (no
->is_function_declaration())
9249 t
= no
->func_declaration_value()->type();
9252 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
9253 return TRAVERSE_EXIT
;
9259 // Traverse function declarations when needed.
9260 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
9262 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
9263 p
!= this->end_declarations();
9266 if (p
->second
->is_function_declaration())
9268 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
9269 return TRAVERSE_EXIT
;
9274 return TRAVERSE_CONTINUE
;
9278 Bindings::debug_dump()
9280 std::set
<Named_object
*> defs
;
9281 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9282 defs
.insert(this->named_objects_
[i
]);
9283 for (Contour::iterator p
= this->bindings_
.begin();
9284 p
!= this->bindings_
.end();
9287 const char* tag
= " ";
9288 if (defs
.find(p
->second
) != defs
.end())
9291 debug_go_named_object(p
->second
);
9296 debug_go_bindings(Bindings
* bindings
)
9298 if (bindings
!= NULL
)
9299 bindings
->debug_dump();
9304 // Clear any references to this label.
9309 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
9310 p
!= this->refs_
.end();
9313 this->refs_
.clear();
9316 // Get the backend representation for a label.
9319 Label::get_backend_label(Translate_context
* context
)
9321 if (this->blabel_
== NULL
)
9323 Function
* function
= context
->function()->func_value();
9324 Bfunction
* bfunction
= function
->get_decl();
9325 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
9328 return this->blabel_
;
9331 // Return an expression for the address of this label.
9334 Label::get_addr(Translate_context
* context
, Location location
)
9336 Blabel
* label
= this->get_backend_label(context
);
9337 return context
->backend()->label_address(label
, location
);
9340 // Return the dummy label that represents any instance of the blank label.
9343 Label::create_dummy_label()
9345 static Label
* dummy_label
;
9346 if (dummy_label
== NULL
)
9348 dummy_label
= new Label("_");
9349 dummy_label
->set_is_used();
9354 // Class Unnamed_label.
9356 // Get the backend representation for an unnamed label.
9359 Unnamed_label::get_blabel(Translate_context
* context
)
9361 if (this->blabel_
== NULL
)
9363 Function
* function
= context
->function()->func_value();
9364 Bfunction
* bfunction
= function
->get_decl();
9365 this->blabel_
= context
->backend()->label(bfunction
, "",
9368 return this->blabel_
;
9371 // Return a statement which defines this unnamed label.
9374 Unnamed_label::get_definition(Translate_context
* context
)
9376 Blabel
* blabel
= this->get_blabel(context
);
9377 return context
->backend()->label_definition_statement(blabel
);
9380 // Return a goto statement to this unnamed label.
9383 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
9385 Blabel
* blabel
= this->get_blabel(context
);
9386 return context
->backend()->goto_statement(blabel
, location
);
9391 Package::Package(const std::string
& pkgpath
,
9392 const std::string
& pkgpath_symbol
, Location location
)
9393 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
9394 package_name_(), bindings_(new Bindings(NULL
)),
9397 go_assert(!pkgpath
.empty());
9400 // Set the package name.
9403 Package::set_package_name(const std::string
& package_name
, Location location
)
9405 go_assert(!package_name
.empty());
9406 if (this->package_name_
.empty())
9407 this->package_name_
= package_name
;
9408 else if (this->package_name_
!= package_name
)
9409 go_error_at(location
,
9410 ("saw two different packages with "
9411 "the same package path %s: %s, %s"),
9412 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
9413 package_name
.c_str());
9416 // Return the pkgpath symbol, which is a prefix for symbols defined in
9420 Package::pkgpath_symbol() const
9422 if (this->pkgpath_symbol_
.empty())
9423 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
9424 return this->pkgpath_symbol_
;
9427 // Set the package path symbol.
9430 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
9432 go_assert(!pkgpath_symbol
.empty());
9433 if (this->pkgpath_symbol_
.empty())
9434 this->pkgpath_symbol_
= pkgpath_symbol
;
9436 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
9439 // Note that symbol from this package was and qualified by ALIAS.
9442 Package::note_usage(const std::string
& alias
) const
9444 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9445 go_assert(p
!= this->aliases_
.end());
9446 p
->second
->note_usage();
9449 // Forget a given usage. If forgetting this usage means this package becomes
9450 // unused, report that error.
9453 Package::forget_usage(Expression
* usage
) const
9455 if (this->fake_uses_
.empty())
9458 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
9459 go_assert(p
!= this->fake_uses_
.end());
9460 this->fake_uses_
.erase(p
);
9462 if (this->fake_uses_
.empty())
9463 go_error_at(this->location(), "imported and not used: %s",
9464 Gogo::message_name(this->package_name()).c_str());
9467 // Clear the used field for the next file. If the only usages of this package
9468 // are possibly fake, keep the fake usages for lowering.
9471 Package::clear_used()
9473 std::string dot_alias
= "." + this->package_name();
9474 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
9475 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
9476 this->fake_uses_
.clear();
9478 this->aliases_
.clear();
9482 Package::add_alias(const std::string
& alias
, Location location
)
9484 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9485 if (p
== this->aliases_
.end())
9487 std::pair
<Aliases::iterator
, bool> ret
;
9488 ret
= this->aliases_
.insert(std::make_pair(alias
,
9489 new Package_alias(location
)));
9495 // Determine types of constants. Everything else in a package
9496 // (variables, function declarations) should already have a fixed
9497 // type. Constants may have abstract types.
9500 Package::determine_types()
9502 Bindings
* bindings
= this->bindings_
;
9503 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
9504 p
!= bindings
->end_definitions();
9507 if ((*p
)->is_const())
9508 (*p
)->const_value()->determine_type();
9516 Traverse::~Traverse()
9518 if (this->types_seen_
!= NULL
)
9519 delete this->types_seen_
;
9520 if (this->expressions_seen_
!= NULL
)
9521 delete this->expressions_seen_
;
9524 // Record that we are looking at a type, and return true if we have
9528 Traverse::remember_type(const Type
* type
)
9530 if (type
->is_error_type())
9532 go_assert((this->traverse_mask() & traverse_types
) != 0
9533 || (this->traverse_mask() & traverse_expressions
) != 0);
9534 // We mostly only have to remember named types. But it turns out
9535 // that an interface type can refer to itself without using a name
9536 // by relying on interface inheritance, as in
9538 // type I interface { F() interface{I} }
9540 // Similarly it is possible for array types to refer to themselves
9541 // without a name, e.g.
9543 // var x [uintptr(unsafe.Sizeof(&x))]byte
9545 if (type
->classification() != Type::TYPE_NAMED
9546 && type
->classification() != Type::TYPE_ARRAY
9547 && type
->classification() != Type::TYPE_INTERFACE
)
9549 if (this->types_seen_
== NULL
)
9550 this->types_seen_
= new Types_seen();
9551 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9555 // Record that we are looking at an expression, and return true if we
9556 // have already seen it. NB: this routine used to assert if the traverse
9557 // mask did not include expressions/types -- this is no longer the case,
9558 // since it can be useful to remember specific expressions during
9559 // walks that only cover statements.
9562 Traverse::remember_expression(const Expression
* expression
)
9564 if (this->expressions_seen_
== NULL
)
9565 this->expressions_seen_
= new Expressions_seen();
9566 std::pair
<Expressions_seen::iterator
, bool> ins
=
9567 this->expressions_seen_
->insert(expression
);
9571 // The default versions of these functions should never be called: the
9572 // traversal mask indicates which functions may be called.
9575 Traverse::variable(Named_object
*)
9581 Traverse::constant(Named_object
*, bool)
9587 Traverse::function(Named_object
*)
9593 Traverse::block(Block
*)
9599 Traverse::statement(Block
*, size_t*, Statement
*)
9605 Traverse::expression(Expression
**)
9611 Traverse::type(Type
*)
9617 Traverse::function_declaration(Named_object
*)
9622 // Class Statement_inserter.
9625 Statement_inserter::insert(Statement
* s
)
9627 if (this->statements_added_
!= NULL
)
9628 this->statements_added_
->insert(s
);
9630 if (this->block_
!= NULL
)
9632 go_assert(this->pindex_
!= NULL
);
9633 this->block_
->insert_statement_before(*this->pindex_
, s
);
9636 else if (this->var_
!= NULL
)
9637 this->var_
->add_preinit_statement(this->gogo_
, s
);
9639 go_assert(saw_errors());