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),
40 current_file_imported_embed_(false),
51 pkgpath_from_option_(false),
52 prefix_from_option_(false),
53 relative_import_path_(),
59 check_divide_by_zero_(true),
60 check_divide_overflow_(true),
61 compiling_runtime_(false),
62 debug_escape_level_(0),
63 debug_optimization_(false),
64 nil_check_size_threshold_(4096),
68 specific_type_functions_(),
69 specific_type_functions_are_written_(false),
70 named_types_are_converted_(false),
74 imported_inlinable_functions_(),
75 imported_inline_functions_()
77 const Location loc
= Linemap::predeclared_location();
79 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
80 RUNTIME_TYPE_KIND_UINT8
);
81 this->add_named_type(uint8_type
);
82 this->add_named_type(Type::make_integer_type("uint16", true, 16,
83 RUNTIME_TYPE_KIND_UINT16
));
84 this->add_named_type(Type::make_integer_type("uint32", true, 32,
85 RUNTIME_TYPE_KIND_UINT32
));
86 this->add_named_type(Type::make_integer_type("uint64", true, 64,
87 RUNTIME_TYPE_KIND_UINT64
));
89 this->add_named_type(Type::make_integer_type("int8", false, 8,
90 RUNTIME_TYPE_KIND_INT8
));
91 this->add_named_type(Type::make_integer_type("int16", false, 16,
92 RUNTIME_TYPE_KIND_INT16
));
93 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
94 RUNTIME_TYPE_KIND_INT32
);
95 this->add_named_type(int32_type
);
96 this->add_named_type(Type::make_integer_type("int64", false, 64,
97 RUNTIME_TYPE_KIND_INT64
));
99 this->add_named_type(Type::make_float_type("float32", 32,
100 RUNTIME_TYPE_KIND_FLOAT32
));
101 this->add_named_type(Type::make_float_type("float64", 64,
102 RUNTIME_TYPE_KIND_FLOAT64
));
104 this->add_named_type(Type::make_complex_type("complex64", 64,
105 RUNTIME_TYPE_KIND_COMPLEX64
));
106 this->add_named_type(Type::make_complex_type("complex128", 128,
107 RUNTIME_TYPE_KIND_COMPLEX128
));
109 int int_type_size
= pointer_size
;
110 if (int_type_size
< 32)
112 this->add_named_type(Type::make_integer_type("uint", true,
114 RUNTIME_TYPE_KIND_UINT
));
115 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
116 RUNTIME_TYPE_KIND_INT
);
117 this->add_named_type(int_type
);
119 this->add_named_type(Type::make_integer_type("uintptr", true,
121 RUNTIME_TYPE_KIND_UINTPTR
));
123 // "byte" is an alias for "uint8".
124 uint8_type
->integer_type()->set_is_byte();
125 this->add_named_type(Type::make_integer_type_alias("byte", uint8_type
));
127 // "rune" is an alias for "int32".
128 int32_type
->integer_type()->set_is_rune();
129 this->add_named_type(Type::make_integer_type_alias("rune", int32_type
));
131 this->add_named_type(Type::make_named_bool_type());
133 this->add_named_type(Type::make_named_string_type());
135 // "error" is interface { Error() string }.
137 Typed_identifier_list
*methods
= new Typed_identifier_list
;
138 Typed_identifier_list
*results
= new Typed_identifier_list
;
139 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
140 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
141 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
142 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
143 error_iface
->finalize_methods();
144 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
145 this->add_named_type(error_type
);
148 // "any" is an alias for the empty interface type.
150 Type
* empty
= Type::make_empty_interface_type(loc
);
151 Named_object
* no
= Named_object::make_type("any", NULL
, empty
, loc
);
152 Named_type
* nt
= no
->type_value();
154 this->add_named_type(nt
);
157 this->globals_
->add_constant(Typed_identifier("true",
158 Type::make_boolean_type(),
161 Expression::make_boolean(true, loc
),
163 this->globals_
->add_constant(Typed_identifier("false",
164 Type::make_boolean_type(),
167 Expression::make_boolean(false, loc
),
170 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
173 Expression::make_nil(loc
),
176 Type
* abstract_int_type
= Type::make_abstract_integer_type();
177 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
180 Expression::make_iota(),
183 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
184 new_type
->set_is_varargs();
185 new_type
->set_is_builtin();
186 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
188 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
189 make_type
->set_is_varargs();
190 make_type
->set_is_builtin();
191 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
193 Typed_identifier_list
* len_result
= new Typed_identifier_list();
194 len_result
->push_back(Typed_identifier("", int_type
, loc
));
195 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
197 len_type
->set_is_builtin();
198 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
200 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
201 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
202 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
204 cap_type
->set_is_builtin();
205 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
207 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
208 print_type
->set_is_varargs();
209 print_type
->set_is_builtin();
210 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
212 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
213 print_type
->set_is_varargs();
214 print_type
->set_is_builtin();
215 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
217 Type
*empty
= Type::make_empty_interface_type(loc
);
218 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
219 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
220 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
222 panic_type
->set_is_builtin();
223 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
225 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
226 recover_result
->push_back(Typed_identifier("", empty
, loc
));
227 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
230 recover_type
->set_is_builtin();
231 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
233 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
234 close_type
->set_is_varargs();
235 close_type
->set_is_builtin();
236 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
238 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
239 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
240 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
242 copy_type
->set_is_varargs();
243 copy_type
->set_is_builtin();
244 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
246 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
247 append_type
->set_is_varargs();
248 append_type
->set_is_builtin();
249 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
251 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
252 complex_type
->set_is_varargs();
253 complex_type
->set_is_builtin();
254 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
256 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
257 real_type
->set_is_varargs();
258 real_type
->set_is_builtin();
259 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
261 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
262 imag_type
->set_is_varargs();
263 imag_type
->set_is_builtin();
264 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
266 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
267 delete_type
->set_is_varargs();
268 delete_type
->set_is_builtin();
269 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
273 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
275 go_assert(!pkgpath
.empty());
276 return go_encode_id(pkgpath
);
279 // Return a hash code for a string, given a starting hash.
282 Gogo::hash_string(const std::string
& s
, unsigned int h
)
284 const char* p
= s
.data();
285 size_t len
= s
.length();
286 for (; len
> 0; --len
)
294 // Get the package path to use for type reflection data. This should
295 // ideally be unique across the entire link.
298 Gogo::pkgpath() const
300 go_assert(this->pkgpath_set_
);
301 return this->pkgpath_
;
304 // Set the package path from the -fgo-pkgpath command line option.
307 Gogo::set_pkgpath(const std::string
& arg
)
309 go_assert(!this->pkgpath_set_
);
310 this->pkgpath_
= arg
;
311 this->pkgpath_set_
= true;
312 this->pkgpath_from_option_
= true;
315 // Get the package path to use for symbol names.
318 Gogo::pkgpath_symbol() const
320 go_assert(this->pkgpath_set_
);
321 return this->pkgpath_symbol_
;
324 // Set the unique prefix to use to determine the package path, from
325 // the -fgo-prefix command line option.
328 Gogo::set_prefix(const std::string
& arg
)
330 go_assert(!this->prefix_from_option_
);
332 this->prefix_from_option_
= true;
335 // Munge name for use in an error message.
338 Gogo::message_name(const std::string
& name
)
340 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
343 // Get the package name.
346 Gogo::package_name() const
348 go_assert(this->package_
!= NULL
);
349 return this->package_
->package_name();
352 // Set the package name.
355 Gogo::set_package_name(const std::string
& package_name
,
358 if (this->package_
!= NULL
)
360 if (this->package_
->package_name() != package_name
)
361 go_error_at(location
, "expected package %<%s%>",
362 Gogo::message_name(this->package_
->package_name()).c_str());
366 // Now that we know the name of the package we are compiling, set
367 // the package path to use for reflect.Type.PkgPath and global
369 if (this->pkgpath_set_
)
370 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
373 if (!this->prefix_from_option_
&& package_name
== "main")
375 this->pkgpath_
= package_name
;
376 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
380 if (!this->prefix_from_option_
)
381 this->prefix_
= "go";
382 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
383 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
384 + Gogo::pkgpath_for_symbol(package_name
));
386 this->pkgpath_set_
= true;
389 this->package_
= this->register_package(this->pkgpath_
,
390 this->pkgpath_symbol_
, location
);
391 this->package_
->set_package_name(package_name
, location
);
393 if (this->is_main_package())
395 // Declare "main" as a function which takes no parameters and
397 Location uloc
= Linemap::unknown_location();
398 this->declare_function(Gogo::pack_hidden_name("main", false),
399 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
404 // Return whether this is the "main" package. This is not true if
405 // -fgo-pkgpath or -fgo-prefix was used.
408 Gogo::is_main_package() const
410 return (this->package_name() == "main"
411 && !this->pkgpath_from_option_
412 && !this->prefix_from_option_
);
418 Gogo::import_package(const std::string
& filename
,
419 const std::string
& local_name
,
420 bool is_local_name_exported
,
424 if (filename
.empty())
426 go_error_at(location
, "import path is empty");
430 const char *pf
= filename
.data();
431 const char *pend
= pf
+ filename
.length();
435 int adv
= Lex::fetch_char(pf
, &c
);
438 go_error_at(location
, "import path contains invalid UTF-8 sequence");
443 go_error_at(location
, "import path contains NUL");
446 if (c
< 0x20 || c
== 0x7f)
448 go_error_at(location
, "import path contains control character");
453 go_error_at(location
, "import path contains backslash; use slash");
456 if (Lex::is_unicode_space(c
))
458 go_error_at(location
, "import path contains space character");
461 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
463 go_error_at(location
,
464 "import path contains invalid character '%c'", c
);
470 if (IS_ABSOLUTE_PATH(filename
.c_str()))
472 go_error_at(location
, "import path cannot be absolute path");
476 if (local_name
== "init")
477 go_error_at(location
, "cannot import package as init");
479 if (filename
== "unsafe")
481 this->import_unsafe(local_name
, is_local_name_exported
, location
);
482 this->current_file_imported_unsafe_
= true;
486 if (filename
== "embed")
487 this->current_file_imported_embed_
= true;
489 Imports::const_iterator p
= this->imports_
.find(filename
);
490 if (p
!= this->imports_
.end())
492 Package
* package
= p
->second
;
493 package
->set_location(location
);
494 std::string ln
= local_name
;
495 bool is_ln_exported
= is_local_name_exported
;
498 ln
= package
->package_name();
499 go_assert(!ln
.empty());
500 is_ln_exported
= Lex::is_exported_name(ln
);
506 Bindings
* bindings
= package
->bindings();
507 for (Bindings::const_declarations_iterator pd
=
508 bindings
->begin_declarations();
509 pd
!= bindings
->end_declarations();
511 this->add_dot_import_object(pd
->second
);
512 std::string dot_alias
= "." + package
->package_name();
513 package
->add_alias(dot_alias
, location
);
517 package
->add_alias(ln
, location
);
518 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
519 this->package_
->bindings()->add_package(ln
, package
);
524 // If we are using an importcfg file we have to check two mappings.
525 // IMPORT_MAP_ is a mapping from package path to real package path,
526 // for vendoring. PACKAGE_FILE_ is a mapping from package path to
527 // file name, to find the file in the build cache.
528 std::string path
= filename
;
529 Unordered_map(std::string
, std::string
)::const_iterator pi
;
530 pi
= this->import_map_
.find(filename
);
531 if (pi
!= this->import_map_
.end())
533 pi
= this->package_file_
.find(path
);
534 if (pi
!= this->package_file_
.end())
537 Import::Stream
* stream
= Import::open_package(path
, location
,
538 this->relative_import_path_
);
542 go_error_at(location
, "import file %qs not found", filename
.c_str());
546 Import
* imp
= new Import(stream
, location
);
547 imp
->register_builtin_types(this);
548 Package
* package
= imp
->import(this, local_name
, is_local_name_exported
);
551 if (package
->pkgpath() == this->pkgpath())
552 go_error_at(location
,
553 ("imported package uses same package path as package "
554 "being compiled (see %<-fgo-pkgpath%> option)"));
556 this->imports_
.insert(std::make_pair(filename
, package
));
562 // FIXME: we never delete imp; we may need it for inlinable functions.
566 Gogo::lookup_init(const std::string
& init_name
)
568 Import_init
tmp("", init_name
, -1);
569 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
570 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
573 // Add an import control function for an imported package to the list.
576 Gogo::add_import_init_fn(const std::string
& package_name
,
577 const std::string
& init_name
, int prio
)
579 for (Import_init_set::iterator p
=
580 this->imported_init_fns_
.begin();
581 p
!= this->imported_init_fns_
.end();
584 Import_init
*ii
= (*p
);
585 if (ii
->init_name() == init_name
)
587 // If a test of package P1, built as part of package P1,
588 // imports package P2, and P2 imports P1 (perhaps
589 // indirectly), then we will see the same import name with
590 // different import priorities. That is OK, so don't give
591 // an error about it.
592 if (ii
->package_name() != package_name
)
594 go_error_at(Linemap::unknown_location(),
595 "duplicate package initialization name %qs",
596 Gogo::message_name(init_name
).c_str());
597 go_inform(Linemap::unknown_location(), "used by package %qs",
598 Gogo::message_name(ii
->package_name()).c_str());
599 go_inform(Linemap::unknown_location(), " and by package %qs",
600 Gogo::message_name(package_name
).c_str());
602 ii
->set_priority(prio
);
607 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
608 this->imported_init_fns_
.insert(nii
);
611 // Return whether we are at the global binding level.
614 Gogo::in_global_scope() const
616 return this->functions_
.empty();
619 // Return the current binding contour.
622 Gogo::current_bindings()
624 if (!this->functions_
.empty())
625 return this->functions_
.back().blocks
.back()->bindings();
626 else if (this->package_
!= NULL
)
627 return this->package_
->bindings();
629 return this->globals_
;
633 Gogo::current_bindings() const
635 if (!this->functions_
.empty())
636 return this->functions_
.back().blocks
.back()->bindings();
637 else if (this->package_
!= NULL
)
638 return this->package_
->bindings();
640 return this->globals_
;
644 Gogo::update_init_priority(Import_init
* ii
,
645 std::set
<const Import_init
*>* visited
)
650 for (std::set
<std::string
>::const_iterator pci
=
651 ii
->precursors().begin();
652 pci
!= ii
->precursors().end();
655 Import_init
* succ
= this->lookup_init(*pci
);
656 if (visited
->find(succ
) == visited
->end())
657 update_init_priority(succ
, visited
);
658 succ_prior
= std::max(succ_prior
, succ
->priority());
660 if (ii
->priority() <= succ_prior
)
661 ii
->set_priority(succ_prior
+ 1);
665 Gogo::recompute_init_priorities()
667 std::set
<Import_init
*> nonroots
;
669 for (Import_init_set::const_iterator p
=
670 this->imported_init_fns_
.begin();
671 p
!= this->imported_init_fns_
.end();
674 const Import_init
*ii
= *p
;
675 for (std::set
<std::string
>::const_iterator pci
=
676 ii
->precursors().begin();
677 pci
!= ii
->precursors().end();
680 Import_init
* ii_init
= this->lookup_init(*pci
);
681 nonroots
.insert(ii_init
);
685 // Recursively update priorities starting at roots.
686 std::set
<const Import_init
*> visited
;
687 for (Import_init_set::iterator p
=
688 this->imported_init_fns_
.begin();
689 p
!= this->imported_init_fns_
.end();
692 Import_init
* ii
= *p
;
693 if (nonroots
.find(ii
) != nonroots
.end())
695 update_init_priority(ii
, &visited
);
699 // Add statements to INIT_STMTS which run the initialization
700 // functions for imported packages. This is only used for the "main"
704 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
706 go_assert(this->is_main_package());
708 if (this->imported_init_fns_
.empty())
711 Location unknown_loc
= Linemap::unknown_location();
712 Function_type
* func_type
=
713 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
714 Btype
* fntype
= func_type
->get_backend_fntype(this);
716 // Recompute init priorities based on a walk of the init graph.
717 recompute_init_priorities();
719 // We must call them in increasing priority order.
720 std::vector
<const Import_init
*> v
;
721 for (Import_init_set::const_iterator p
=
722 this->imported_init_fns_
.begin();
723 p
!= this->imported_init_fns_
.end();
726 // Don't include dummy inits. They are not real functions.
727 if ((*p
)->is_dummy())
729 if ((*p
)->priority() < 0)
730 go_error_at(Linemap::unknown_location(),
731 "internal error: failed to set init priority for %s",
732 (*p
)->package_name().c_str());
735 std::sort(v
.begin(), v
.end(), priority_compare
);
737 // We build calls to the init functions, which take no arguments.
738 std::vector
<Bexpression
*> empty_args
;
739 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
743 const Import_init
* ii
= *p
;
744 std::string user_name
= ii
->package_name() + ".init";
745 const std::string
& init_name(ii
->init_name());
746 const unsigned int flags
=
747 (Backend::function_is_visible
748 | Backend::function_is_declaration
749 | Backend::function_is_inlinable
);
750 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
752 Bexpression
* pfunc_code
=
753 this->backend()->function_code_expression(pfunc
, unknown_loc
);
754 Bexpression
* pfunc_call
=
755 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
757 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
762 // Register global variables with the garbage collector. We need to
763 // register all variables which can hold a pointer value. They become
764 // roots during the mark phase. We build a struct that is easy to
765 // hook into a list of roots.
767 // type gcRoot struct {
768 // decl unsafe.Pointer // Pointer to variable.
769 // size uintptr // Total size of variable.
770 // ptrdata uintptr // Length of variable's gcdata.
771 // gcdata *byte // Pointer mask.
774 // type gcRootList struct {
780 // The last entry in the roots array has a NULL decl field.
783 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
784 std::vector
<Bstatement
*>& init_stmts
,
787 if (var_gc
.empty() && this->gc_roots_
.empty())
790 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
791 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
792 Type
* byte_type
= Type::lookup_integer_type("byte");
793 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
794 Struct_type
* root_type
=
795 Type::make_builtin_struct_type(4,
797 "size", uintptr_type
,
798 "ptrdata", uintptr_type
,
799 "gcdata", pointer_byte_type
);
801 Location builtin_loc
= Linemap::predeclared_location();
802 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
803 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
805 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
806 root_array_type
->set_is_array_incomparable();
808 Type
* int_type
= Type::lookup_integer_type("int");
809 Struct_type
* root_list_type
=
810 Type::make_builtin_struct_type(3,
813 "roots", root_array_type
);
815 // Build an initializer for the roots array.
817 Expression_list
* roots_init
= new Expression_list();
819 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
823 Expression_list
* init
= new Expression_list();
825 Location no_loc
= (*p
)->location();
826 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
827 Expression
* decl_addr
=
828 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
829 decl_addr
->unary_expression()->set_does_not_escape();
830 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
831 init
->push_back(decl_addr
);
834 Expression::make_type_info(decl
->type(),
835 Expression::TYPE_INFO_SIZE
);
836 init
->push_back(size
);
838 Expression
* ptrdata
=
839 Expression::make_type_info(decl
->type(),
840 Expression::TYPE_INFO_BACKEND_PTRDATA
);
841 init
->push_back(ptrdata
);
843 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
844 init
->push_back(gcdata
);
846 Expression
* root_ctor
=
847 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
848 roots_init
->push_back(root_ctor
);
851 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
852 p
!= this->gc_roots_
.end();
855 Expression_list
*init
= new Expression_list();
857 Expression
* expr
= *p
;
858 Location eloc
= expr
->location();
859 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
861 Type
* type
= expr
->type()->points_to();
862 go_assert(type
!= NULL
);
865 Expression::make_type_info(type
,
866 Expression::TYPE_INFO_SIZE
);
867 init
->push_back(size
);
869 Expression
* ptrdata
=
870 Expression::make_type_info(type
,
871 Expression::TYPE_INFO_BACKEND_PTRDATA
);
872 init
->push_back(ptrdata
);
874 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
875 init
->push_back(gcdata
);
877 Expression
* root_ctor
=
878 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
879 roots_init
->push_back(root_ctor
);
882 // Build a constructor for the struct.
884 Expression_list
* root_list_init
= new Expression_list();
885 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
886 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
889 Expression
* roots_ctor
=
890 Expression::make_array_composite_literal(root_array_type
, roots_init
,
892 root_list_init
->push_back(roots_ctor
);
894 Expression
* root_list_ctor
=
895 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
898 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
900 root_addr
->unary_expression()->set_is_gc_root();
901 Expression
* register_roots
= Runtime::make_call(this,
902 Runtime::REGISTER_GC_ROOTS
,
903 builtin_loc
, 1, root_addr
);
905 Translate_context
context(this, NULL
, NULL
, NULL
);
906 Bexpression
* bcall
= register_roots
->get_backend(&context
);
907 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
910 // Build the list of type descriptors defined in this package. This is to help
911 // the reflect package to find compiler-generated types.
913 // type typeDescriptorList struct {
915 // types [...]unsafe.Pointer
919 type_descriptor_list_type(unsigned long len
)
921 Location builtin_loc
= Linemap::predeclared_location();
922 Type
* int_type
= Type::lookup_integer_type("int");
923 Type
* ptr_type
= Type::make_pointer_type(Type::make_void_type());
924 // Avoid creating zero-length type.
925 unsigned long nelems
= (len
!= 0 ? len
: 1);
926 Expression
* len_expr
= Expression::make_integer_ul(nelems
, NULL
,
928 Array_type
* array_type
= Type::make_array_type(ptr_type
, len_expr
);
929 array_type
->set_is_array_incomparable();
930 Struct_type
* list_type
=
931 Type::make_builtin_struct_type(2, "count", int_type
,
932 "types", array_type
);
937 Gogo::build_type_descriptor_list()
939 // Create the list type
940 Location builtin_loc
= Linemap::predeclared_location();
941 unsigned long len
= this->type_descriptors_
.size();
942 Struct_type
* list_type
= type_descriptor_list_type(len
);
943 Btype
* bt
= list_type
->get_backend(this);
944 Btype
* bat
= list_type
->field(1)->type()->get_backend(this);
946 // Create the variable
947 std::string name
= this->type_descriptor_list_symbol(this->pkgpath_symbol());
948 unsigned int flags
= Backend::variable_is_constant
;
949 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bt
, flags
, 0);
951 // Build the initializer
952 std::vector
<unsigned long> indexes
;
953 std::vector
<Bexpression
*> vals
;
954 std::vector
<Type
*>::iterator p
= this->type_descriptors_
.begin();
955 for (unsigned long i
= 0; i
< len
; ++i
, ++p
)
957 Bexpression
* bexpr
= (*p
)->type_descriptor_pointer(this,
959 indexes
.push_back(i
);
960 vals
.push_back(bexpr
);
962 Bexpression
* barray
=
963 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
966 Translate_context
context(this, NULL
, NULL
, NULL
);
967 std::vector
<Bexpression
*> fields
;
968 Expression
* len_expr
= Expression::make_integer_ul(len
, NULL
,
970 fields
.push_back(len_expr
->get_backend(&context
));
971 fields
.push_back(barray
);
973 this->backend()->constructor_expression(bt
, fields
, builtin_loc
);
975 this->backend()->implicit_variable_set_init(bv
, name
, bt
, flags
, binit
);
978 // Register the type descriptors with the runtime. This is to help
979 // the reflect package to find compiler-generated types.
982 Gogo::register_type_descriptors(std::vector
<Bstatement
*>& init_stmts
,
985 // Create the list type
986 Location builtin_loc
= Linemap::predeclared_location();
987 Struct_type
* list_type
= type_descriptor_list_type(1);
988 Btype
* bt
= list_type
->get_backend(this);
990 // Collect type lists from transitive imports.
991 std::vector
<std::string
> list_names
;
992 for (Import_init_set::iterator it
= this->imported_init_fns_
.begin();
993 it
!= this->imported_init_fns_
.end();
996 std::string pkgpath_symbol
=
997 this->pkgpath_symbol_from_init_fn_name((*it
)->init_name());
998 list_names
.push_back(this->type_descriptor_list_symbol(pkgpath_symbol
));
1000 // Add the main package itself.
1001 list_names
.push_back(this->type_descriptor_list_symbol("main"));
1003 // Build a list of lists.
1004 std::vector
<unsigned long> indexes
;
1005 std::vector
<Bexpression
*> vals
;
1006 unsigned long i
= 0;
1007 for (std::vector
<std::string
>::iterator p
= list_names
.begin();
1008 p
!= list_names
.end();
1012 this->backend()->implicit_variable_reference(*p
, *p
, bt
);
1013 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1014 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1016 indexes
.push_back(i
);
1017 vals
.push_back(bexpr
);
1020 Expression
* len_expr
= Expression::make_integer_ul(i
, NULL
, builtin_loc
);
1021 Type
* list_ptr_type
= Type::make_pointer_type(list_type
);
1022 Type
* list_array_type
= Type::make_array_type(list_ptr_type
, len_expr
);
1023 Btype
* bat
= list_array_type
->get_backend(this);
1024 Bexpression
* barray
=
1025 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
1028 // Create a variable holding the list.
1029 std::string name
= this->typelists_symbol();
1030 unsigned int flags
= (Backend::variable_is_hidden
1031 | Backend::variable_is_constant
);
1032 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bat
, flags
,
1034 this->backend()->implicit_variable_set_init(bv
, name
, bat
, flags
, barray
);
1036 // Build the call in main package's init function.
1037 Translate_context
context(this, NULL
, NULL
, NULL
);
1038 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1039 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1040 Type
* array_ptr_type
= Type::make_pointer_type(list_array_type
);
1041 Expression
* expr
= Expression::make_backend(bexpr
, array_ptr_type
,
1043 expr
= Runtime::make_call(this, Runtime::REGISTER_TYPE_DESCRIPTORS
,
1044 builtin_loc
, 2, len_expr
->copy(), expr
);
1045 Bexpression
* bcall
= expr
->get_backend(&context
);
1046 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
,
1050 // Build the decl for the initialization function.
1053 Gogo::initialization_function_decl()
1055 std::string name
= this->get_init_fn_name();
1056 Location loc
= this->package_
->location();
1058 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
1059 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
1060 return Named_object::make_function(name
, NULL
, initfn
);
1063 // Create the magic initialization function. CODE_STMT is the
1064 // code that it needs to run.
1067 Gogo::create_initialization_function(Named_object
* initfn
,
1068 Bstatement
* code_stmt
)
1070 // Make sure that we thought we needed an initialization function,
1071 // as otherwise we will not have reported it in the export data.
1072 go_assert(this->is_main_package() || this->need_init_fn_
);
1075 initfn
= this->initialization_function_decl();
1077 // Bind the initialization function code to a block.
1078 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
1079 Location pkg_loc
= this->package_
->location();
1080 std::vector
<Bvariable
*> vars
;
1081 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
1083 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
1085 go_assert(saw_errors());
1091 // Given an expression, collect all the global variables defined in
1092 // this package that it references.
1094 class Find_vars
: public Traverse
1097 // The list of variables we accumulate.
1098 typedef Unordered_set(Named_object
*) Vars
;
1100 // A hash table we use to avoid looping. The index is a
1101 // Named_object* or a Temporary_statement*. We only look through
1102 // objects defined in this package.
1103 typedef Unordered_set(const void*) Seen_objects
;
1107 : Traverse(traverse_expressions
| traverse_statements
),
1108 vars_(), seen_objects_(), lhs_is_ref_(false)
1111 // An iterator through the variables found, after the traversal.
1112 typedef Vars::const_iterator const_iterator
;
1116 { return this->vars_
.begin(); }
1120 { return this->vars_
.end(); }
1123 expression(Expression
**);
1126 statement(Block
*, size_t* index
, Statement
*);
1129 // Accumulated variables.
1131 // Objects we have already seen.
1132 Seen_objects seen_objects_
;
1133 // Whether an assignment to a variable counts as a reference.
1137 // Collect global variables referenced by EXPR. Look through function
1138 // calls and variable initializations.
1141 Find_vars::expression(Expression
** pexpr
)
1143 Expression
* e
= *pexpr
;
1145 Var_expression
* ve
= e
->var_expression();
1148 Named_object
* v
= ve
->named_object();
1149 if (!v
->is_variable() || v
->package() != NULL
)
1151 // This is a result parameter or a variable defined in a
1152 // different package. Either way we don't care about it.
1153 return TRAVERSE_CONTINUE
;
1156 std::pair
<Seen_objects::iterator
, bool> ins
=
1157 this->seen_objects_
.insert(v
);
1160 // We've seen this variable before.
1161 return TRAVERSE_CONTINUE
;
1164 if (v
->var_value()->is_global())
1165 this->vars_
.insert(v
);
1167 Expression
* init
= v
->var_value()->init();
1170 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1171 return TRAVERSE_EXIT
;
1175 // We traverse the code of any function or bound method we see. Note that
1176 // this means that we will traverse the code of a function or bound method
1177 // whose address is taken even if it is not called.
1178 Func_expression
* fe
= e
->func_expression();
1179 Bound_method_expression
* bme
= e
->bound_method_expression();
1180 if (fe
!= NULL
|| bme
!= NULL
)
1182 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1183 if (f
->is_function() && f
->package() == NULL
)
1185 std::pair
<Seen_objects::iterator
, bool> ins
=
1186 this->seen_objects_
.insert(f
);
1189 // This is the first time we have seen this name.
1190 bool hold
= this->lhs_is_ref_
;
1191 this->lhs_is_ref_
= true;
1192 int r
= f
->func_value()->block()->traverse(this);
1193 this->lhs_is_ref_
= hold
;
1194 if (r
== TRAVERSE_EXIT
)
1195 return TRAVERSE_EXIT
;
1200 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1203 Temporary_statement
* ts
= tre
->statement();
1204 Expression
* init
= ts
->init();
1207 std::pair
<Seen_objects::iterator
, bool> ins
=
1208 this->seen_objects_
.insert(ts
);
1211 // This is the first time we have seen this temporary
1213 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1214 return TRAVERSE_EXIT
;
1219 return TRAVERSE_CONTINUE
;
1222 // Check a statement while searching for variables. This is where we
1223 // skip variables on the left hand side of assigments if appropriate.
1226 Find_vars::statement(Block
*, size_t*, Statement
* s
)
1228 if (this->lhs_is_ref_
)
1229 return TRAVERSE_CONTINUE
;
1230 Assignment_statement
* as
= s
->assignment_statement();
1232 return TRAVERSE_CONTINUE
;
1234 // Only traverse subexpressions of the LHS.
1235 if (as
->lhs()->traverse_subexpressions(this) == TRAVERSE_EXIT
)
1236 return TRAVERSE_EXIT
;
1238 Expression
* rhs
= as
->rhs();
1239 if (Expression::traverse(&rhs
, this) == TRAVERSE_EXIT
)
1240 return TRAVERSE_EXIT
;
1242 return TRAVERSE_SKIP_COMPONENTS
;
1245 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1248 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1251 Find_vars find_vars
;
1253 Expression::traverse(&expr
, &find_vars
);
1254 if (preinit
!= NULL
)
1255 preinit
->traverse(&find_vars
);
1258 Expression
* init
= dep
->var_value()->init();
1260 Expression::traverse(&init
, &find_vars
);
1261 if (dep
->var_value()->has_pre_init())
1262 dep
->var_value()->preinit()->traverse(&find_vars
);
1265 for (Find_vars::const_iterator p
= find_vars
.begin();
1266 p
!= find_vars
.end();
1275 // Sort variable initializations. If the initialization expression
1276 // for variable A refers directly or indirectly to the initialization
1277 // expression for variable B, then we must initialize B before A.
1283 : var_(NULL
), init_(NULL
), dep_count_(0)
1286 Var_init(Named_object
* var
, Bstatement
* init
)
1287 : var_(var
), init_(init
), dep_count_(0)
1290 // Return the variable.
1293 { return this->var_
; }
1295 // Return the initialization expression.
1298 { return this->init_
; }
1300 // Return the number of remaining dependencies.
1303 { return this->dep_count_
; }
1305 // Increment the number of dependencies.
1308 { ++this->dep_count_
; }
1310 // Decrement the number of dependencies.
1313 { --this->dep_count_
; }
1316 // The variable being initialized.
1318 // The backend initialization statement.
1320 // The number of initializations this is dependent on. A variable
1321 // initialization should not be emitted if any of its dependencies
1322 // have not yet been resolved.
1326 // For comparing Var_init keys in a map.
1329 operator<(const Var_init
& v1
, const Var_init
& v2
)
1330 { return v1
.var()->name() < v2
.var()->name(); }
1332 typedef std::list
<Var_init
> Var_inits
;
1334 // Sort the variable initializations. The rule we follow is that we
1335 // emit them in the order they appear in the array, except that if the
1336 // initialization expression for a variable V1 depends upon another
1337 // variable V2 then we initialize V1 after V2.
1340 sort_var_inits(Var_inits
* var_inits
)
1342 if (var_inits
->empty())
1345 std::map
<Named_object
*, Var_init
*> var_to_init
;
1347 // A mapping from a variable initialization to a set of
1348 // variable initializations that depend on it.
1349 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1350 Init_deps init_deps
;
1351 bool init_loop
= false;
1353 // Map from variable to Var_init.
1354 for (Var_inits::iterator pvar
= var_inits
->begin();
1355 pvar
!= var_inits
->end();
1358 Named_object
* var
= pvar
->var();
1359 var_to_init
[var
] = &*pvar
;
1362 // Add dependencies to init_deps, and check for cycles.
1363 for (Var_inits::iterator pvar
= var_inits
->begin();
1364 pvar
!= var_inits
->end();
1367 Named_object
* var
= pvar
->var();
1369 const std::vector
<Named_object
*>* refs
=
1370 pvar
->var()->var_value()->init_refs();
1373 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1374 pdep
!= refs
->end();
1377 Named_object
* dep
= *pdep
;
1380 // This is a reference from a variable to itself.
1381 go_error_at(var
->location(),
1382 ("initialization expression for %qs "
1383 "depends upon itself"),
1384 var
->message_name().c_str());
1388 Var_init
* dep_init
= var_to_init
[dep
];
1389 if (dep_init
== NULL
)
1391 // This is a dependency on some variable that doesn't
1392 // have an initializer, so for purposes of
1393 // initialization ordering this is irrelevant.
1397 init_deps
[*dep_init
].insert(&(*pvar
));
1398 pvar
->add_dependency();
1400 // Check for cycles.
1401 const std::vector
<Named_object
*>* deprefs
=
1402 dep_init
->var()->var_value()->init_refs();
1403 if (deprefs
== NULL
)
1405 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1407 pdepdep
!= deprefs
->end();
1410 if (*pdepdep
== var
)
1412 go_error_at(var
->location(),
1413 ("initialization expressions for %qs and "
1414 "%qs depend upon each other"),
1415 var
->message_name().c_str(),
1416 dep
->message_name().c_str());
1417 go_inform(dep
->location(), "%qs defined here",
1418 dep
->message_name().c_str());
1426 var_to_init
.clear();
1428 // If there are no dependencies then the declaration order is sorted.
1429 if (!init_deps
.empty() && !init_loop
)
1431 // Otherwise, sort variable initializations by emitting all variables with
1432 // no dependencies in declaration order. VAR_INITS is already in
1433 // declaration order.
1435 while (!var_inits
->empty())
1437 Var_inits::iterator v1
;;
1438 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1440 if (v1
->dep_count() == 0)
1443 go_assert(v1
!= var_inits
->end());
1445 // V1 either has no dependencies or its dependencies have already
1446 // been emitted, add it to READY next. When V1 is emitted, remove
1447 // a dependency from each V that depends on V1.
1448 ready
.splice(ready
.end(), *var_inits
, v1
);
1450 Init_deps::iterator p1
= init_deps
.find(*v1
);
1451 if (p1
!= init_deps
.end())
1453 std::set
<Var_init
*> resolved
= p1
->second
;
1454 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1455 pv
!= resolved
.end();
1457 (*pv
)->remove_dependency();
1458 init_deps
.erase(p1
);
1461 var_inits
->swap(ready
);
1462 go_assert(init_deps
.empty());
1466 // Give an error if the initialization expression for VAR depends on
1467 // itself. We only check if INIT is not NULL and there is no
1468 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1469 // which we will interpret as a loop.
1472 Gogo::check_self_dep(Named_object
* var
)
1474 Expression
* init
= var
->var_value()->init();
1475 Block
* preinit
= var
->var_value()->preinit();
1476 Named_object
* dep
= this->var_depends_on(var
->var_value());
1479 && expression_requires(init
, preinit
, NULL
, var
))
1480 go_error_at(var
->location(),
1481 "initialization expression for %qs depends upon itself",
1482 var
->message_name().c_str());
1485 // Write out the global definitions.
1488 Gogo::write_globals()
1490 this->build_interface_method_tables();
1492 Bindings
* bindings
= this->current_bindings();
1494 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1495 p
!= bindings
->end_declarations();
1498 // If any function declarations needed a descriptor, make sure
1500 Named_object
* no
= p
->second
;
1501 if (no
->is_function_declaration())
1502 no
->func_declaration_value()->build_backend_descriptor(this);
1505 // Lists of globally declared types, variables, constants, and functions
1506 // that must be defined.
1507 std::vector
<Btype
*> type_decls
;
1508 std::vector
<Bvariable
*> var_decls
;
1509 std::vector
<Bexpression
*> const_decls
;
1510 std::vector
<Bfunction
*> func_decls
;
1512 // The init function declaration and associated Bfunction, if necessary.
1513 Named_object
* init_fndecl
= NULL
;
1514 Bfunction
* init_bfn
= NULL
;
1516 std::vector
<Bstatement
*> init_stmts
;
1517 std::vector
<Bstatement
*> var_init_stmts
;
1519 if (this->is_main_package())
1521 init_fndecl
= this->initialization_function_decl();
1522 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1525 // A list of variable initializations.
1526 Var_inits var_inits
;
1528 // A list of variables which need to be registered with the garbage
1530 size_t count_definitions
= bindings
->size_definitions();
1531 std::vector
<Named_object
*> var_gc
;
1532 var_gc
.reserve(count_definitions
);
1534 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1535 p
!= bindings
->end_definitions();
1538 Named_object
* no
= *p
;
1539 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1541 // There is nothing to do for a package.
1542 if (no
->is_package())
1545 // There is nothing to do for an object which was imported from
1546 // a different package into the global scope.
1547 if (no
->package() != NULL
)
1550 // Skip blank named functions and constants.
1551 if ((no
->is_function() && no
->func_value()->is_sink())
1552 || (no
->is_const() && no
->const_value()->is_sink()))
1555 // Skip global sink variables with static initializers. With
1556 // non-static initializers we have to evaluate for side effects,
1557 // and we wind up initializing a dummy variable. That is not
1558 // ideal but it works and it's a rare case.
1559 if (no
->is_variable()
1560 && no
->var_value()->is_global_sink()
1561 && !no
->var_value()->has_pre_init()
1562 && (no
->var_value()->init() == NULL
1563 || no
->var_value()->init()->is_static_initializer()))
1566 // There is nothing useful we can output for constants which
1567 // have ideal or non-integral type.
1570 Type
* type
= no
->const_value()->type();
1572 type
= no
->const_value()->expr()->type();
1573 if (type
->is_abstract() || !type
->is_numeric_type())
1577 if (!no
->is_variable())
1578 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1581 Variable
* var
= no
->var_value();
1582 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1583 var_decls
.push_back(bvar
);
1585 // Check for a sink variable, which may be used to run an
1586 // initializer purely for its side effects.
1587 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1589 Bstatement
* var_init_stmt
= NULL
;
1590 if (!var
->has_pre_init())
1592 // If the backend representation of the variable initializer is
1593 // constant, we can just set the initial value using
1594 // global_var_set_init instead of during the init() function.
1595 // The initializer is constant if it is the zero-value of the
1596 // variable's type or if the initial value is an immutable value
1597 // that is not copied to the heap.
1598 bool is_static_initializer
= false;
1599 if (var
->init() == NULL
)
1600 is_static_initializer
= true;
1603 Type
* var_type
= var
->type();
1604 Expression
* init
= var
->init();
1605 Expression
* init_cast
=
1606 Expression::make_cast(var_type
, init
, var
->location());
1607 is_static_initializer
= init_cast
->is_static_initializer();
1610 // Non-constant variable initializations might need to create
1611 // temporary variables, which will need the initialization
1612 // function as context.
1613 Named_object
* var_init_fn
;
1614 if (is_static_initializer
)
1618 if (init_fndecl
== NULL
)
1620 init_fndecl
= this->initialization_function_decl();
1621 Function
* func
= init_fndecl
->func_value();
1622 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1624 var_init_fn
= init_fndecl
;
1626 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1628 if (var_binit
== NULL
)
1630 else if (is_static_initializer
)
1632 if (expression_requires(var
->init(), NULL
,
1633 this->var_depends_on(var
), no
))
1634 go_error_at(no
->location(),
1635 "initialization expression for %qs depends "
1637 no
->message_name().c_str());
1638 this->backend()->global_variable_set_init(bvar
, var_binit
);
1642 this->backend()->expression_statement(init_bfn
, var_binit
);
1645 Location loc
= var
->location();
1646 Bexpression
* var_expr
=
1647 this->backend()->var_expression(bvar
, loc
);
1649 this->backend()->assignment_statement(init_bfn
, var_expr
,
1655 // We are going to create temporary variables which
1656 // means that we need an fndecl.
1657 if (init_fndecl
== NULL
)
1658 init_fndecl
= this->initialization_function_decl();
1660 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1661 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1664 if (var_init_stmt
!= NULL
)
1666 if (var
->init() == NULL
&& !var
->has_pre_init())
1667 var_init_stmts
.push_back(var_init_stmt
);
1669 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1671 else if (this->var_depends_on(var
) != NULL
)
1673 // This variable is initialized from something that is
1674 // not in its init or preinit. This variable needs to
1675 // participate in dependency analysis sorting, in case
1676 // some other variable depends on this one.
1677 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1678 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1679 Bstatement
* zero_stmt
=
1680 this->backend()->expression_statement(init_bfn
, zero
);
1681 var_inits
.push_back(Var_init(no
, zero_stmt
));
1684 // Collect a list of all global variables with pointers,
1685 // to register them for the garbage collector.
1686 if (!is_sink
&& var
->type()->has_pointer())
1688 // Avoid putting runtime.gcRoots itself on the list.
1689 if (this->compiling_runtime()
1690 && this->package_name() == "runtime"
1691 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1692 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1695 var_gc
.push_back(no
);
1700 // Output inline functions, which are in different packages.
1701 for (std::vector
<Named_object
*>::const_iterator p
=
1702 this->imported_inline_functions_
.begin();
1703 p
!= this->imported_inline_functions_
.end();
1705 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1707 // Build the list of type descriptors.
1708 this->build_type_descriptor_list();
1710 if (this->is_main_package())
1712 // Register the type descriptor lists, so that at run time
1713 // the reflect package can find compiler-created types, and
1714 // deduplicate if the same type is created with reflection.
1715 // This needs to be done before calling any package's init
1716 // function, as it may create type through reflection.
1717 this->register_type_descriptors(init_stmts
, init_bfn
);
1719 // Initialize imported packages.
1720 this->init_imports(init_stmts
, init_bfn
);
1723 // Register global variables with the garbage collector.
1724 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1726 // Simple variable initializations, after all variables are
1728 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1730 // Complete variable initializations, first sorting them into a
1732 if (!var_inits
.empty())
1734 sort_var_inits(&var_inits
);
1735 for (Var_inits::const_iterator p
= var_inits
.begin();
1736 p
!= var_inits
.end();
1738 init_stmts
.push_back(p
->init());
1741 // After all the variables are initialized, call the init
1742 // functions if there are any. Init functions take no arguments, so
1743 // we pass in EMPTY_ARGS to call them.
1744 std::vector
<Bexpression
*> empty_args
;
1745 for (std::vector
<Named_object
*>::const_iterator p
=
1746 this->init_functions_
.begin();
1747 p
!= this->init_functions_
.end();
1750 Location func_loc
= (*p
)->location();
1751 Function
* func
= (*p
)->func_value();
1752 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1753 Bexpression
* func_code
=
1754 this->backend()->function_code_expression(initfn
, func_loc
);
1755 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1758 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1759 init_stmts
.push_back(ist
);
1762 // Set up a magic function to do all the initialization actions.
1763 // This will be called if this package is imported.
1764 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1765 if (this->need_init_fn_
|| this->is_main_package())
1768 this->create_initialization_function(init_fndecl
, init_fncode
);
1769 if (init_fndecl
!= NULL
)
1770 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1773 // We should not have seen any new bindings created during the conversion.
1774 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1776 // Define all globally declared values.
1778 this->backend()->write_global_definitions(type_decls
, const_decls
,
1779 func_decls
, var_decls
);
1782 // Return the current block.
1785 Gogo::current_block()
1787 if (this->functions_
.empty())
1790 return this->functions_
.back().blocks
.back();
1793 // Look up a name in the current binding contour. If PFUNCTION is not
1794 // NULL, set it to the function in which the name is defined, or NULL
1795 // if the name is defined in global scope.
1798 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1800 if (pfunction
!= NULL
)
1803 if (Gogo::is_sink_name(name
))
1804 return Named_object::make_sink();
1806 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1807 p
!= this->functions_
.rend();
1810 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1813 if (pfunction
!= NULL
)
1814 *pfunction
= p
->function
;
1819 if (this->package_
!= NULL
)
1821 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1824 if (ret
->package() != NULL
)
1826 std::string dot_alias
= "." + ret
->package()->package_name();
1827 ret
->package()->note_usage(dot_alias
);
1833 // We do not look in the global namespace. If we did, the global
1834 // namespace would effectively hide names which were defined in
1835 // package scope which we have not yet seen. Instead,
1836 // define_global_names is called after parsing is over to connect
1837 // undefined names at package scope with names defined at global
1843 // Look up a name in the current block, without searching enclosing
1847 Gogo::lookup_in_block(const std::string
& name
) const
1849 go_assert(!this->functions_
.empty());
1850 go_assert(!this->functions_
.back().blocks
.empty());
1851 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1854 // Look up a name in the global namespace.
1857 Gogo::lookup_global(const char* name
) const
1859 return this->globals_
->lookup(name
);
1862 // Add an imported package.
1865 Gogo::add_imported_package(const std::string
& real_name
,
1866 const std::string
& alias_arg
,
1867 bool is_alias_exported
,
1868 const std::string
& pkgpath
,
1869 const std::string
& pkgpath_symbol
,
1871 bool* padd_to_globals
)
1873 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1874 ret
->set_package_name(real_name
, location
);
1876 *padd_to_globals
= false;
1878 if (alias_arg
== "_")
1880 else if (alias_arg
== ".")
1882 *padd_to_globals
= true;
1883 std::string dot_alias
= "." + real_name
;
1884 ret
->add_alias(dot_alias
, location
);
1888 std::string alias
= alias_arg
;
1892 is_alias_exported
= Lex::is_exported_name(alias
);
1894 ret
->add_alias(alias
, location
);
1895 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1896 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1897 if (!no
->is_package())
1904 // Register a package. This package may or may not be imported. This
1905 // returns the Package structure for the package, creating if it
1906 // necessary. LOCATION is the location of the import statement that
1907 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1908 // for names in the package; it may be the empty string, in which case
1909 // we either get it later or make a guess when we need it.
1912 Gogo::register_package(const std::string
& pkgpath
,
1913 const std::string
& pkgpath_symbol
, Location location
)
1915 Package
* package
= NULL
;
1916 std::pair
<Packages::iterator
, bool> ins
=
1917 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1920 // We have seen this package name before.
1921 package
= ins
.first
->second
;
1922 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1923 if (!pkgpath_symbol
.empty())
1924 package
->set_pkgpath_symbol(pkgpath_symbol
);
1925 if (Linemap::is_unknown_location(package
->location()))
1926 package
->set_location(location
);
1930 // First time we have seen this package name.
1931 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1932 go_assert(ins
.first
->second
== NULL
);
1933 ins
.first
->second
= package
;
1939 // Return the pkgpath symbol for a package, given the pkgpath.
1942 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1944 Packages::iterator p
= this->packages_
.find(pkgpath
);
1945 go_assert(p
!= this->packages_
.end());
1946 return p
->second
->pkgpath_symbol();
1949 // Start compiling a function.
1952 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1953 bool add_method_to_type
, Location location
)
1955 bool at_top_level
= this->functions_
.empty();
1957 Block
* block
= new Block(NULL
, location
);
1959 Named_object
* enclosing
= (at_top_level
1961 : this->functions_
.back().function
);
1963 Function
* function
= new Function(type
, enclosing
, block
, location
);
1965 if (type
->is_method())
1967 const Typed_identifier
* receiver
= type
->receiver();
1968 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1969 true, true, location
);
1970 std::string rname
= receiver
->name();
1971 unsigned rcounter
= 0;
1973 // We need to give a nameless receiver parameter a synthesized name to
1974 // avoid having it clash with some other nameless param. FIXME.
1975 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
1977 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1980 const Typed_identifier_list
* parameters
= type
->parameters();
1981 bool is_varargs
= type
->is_varargs();
1982 unsigned pcounter
= 0;
1983 if (parameters
!= NULL
)
1985 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1986 p
!= parameters
->end();
1989 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1991 if (is_varargs
&& p
+ 1 == parameters
->end())
1992 param
->set_is_varargs_parameter();
1994 std::string pname
= p
->name();
1996 // We need to give each nameless parameter a non-empty name to avoid
1997 // having it clash with some other nameless param. FIXME.
1998 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
2000 block
->bindings()->add_variable(pname
, NULL
, param
);
2004 function
->create_result_variables(this);
2006 const std::string
* pname
;
2007 std::string nested_name
;
2008 bool is_init
= false;
2009 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
2011 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
2012 || (type
->results() != NULL
&& !type
->results()->empty()))
2013 go_error_at(location
,
2014 "func init must have no arguments and no return values");
2015 // There can be multiple "init" functions, so give them each a
2017 nested_name
= this->init_function_name();
2018 pname
= &nested_name
;
2021 else if (!name
.empty())
2025 // Invent a name for a nested function.
2026 nested_name
= this->nested_function_name(enclosing
);
2027 pname
= &nested_name
;
2031 if (Gogo::is_sink_name(*pname
))
2033 std::string
sname(this->sink_function_name());
2034 ret
= Named_object::make_function(sname
, NULL
, function
);
2035 ret
->func_value()->set_is_sink();
2037 if (!type
->is_method())
2038 ret
= this->package_
->bindings()->add_named_object(ret
);
2039 else if (add_method_to_type
)
2041 // We should report errors even for sink methods.
2042 Type
* rtype
= type
->receiver()->type();
2043 // Avoid points_to and deref to avoid getting an error if
2044 // the type is not yet defined.
2045 if (rtype
->classification() == Type::TYPE_POINTER
)
2046 rtype
= rtype
->points_to();
2047 while (rtype
->named_type() != NULL
2048 && rtype
->named_type()->is_alias())
2049 rtype
= rtype
->named_type()->real_type()->forwarded();
2050 if (rtype
->is_error_type())
2052 else if (rtype
->named_type() != NULL
)
2054 if (rtype
->named_type()->named_object()->package() != NULL
)
2055 go_error_at(type
->receiver()->location(),
2056 "may not define methods on non-local type");
2058 else if (rtype
->forward_declaration_type() != NULL
)
2060 // Go ahead and add the method in case we need to report
2061 // an error when we see the definition.
2062 rtype
->forward_declaration_type()->add_existing_method(ret
);
2065 go_error_at(type
->receiver()->location(),
2066 ("invalid receiver type "
2067 "(receiver must be a named type)"));
2070 else if (!type
->is_method())
2072 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
2073 if (!ret
->is_function() || ret
->func_value() != function
)
2075 // Redefinition error. Invent a name to avoid knockon
2077 std::string
rname(this->redefined_function_name());
2078 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
2083 if (!add_method_to_type
)
2084 ret
= Named_object::make_function(name
, NULL
, function
);
2087 go_assert(at_top_level
);
2088 Type
* rtype
= type
->receiver()->type();
2090 while (rtype
->named_type() != NULL
2091 && rtype
->named_type()->is_alias())
2092 rtype
= rtype
->named_type()->real_type()->forwarded();
2094 // We want to look through the pointer created by the
2095 // parser, without getting an error if the type is not yet
2097 if (rtype
->classification() == Type::TYPE_POINTER
)
2098 rtype
= rtype
->points_to();
2100 while (rtype
->named_type() != NULL
2101 && rtype
->named_type()->is_alias())
2102 rtype
= rtype
->named_type()->real_type()->forwarded();
2104 if (rtype
->is_error_type())
2105 ret
= Named_object::make_function(name
, NULL
, function
);
2106 else if (rtype
->named_type() != NULL
)
2108 if (rtype
->named_type()->named_object()->package() != NULL
)
2110 go_error_at(type
->receiver()->location(),
2111 "may not define methods on non-local type");
2112 ret
= Named_object::make_function(name
, NULL
, function
);
2116 ret
= rtype
->named_type()->add_method(name
, function
);
2117 if (!ret
->is_function())
2119 // Redefinition error.
2120 ret
= Named_object::make_function(name
, NULL
, function
);
2124 else if (rtype
->forward_declaration_type() != NULL
)
2126 Named_object
* type_no
=
2127 rtype
->forward_declaration_type()->named_object();
2128 if (type_no
->is_unknown())
2130 // If we are seeing methods it really must be a
2131 // type. Declare it as such. An alternative would
2132 // be to support lists of methods for unknown
2133 // expressions. Either way the error messages if
2134 // this is not a type are going to get confusing.
2135 Named_object
* declared
=
2136 this->declare_package_type(type_no
->name(),
2137 type_no
->location());
2139 == type_no
->unknown_value()->real_named_object());
2141 ret
= rtype
->forward_declaration_type()->add_method(name
,
2146 go_error_at(type
->receiver()->location(),
2147 ("invalid receiver type (receiver must "
2148 "be a named type)"));
2149 ret
= Named_object::make_function(name
, NULL
, function
);
2152 this->package_
->bindings()->add_method(ret
);
2155 this->functions_
.resize(this->functions_
.size() + 1);
2156 Open_function
& of(this->functions_
.back());
2158 of
.blocks
.push_back(block
);
2162 this->init_functions_
.push_back(ret
);
2163 this->need_init_fn_
= true;
2169 // Finish compiling a function.
2172 Gogo::finish_function(Location location
)
2174 this->finish_block(location
);
2175 go_assert(this->functions_
.back().blocks
.empty());
2176 this->functions_
.pop_back();
2179 // Return the current function.
2182 Gogo::current_function() const
2184 go_assert(!this->functions_
.empty());
2185 return this->functions_
.back().function
;
2188 // Start a new block.
2191 Gogo::start_block(Location location
)
2193 go_assert(!this->functions_
.empty());
2194 Block
* block
= new Block(this->current_block(), location
);
2195 this->functions_
.back().blocks
.push_back(block
);
2201 Gogo::finish_block(Location location
)
2203 go_assert(!this->functions_
.empty());
2204 go_assert(!this->functions_
.back().blocks
.empty());
2205 Block
* block
= this->functions_
.back().blocks
.back();
2206 this->functions_
.back().blocks
.pop_back();
2207 block
->set_end_location(location
);
2211 // Add an erroneous name.
2214 Gogo::add_erroneous_name(const std::string
& name
)
2216 return this->package_
->bindings()->add_erroneous_name(name
);
2219 // Add an unknown name.
2222 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2224 return this->package_
->bindings()->add_unknown_name(name
, location
);
2227 // Declare a function.
2230 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2233 if (!type
->is_method())
2234 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2238 // We don't bother to add this to the list of global
2240 Type
* rtype
= type
->receiver()->type();
2242 while (rtype
->named_type() != NULL
2243 && rtype
->named_type()->is_alias())
2244 rtype
= rtype
->named_type()->real_type()->forwarded();
2246 // We want to look through the pointer created by the
2247 // parser, without getting an error if the type is not yet
2249 if (rtype
->classification() == Type::TYPE_POINTER
)
2250 rtype
= rtype
->points_to();
2252 while (rtype
->named_type() != NULL
2253 && rtype
->named_type()->is_alias())
2254 rtype
= rtype
->named_type()->real_type()->forwarded();
2256 if (rtype
->is_error_type())
2258 else if (rtype
->named_type() != NULL
)
2259 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2261 else if (rtype
->forward_declaration_type() != NULL
)
2263 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2264 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2268 go_error_at(type
->receiver()->location(),
2269 "invalid receiver type (receiver must be a named type)");
2270 return Named_object::make_erroneous_name(name
);
2275 // Add a label definition.
2278 Gogo::add_label_definition(const std::string
& label_name
,
2281 go_assert(!this->functions_
.empty());
2282 Function
* func
= this->functions_
.back().function
->func_value();
2283 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2284 this->add_statement(Statement::make_label_statement(label
, location
));
2288 // Add a label reference.
2291 Gogo::add_label_reference(const std::string
& label_name
,
2292 Location location
, bool issue_goto_errors
)
2294 go_assert(!this->functions_
.empty());
2295 Function
* func
= this->functions_
.back().function
->func_value();
2296 return func
->add_label_reference(this, label_name
, location
,
2300 // Return the current binding state.
2303 Gogo::bindings_snapshot(Location location
)
2305 return new Bindings_snapshot(this->current_block(), location
);
2311 Gogo::add_statement(Statement
* statement
)
2313 go_assert(!this->functions_
.empty()
2314 && !this->functions_
.back().blocks
.empty());
2315 this->functions_
.back().blocks
.back()->add_statement(statement
);
2321 Gogo::add_block(Block
* block
, Location location
)
2323 go_assert(!this->functions_
.empty()
2324 && !this->functions_
.back().blocks
.empty());
2325 Statement
* statement
= Statement::make_block_statement(block
, location
);
2326 this->functions_
.back().blocks
.back()->add_statement(statement
);
2332 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2335 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2341 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2343 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2345 if (!this->in_global_scope() && no
->is_type())
2347 Named_object
* f
= this->functions_
.back().function
;
2349 if (f
->is_function())
2350 index
= f
->func_value()->new_local_type_index();
2353 no
->type_value()->set_in_function(f
, index
);
2357 // Add a named type.
2360 Gogo::add_named_type(Named_type
* type
)
2362 go_assert(this->in_global_scope());
2363 this->current_bindings()->add_named_type(type
);
2369 Gogo::declare_type(const std::string
& name
, Location location
)
2371 Bindings
* bindings
= this->current_bindings();
2372 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2373 if (!this->in_global_scope() && no
->is_type_declaration())
2375 Named_object
* f
= this->functions_
.back().function
;
2377 if (f
->is_function())
2378 index
= f
->func_value()->new_local_type_index();
2381 no
->type_declaration_value()->set_in_function(f
, index
);
2386 // Declare a type at the package level.
2389 Gogo::declare_package_type(const std::string
& name
, Location location
)
2391 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2394 // Declare a function at the package level.
2397 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2400 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2404 // Add a function declaration to the list of functions we may want to
2408 Gogo::add_imported_inlinable_function(Named_object
* no
)
2410 go_assert(no
->is_function_declaration());
2411 Function_declaration
* fd
= no
->func_declaration_value();
2412 if (fd
->is_on_inlinable_list())
2414 this->imported_inlinable_functions_
.push_back(no
);
2415 fd
->set_is_on_inlinable_list();
2418 // Define a type which was already declared.
2421 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2423 this->current_bindings()->define_type(no
, type
);
2429 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2431 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2434 // In a function the middle-end wants to see a DECL_EXPR node.
2436 && no
->is_variable()
2437 && !no
->var_value()->is_parameter()
2438 && !this->functions_
.empty())
2439 this->add_statement(Statement::make_variable_declaration(no
));
2445 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2447 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2450 go_assert(strlen(tag
) < 10);
2451 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2458 // Add a sink--a reference to the blank identifier _.
2463 return Named_object::make_sink();
2466 // Add a named object for a dot import.
2469 Gogo::add_dot_import_object(Named_object
* no
)
2471 // If the name already exists, then it was defined in some file seen
2472 // earlier. If the earlier name is just a declaration, don't add
2473 // this name, because that will cause the previous declaration to
2474 // merge to this imported name, which should not happen. Just add
2475 // this name to the list of file block names to get appropriate
2476 // errors if we see a later definition.
2477 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2478 if (e
!= NULL
&& e
->package() == NULL
)
2480 if (e
->is_unknown())
2482 if (e
->package() == NULL
2483 && (e
->is_type_declaration()
2484 || e
->is_function_declaration()
2485 || e
->is_unknown()))
2487 this->add_file_block_name(no
->name(), no
->location());
2492 this->current_bindings()->add_named_object(no
);
2495 // Add a linkname. This implements the go:linkname compiler directive.
2496 // We only support this for functions and function declarations.
2499 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2500 const std::string
& ext_name
, Location loc
)
2503 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2506 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2507 else if (no
->is_function())
2509 if (ext_name
.empty())
2510 no
->func_value()->set_is_exported_by_linkname();
2512 no
->func_value()->set_asm_name(ext_name
);
2514 else if (no
->is_function_declaration())
2516 if (ext_name
.empty())
2518 ("%<//go:linkname%> missing external name "
2519 "for declaration of %s"),
2522 no
->func_declaration_value()->set_asm_name(ext_name
);
2526 ("%s is not a function; "
2527 "%<//go:linkname%> is only supported for functions"),
2531 // Mark all local variables used. This is used when some types of
2532 // parse error occur.
2535 Gogo::mark_locals_used()
2537 for (Open_functions::iterator pf
= this->functions_
.begin();
2538 pf
!= this->functions_
.end();
2541 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2542 pb
!= pf
->blocks
.end();
2544 (*pb
)->bindings()->mark_locals_used();
2548 // Record that we've seen an interface type.
2551 Gogo::record_interface_type(Interface_type
* itype
)
2553 this->interface_types_
.push_back(itype
);
2556 // Define the global names. We do this only after parsing all the
2557 // input files, because the program might define the global names
2561 Gogo::define_global_names()
2563 if (this->is_main_package())
2565 // Every Go program has to import the runtime package, so that
2566 // it is properly initialized. We can't use
2567 // predeclared_location here as it will cause runtime functions
2568 // to appear to be builtin functions.
2569 this->import_package("runtime", "_", false, false,
2570 this->package_
->location());
2573 for (Bindings::const_declarations_iterator p
=
2574 this->globals_
->begin_declarations();
2575 p
!= this->globals_
->end_declarations();
2578 Named_object
* global_no
= p
->second
;
2579 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2580 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2584 if (no
->is_type_declaration())
2586 if (global_no
->is_type())
2588 if (no
->type_declaration_value()->has_methods())
2590 for (std::vector
<Named_object
*>::const_iterator pm
=
2591 no
->type_declaration_value()->methods()->begin();
2592 pm
!= no
->type_declaration_value()->methods()->end();
2594 go_error_at((*pm
)->location(),
2595 "may not define methods on non-local type");
2597 no
->set_type_value(global_no
->type_value());
2601 go_error_at(no
->location(), "expected type");
2602 Type
* errtype
= Type::make_error_type();
2604 Named_object::make_type("erroneous_type", NULL
, errtype
,
2605 Linemap::predeclared_location());
2606 no
->set_type_value(err
->type_value());
2609 else if (no
->is_unknown())
2610 no
->unknown_value()->set_real_named_object(global_no
);
2613 // Give an error if any name is defined in both the package block
2614 // and the file block. For example, this can happen if one file
2615 // imports "fmt" and another file defines a global variable fmt.
2616 for (Bindings::const_declarations_iterator p
=
2617 this->package_
->bindings()->begin_declarations();
2618 p
!= this->package_
->bindings()->end_declarations();
2621 if (p
->second
->is_unknown()
2622 && p
->second
->unknown_value()->real_named_object() == NULL
)
2624 // No point in warning about an undefined name, as we will
2625 // get other errors later anyhow.
2628 File_block_names::const_iterator pf
=
2629 this->file_block_names_
.find(p
->second
->name());
2630 if (pf
!= this->file_block_names_
.end())
2632 std::string n
= p
->second
->message_name();
2633 go_error_at(p
->second
->location(),
2634 "%qs defined as both imported name and global name",
2636 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2639 // No package scope identifier may be named "init".
2640 if (!p
->second
->is_function()
2641 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2643 go_error_at(p
->second
->location(),
2644 "cannot declare init - must be func");
2649 // Clear out names in file scope.
2652 Gogo::clear_file_scope()
2654 this->package_
->bindings()->clear_file_scope(this);
2656 // Warn about packages which were imported but not used.
2657 bool quiet
= saw_errors();
2658 for (Packages::iterator p
= this->packages_
.begin();
2659 p
!= this->packages_
.end();
2662 Package
* package
= p
->second
;
2663 if (package
!= this->package_
&& !quiet
)
2665 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2666 p1
!= package
->aliases().end();
2669 if (!p1
->second
->used())
2671 // Give a more refined error message if the alias name is known.
2672 std::string pkg_name
= package
->package_name();
2673 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2675 go_error_at(p1
->second
->location(),
2676 "imported and not used: %s as %s",
2677 Gogo::message_name(pkg_name
).c_str(),
2678 Gogo::message_name(p1
->first
).c_str());
2681 go_error_at(p1
->second
->location(),
2682 "imported and not used: %s",
2683 Gogo::message_name(pkg_name
).c_str());
2687 package
->clear_used();
2690 this->current_file_imported_unsafe_
= false;
2691 this->current_file_imported_embed_
= false;
2694 // Queue up a type-specific hash function for later writing. These
2695 // are written out in write_specific_type_functions, called after the
2696 // parse tree is lowered.
2699 Gogo::queue_hash_function(Type
* type
, int64_t size
, Backend_name
* bname
,
2700 Function_type
* hash_fntype
)
2702 go_assert(!this->specific_type_functions_are_written_
);
2703 go_assert(!this->in_global_scope());
2704 Specific_type_function::Specific_type_function_kind kind
=
2705 Specific_type_function::SPECIFIC_HASH
;
2706 Specific_type_function
* tsf
= new Specific_type_function(type
, NULL
, size
,
2709 this->specific_type_functions_
.push_back(tsf
);
2712 // Queue up a type-specific equal function for later writing. These
2713 // are written out in write_specific_type_functions, called after the
2714 // parse tree is lowered.
2717 Gogo::queue_equal_function(Type
* type
, Named_type
* name
, int64_t size
,
2718 Backend_name
* bname
, Function_type
* equal_fntype
)
2720 go_assert(!this->specific_type_functions_are_written_
);
2721 go_assert(!this->in_global_scope());
2722 Specific_type_function::Specific_type_function_kind kind
=
2723 Specific_type_function::SPECIFIC_EQUAL
;
2724 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2727 this->specific_type_functions_
.push_back(tsf
);
2730 // Look for types which need specific hash or equality functions.
2732 class Specific_type_functions
: public Traverse
2735 Specific_type_functions(Gogo
* gogo
)
2736 : Traverse(traverse_types
),
2748 Specific_type_functions::type(Type
* t
)
2750 switch (t
->classification())
2752 case Type::TYPE_NAMED
:
2754 Named_type
* nt
= t
->named_type();
2756 return TRAVERSE_CONTINUE
;
2757 if (t
->needs_specific_type_functions(this->gogo_
))
2758 t
->equal_function(this->gogo_
, nt
, NULL
);
2760 // If this is a struct type, we don't want to make functions
2761 // for the unnamed struct.
2762 Type
* rt
= nt
->real_type();
2763 if (rt
->struct_type() == NULL
)
2765 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2766 return TRAVERSE_EXIT
;
2770 // If this type is defined in another package, then we don't
2771 // need to worry about the unexported fields.
2772 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2773 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2774 for (Struct_field_list::const_iterator p
= fields
->begin();
2778 if (is_defined_elsewhere
2779 && Gogo::is_hidden_name(p
->field_name()))
2781 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2782 return TRAVERSE_EXIT
;
2786 return TRAVERSE_SKIP_COMPONENTS
;
2789 case Type::TYPE_STRUCT
:
2790 case Type::TYPE_ARRAY
:
2791 if (t
->needs_specific_type_functions(this->gogo_
))
2792 t
->equal_function(this->gogo_
, NULL
, NULL
);
2795 case Type::TYPE_MAP
:
2797 Type
* key_type
= t
->map_type()->key_type()->unalias();
2798 if (key_type
->needs_specific_type_functions(this->gogo_
))
2799 key_type
->hash_function(this->gogo_
, NULL
);
2807 return TRAVERSE_CONTINUE
;
2810 // Write out type specific functions.
2813 Gogo::write_specific_type_functions()
2815 Specific_type_functions
stf(this);
2816 this->traverse(&stf
);
2818 while (!this->specific_type_functions_
.empty())
2820 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2821 this->specific_type_functions_
.pop_back();
2822 if (tsf
->kind
== Specific_type_function::SPECIFIC_HASH
)
2823 tsf
->type
->write_hash_function(this, tsf
->size
, &tsf
->bname
,
2826 tsf
->type
->write_equal_function(this, tsf
->name
, tsf
->size
,
2827 &tsf
->bname
, tsf
->fntype
);
2830 this->specific_type_functions_are_written_
= true;
2833 // Traverse the tree.
2836 Gogo::traverse(Traverse
* traverse
)
2838 // Traverse the current package first for consistency. The other
2839 // packages will only contain imported types, constants, and
2841 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2843 for (Packages::const_iterator p
= this->packages_
.begin();
2844 p
!= this->packages_
.end();
2847 if (p
->second
!= this->package_
)
2849 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2855 // Add a type to verify. This is used for types of sink variables, in
2856 // order to give appropriate error messages.
2859 Gogo::add_type_to_verify(Type
* type
)
2861 this->verify_types_
.push_back(type
);
2864 // Traversal class used to verify types.
2866 class Verify_types
: public Traverse
2869 Verify_types(Gogo
* gogo
)
2870 : Traverse(traverse_types
),
2881 // Verify that a type is correct.
2884 Verify_types::type(Type
* t
)
2886 if (!t
->verify(this->gogo_
))
2887 return TRAVERSE_SKIP_COMPONENTS
;
2888 return TRAVERSE_CONTINUE
;
2891 // Verify that all types are correct.
2894 Gogo::verify_types()
2896 Verify_types
traverse(this);
2897 this->traverse(&traverse
);
2899 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2900 p
!= this->verify_types_
.end();
2903 this->verify_types_
.clear();
2906 // Traversal class used to lower parse tree.
2908 class Lower_parse_tree
: public Traverse
2911 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2912 : Traverse(traverse_variables
2913 | traverse_constants
2914 | traverse_functions
2915 | traverse_statements
2916 | traverse_expressions
),
2917 gogo_(gogo
), function_(function
), inserter_()
2921 set_inserter(const Statement_inserter
* inserter
)
2922 { this->inserter_
= *inserter
; }
2925 variable(Named_object
*);
2928 constant(Named_object
*, bool);
2931 function(Named_object
*);
2934 statement(Block
*, size_t* pindex
, Statement
*);
2937 expression(Expression
**);
2942 // The function we are traversing.
2943 Named_object
* function_
;
2944 // Current statement inserter for use by expressions.
2945 Statement_inserter inserter_
;
2951 Lower_parse_tree::variable(Named_object
* no
)
2953 if (!no
->is_variable())
2954 return TRAVERSE_CONTINUE
;
2956 if (no
->is_variable() && no
->var_value()->is_global())
2958 // Global variables can have loops in their initialization
2959 // expressions. This is handled in lower_init_expression.
2960 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2962 return TRAVERSE_CONTINUE
;
2965 // This is a local variable. We are going to return
2966 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2967 // initialization expression when we reach the variable declaration
2968 // statement. However, that means that we need to traverse the type
2970 if (no
->var_value()->has_type())
2972 Type
* type
= no
->var_value()->type();
2975 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2976 return TRAVERSE_EXIT
;
2979 go_assert(!no
->var_value()->has_pre_init());
2981 return TRAVERSE_SKIP_COMPONENTS
;
2984 // Lower constants. We handle constants specially so that we can set
2985 // the right value for the predeclared constant iota. This works in
2986 // conjunction with the way we lower Const_expression objects.
2989 Lower_parse_tree::constant(Named_object
* no
, bool)
2991 Named_constant
* nc
= no
->const_value();
2993 // Don't get into trouble if the constant's initializer expression
2994 // refers to the constant itself.
2996 return TRAVERSE_CONTINUE
;
2999 nc
->traverse_expression(this);
3001 nc
->clear_lowering();
3003 // We will traverse the expression a second time, but that will be
3006 return TRAVERSE_CONTINUE
;
3009 // Lower the body of a function, and set the closure type. Record the
3010 // function while lowering it, so that we can pass it down when
3011 // lowering an expression.
3014 Lower_parse_tree::function(Named_object
* no
)
3016 go_assert(this->function_
== NULL
);
3017 this->function_
= no
;
3018 int t
= no
->func_value()->traverse(this);
3019 this->function_
= NULL
;
3021 if (t
== TRAVERSE_EXIT
)
3023 return TRAVERSE_SKIP_COMPONENTS
;
3026 // Lower statement parse trees.
3029 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3031 // Because we explicitly traverse the statement's contents
3032 // ourselves, we want to skip block statements here. There is
3033 // nothing to lower in a block statement.
3034 if (sorig
->is_block_statement())
3035 return TRAVERSE_CONTINUE
;
3037 Statement_inserter
hold_inserter(this->inserter_
);
3038 this->inserter_
= Statement_inserter(block
, pindex
);
3040 // Lower the expressions first.
3041 int t
= sorig
->traverse_contents(this);
3042 if (t
== TRAVERSE_EXIT
)
3044 this->inserter_
= hold_inserter
;
3048 // Keep lowering until nothing changes.
3049 Statement
* s
= sorig
;
3052 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
3057 t
= s
->traverse_contents(this);
3058 if (t
== TRAVERSE_EXIT
)
3060 this->inserter_
= hold_inserter
;
3066 block
->replace_statement(*pindex
, s
);
3068 this->inserter_
= hold_inserter
;
3069 return TRAVERSE_SKIP_COMPONENTS
;
3072 // Lower expression parse trees.
3075 Lower_parse_tree::expression(Expression
** pexpr
)
3077 // We have to lower all subexpressions first, so that we can get
3078 // their type if necessary. This is awkward, because we don't have
3079 // a postorder traversal pass.
3080 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3081 return TRAVERSE_EXIT
;
3082 // Keep lowering until nothing changes.
3085 Expression
* e
= *pexpr
;
3086 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
3090 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3091 return TRAVERSE_EXIT
;
3095 // Lower the type of this expression before the parent looks at it,
3096 // in case the type contains an array that has expressions in its
3097 // length. Skip an Unknown_expression, as at this point that means
3098 // a composite literal key that does not have a type.
3099 if ((*pexpr
)->unknown_expression() == NULL
)
3100 Type::traverse((*pexpr
)->type(), this);
3102 return TRAVERSE_SKIP_COMPONENTS
;
3105 // Lower the parse tree. This is called after the parse is complete,
3106 // when all names should be resolved.
3109 Gogo::lower_parse_tree()
3111 Lower_parse_tree
lower_parse_tree(this, NULL
);
3112 this->traverse(&lower_parse_tree
);
3114 // If we found any functions defined in other packages that are
3115 // inlinables, import their bodies and turn them into functions.
3117 // Note that as we import inlinable functions we may find more
3118 // inlinable functions, so don't use an iterator.
3119 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
3121 Named_object
* no
= this->imported_inlinable_functions_
[i
];
3122 no
->func_declaration_value()->import_function_body(this, no
);
3125 // There might be type definitions that involve expressions such as the
3126 // array length. Make sure to lower these expressions as well. Otherwise,
3127 // errors hidden within a type can introduce unexpected errors into later
3129 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
3130 p
!= this->verify_types_
.end();
3132 Type::traverse(*p
, &lower_parse_tree
);
3138 Gogo::lower_block(Named_object
* function
, Block
* block
)
3140 Lower_parse_tree
lower_parse_tree(this, function
);
3141 block
->traverse(&lower_parse_tree
);
3144 // Lower an expression. INSERTER may be NULL, in which case the
3145 // expression had better not need to create any temporaries.
3148 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
3151 Lower_parse_tree
lower_parse_tree(this, function
);
3152 if (inserter
!= NULL
)
3153 lower_parse_tree
.set_inserter(inserter
);
3154 lower_parse_tree
.expression(pexpr
);
3157 // Lower a constant. This is called when lowering a reference to a
3158 // constant. We have to make sure that the constant has already been
3162 Gogo::lower_constant(Named_object
* no
)
3164 go_assert(no
->is_const());
3165 Lower_parse_tree
lower(this, NULL
);
3166 lower
.constant(no
, false);
3169 // Make implicit type conversions explicit. Currently only does for
3170 // interface conversions, so the escape analysis can see them and
3173 class Add_conversions
: public Traverse
3177 : Traverse(traverse_statements
3178 | traverse_expressions
)
3182 statement(Block
*, size_t* pindex
, Statement
*);
3185 expression(Expression
**);
3188 // Add explicit conversions in a statement.
3191 Add_conversions::statement(Block
*, size_t*, Statement
* sorig
)
3193 sorig
->add_conversions();
3194 return TRAVERSE_CONTINUE
;
3197 // Add explicit conversions in an expression.
3200 Add_conversions::expression(Expression
** pexpr
)
3202 (*pexpr
)->add_conversions();
3203 return TRAVERSE_CONTINUE
;
3207 Gogo::add_conversions()
3209 Add_conversions add_conversions
;
3210 this->traverse(&add_conversions
);
3214 Gogo::add_conversions_in_block(Block
*b
)
3216 Add_conversions add_conversions
;
3217 b
->traverse(&add_conversions
);
3220 // Traversal class for simple deadcode elimination.
3222 class Remove_deadcode
: public Traverse
3225 Remove_deadcode(Gogo
* gogo
)
3226 : Traverse(traverse_statements
3227 | traverse_expressions
),
3232 statement(Block
*, size_t* pindex
, Statement
*);
3235 expression(Expression
**);
3241 // Remove deadcode in a statement.
3244 Remove_deadcode::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3246 Location loc
= sorig
->location();
3247 If_statement
* ifs
= sorig
->if_statement();
3250 // Remove the dead branch of an if statement.
3252 if (ifs
->condition()->boolean_constant_value(&bval
))
3256 s
= Statement::make_block_statement(ifs
->then_block(),
3259 if (ifs
->else_block() != NULL
)
3260 s
= Statement::make_block_statement(ifs
->else_block(),
3263 // Make a dummy statement.
3264 s
= Statement::make_statement(Expression::make_boolean(false, loc
),
3267 block
->replace_statement(*pindex
, s
);
3270 return TRAVERSE_CONTINUE
;
3273 // Remove deadcode in an expression.
3276 Remove_deadcode::expression(Expression
** pexpr
)
3278 // Discard the right arm of a shortcut expression of constant value.
3279 Binary_expression
* be
= (*pexpr
)->binary_expression();
3282 && be
->boolean_constant_value(&bval
)
3283 && (be
->op() == OPERATOR_ANDAND
3284 || be
->op() == OPERATOR_OROR
))
3286 *pexpr
= Expression::make_boolean(bval
, be
->location());
3287 Type_context
context(NULL
, false);
3288 (*pexpr
)->determine_type(this->gogo_
, &context
);
3290 return TRAVERSE_CONTINUE
;
3296 Gogo::remove_deadcode()
3298 Remove_deadcode
remove_deadcode(this);
3299 this->traverse(&remove_deadcode
);
3302 // Traverse the tree to create function descriptors as needed.
3304 class Create_function_descriptors
: public Traverse
3307 Create_function_descriptors(Gogo
* gogo
)
3308 : Traverse(traverse_functions
| traverse_expressions
),
3313 function(Named_object
*);
3316 expression(Expression
**);
3319 skip_descriptor(Gogo
* gogo
, const Named_object
*);
3325 // Create a descriptor for every top-level exported function and every
3326 // function referenced by an inline function.
3329 Create_function_descriptors::function(Named_object
* no
)
3331 if (Create_function_descriptors::skip_descriptor(this->gogo_
, no
))
3332 return TRAVERSE_CONTINUE
;
3334 if (no
->is_function()
3335 && no
->func_value()->enclosing() == NULL
3336 && !no
->func_value()->is_method()
3337 && ((!Gogo::is_hidden_name(no
->name())
3338 && !Gogo::is_thunk(no
))
3339 || no
->func_value()->is_referenced_by_inline()))
3340 no
->func_value()->descriptor(this->gogo_
, no
);
3342 return TRAVERSE_CONTINUE
;
3345 // If we see a function referenced in any way other than calling it,
3346 // create a descriptor for it.
3349 Create_function_descriptors::expression(Expression
** pexpr
)
3351 Expression
* expr
= *pexpr
;
3353 Func_expression
* fe
= expr
->func_expression();
3356 // We would not get here for a call to this function, so this is
3357 // a reference to a function other than calling it. We need a
3359 if (fe
->closure() != NULL
)
3360 return TRAVERSE_CONTINUE
;
3361 Named_object
* no
= fe
->named_object();
3362 if (no
->is_function() && !no
->func_value()->is_method())
3363 no
->func_value()->descriptor(this->gogo_
, no
);
3364 else if (no
->is_function_declaration()
3365 && !no
->func_declaration_value()->type()->is_method()
3366 && !Linemap::is_predeclared_location(no
->location()))
3367 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3368 return TRAVERSE_CONTINUE
;
3371 Bound_method_expression
* bme
= expr
->bound_method_expression();
3374 // We would not get here for a call to this method, so this is a
3375 // method value. We need to create a thunk.
3376 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3378 return TRAVERSE_CONTINUE
;
3381 Interface_field_reference_expression
* ifre
=
3382 expr
->interface_field_reference_expression();
3385 // We would not get here for a call to this interface method, so
3386 // this is a method value. We need to create a thunk.
3387 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3389 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3391 return TRAVERSE_CONTINUE
;
3394 Call_expression
* ce
= expr
->call_expression();
3397 Expression
* fn
= ce
->fn();
3398 if (fn
->func_expression() != NULL
3399 || fn
->bound_method_expression() != NULL
3400 || fn
->interface_field_reference_expression() != NULL
)
3402 // Traverse the arguments but not the function.
3403 Expression_list
* args
= ce
->args();
3406 if (args
->traverse(this) == TRAVERSE_EXIT
)
3407 return TRAVERSE_EXIT
;
3410 // Traverse the subexpressions of the function, if any.
3411 if (fn
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3412 return TRAVERSE_EXIT
;
3414 return TRAVERSE_SKIP_COMPONENTS
;
3418 return TRAVERSE_CONTINUE
;
3421 // The gc compiler has some special cases that it always compiles as
3422 // intrinsics. For those we don't want to generate a function
3423 // descriptor, as there will be no code for it to refer to.
3426 Create_function_descriptors::skip_descriptor(Gogo
* gogo
,
3427 const Named_object
* no
)
3429 const std::string
& pkgpath(no
->package() == NULL
3431 : no
->package()->pkgpath());
3433 // internal/abi is the standard library package,
3434 // bootstrap/internal/abi is the name used when bootstrapping the gc
3437 return ((pkgpath
== "internal/abi"
3438 || pkgpath
== "bootstrap/internal/abi")
3439 && (no
->name() == "FuncPCABI0"
3440 || no
->name() == "FuncPCABIInternal"));
3443 // Create function descriptors as needed. We need a function
3444 // descriptor for all exported functions and for all functions that
3445 // are referenced without being called.
3448 Gogo::create_function_descriptors()
3450 // Create a function descriptor for any exported function that is
3451 // declared in this package. This is so that we have a descriptor
3452 // for functions written in assembly. Gather the descriptors first
3453 // so that we don't add declarations while looping over them.
3454 std::vector
<Named_object
*> fndecls
;
3455 Bindings
* b
= this->package_
->bindings();
3456 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3457 p
!= b
->end_declarations();
3460 Named_object
* no
= p
->second
;
3461 if (no
->is_function_declaration()
3462 && !no
->func_declaration_value()->type()->is_method()
3463 && !Linemap::is_predeclared_location(no
->location())
3464 && !Gogo::is_hidden_name(no
->name())
3465 && !Create_function_descriptors::skip_descriptor(this, no
))
3466 fndecls
.push_back(no
);
3468 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3471 (*p
)->func_declaration_value()->descriptor(this, *p
);
3474 Create_function_descriptors
cfd(this);
3475 this->traverse(&cfd
);
3478 // Lower calls to builtin functions. We need to do this early because
3479 // some builtin calls are constant expressions. In particular we need
3480 // to do this before finalize_methods, because finalize_methods calls
3481 // is_direct_iface_type, which needs to know whether something like
3482 // [unsafe.Sizeof(byte(0))]*byte is a direct-iface type.
3484 class Lower_builtin_calls
: public Traverse
3487 Lower_builtin_calls(Gogo
* gogo
)
3488 : Traverse(traverse_expressions
),
3493 expression(Expression
**);
3500 Lower_builtin_calls::expression(Expression
** pexpr
)
3502 Call_expression
* ce
= (*pexpr
)->call_expression();
3504 *pexpr
= ce
->lower_builtin(this->gogo_
);
3505 return TRAVERSE_CONTINUE
;
3509 Gogo::lower_builtin_calls()
3511 Lower_builtin_calls
lbc(this);
3512 this->traverse(&lbc
);
3515 // Finalize the methods of an interface type.
3518 Finalize_methods::type(Type
* t
)
3520 // Check the classification so that we don't finalize the methods
3521 // twice for a named interface type.
3522 switch (t
->classification())
3524 case Type::TYPE_INTERFACE
:
3525 t
->interface_type()->finalize_methods();
3528 case Type::TYPE_NAMED
:
3530 Named_type
* nt
= t
->named_type();
3533 return TRAVERSE_CONTINUE
;
3535 Type
* rt
= nt
->real_type();
3536 if (rt
->classification() != Type::TYPE_STRUCT
)
3538 // Finalize the methods of the real type first.
3539 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3540 return TRAVERSE_EXIT
;
3542 // Finalize the methods of this type.
3543 nt
->finalize_methods(this->gogo_
);
3547 // We don't want to finalize the methods of a named struct
3548 // type, as the methods should be attached to the named
3549 // type, not the struct type. We just want to finalize
3552 // It is possible that a field type refers indirectly to
3553 // this type, such as via a field with function type with
3554 // an argument or result whose type is this type. To
3555 // avoid the cycle, first finalize the methods of any
3556 // embedded types, which are the only types we need to
3557 // know to finalize the methods of this type.
3558 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3561 for (Struct_field_list::const_iterator pf
= fields
->begin();
3562 pf
!= fields
->end();
3565 if (pf
->is_anonymous())
3567 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3568 return TRAVERSE_EXIT
;
3573 // Finalize the methods of this type.
3574 nt
->finalize_methods(this->gogo_
);
3576 // Finalize all the struct fields.
3577 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3578 return TRAVERSE_EXIT
;
3581 // If this type is defined in a different package, then finalize the
3582 // types of all the methods, since we won't see them otherwise.
3583 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3585 const Methods
* methods
= nt
->methods();
3586 for (Methods::const_iterator p
= methods
->begin();
3587 p
!= methods
->end();
3590 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3591 return TRAVERSE_EXIT
;
3595 // Finalize the types of all methods that are declared but not
3596 // defined, since we won't see the declarations otherwise.
3597 if (nt
->named_object()->package() == NULL
3598 && nt
->local_methods() != NULL
)
3600 const Bindings
* methods
= nt
->local_methods();
3601 for (Bindings::const_declarations_iterator p
=
3602 methods
->begin_declarations();
3603 p
!= methods
->end_declarations();
3606 if (p
->second
->is_function_declaration())
3608 Type
* mt
= p
->second
->func_declaration_value()->type();
3609 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3610 return TRAVERSE_EXIT
;
3615 return TRAVERSE_SKIP_COMPONENTS
;
3618 case Type::TYPE_STRUCT
:
3619 // Traverse the field types first in case there is an embedded
3620 // field with methods that the struct should inherit.
3621 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3622 return TRAVERSE_EXIT
;
3623 t
->struct_type()->finalize_methods(this->gogo_
);
3624 return TRAVERSE_SKIP_COMPONENTS
;
3630 return TRAVERSE_CONTINUE
;
3633 // Finalize method lists and build stub methods for types.
3636 Gogo::finalize_methods()
3638 Finalize_methods
finalize(this);
3639 this->traverse(&finalize
);
3642 // Finalize the method list for a type. This is called when a type is
3643 // parsed for an inlined function body, which happens after the
3644 // finalize_methods pass.
3647 Gogo::finalize_methods_for_type(Type
* type
)
3649 Finalize_methods
finalize(this);
3650 Type::traverse(type
, &finalize
);
3653 // Set types for unspecified variables and constants.
3656 Gogo::determine_types()
3658 this->current_bindings()->determine_types(this);
3660 // Determine the types of constants in packages.
3661 for (Packages::const_iterator p
= this->packages_
.begin();
3662 p
!= this->packages_
.end();
3664 p
->second
->determine_types(this);
3667 // Traversal class used for type checking.
3669 class Check_types_traverse
: public Traverse
3672 Check_types_traverse(Gogo
* gogo
)
3673 : Traverse(traverse_variables
3674 | traverse_constants
3675 | traverse_functions
3676 | traverse_statements
3677 | traverse_expressions
),
3682 variable(Named_object
*);
3685 constant(Named_object
*, bool);
3688 function(Named_object
*);
3691 statement(Block
*, size_t* pindex
, Statement
*);
3694 expression(Expression
**);
3701 // Check that a variable initializer has the right type.
3704 Check_types_traverse::variable(Named_object
* named_object
)
3706 if (named_object
->is_variable())
3708 Variable
* var
= named_object
->var_value();
3710 // Give error if variable type is not defined.
3711 var
->type()->base();
3713 Expression
* init
= var
->init();
3716 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3719 go_error_at(var
->location(), "incompatible type in initialization");
3721 go_error_at(var
->location(),
3722 "incompatible type in initialization (%s)",
3724 init
= Expression::make_error(named_object
->location());
3727 else if (init
!= NULL
3728 && init
->func_expression() != NULL
)
3730 Named_object
* no
= init
->func_expression()->named_object();
3731 Function_type
* fntype
;
3732 if (no
->is_function())
3733 fntype
= no
->func_value()->type();
3734 else if (no
->is_function_declaration())
3735 fntype
= no
->func_declaration_value()->type();
3739 // Builtin functions cannot be used as function values for variable
3741 if (fntype
->is_builtin())
3743 go_error_at(init
->location(),
3744 "invalid use of special built-in function %qs; "
3746 no
->message_name().c_str());
3751 && !var
->is_global()
3752 && !var
->is_parameter()
3753 && !var
->is_receiver()
3754 && !var
->type()->is_error()
3755 && (init
== NULL
|| !init
->is_error_expression())
3756 && !Lex::is_invalid_identifier(named_object
->name()))
3758 // Avoid giving an error if the initializer is invalid.
3760 init
->check_types(this->gogo_
);
3762 if (init
== NULL
|| !init
->is_error_expression())
3763 go_error_at(var
->location(), "%qs declared but not used",
3764 named_object
->message_name().c_str());
3767 return TRAVERSE_CONTINUE
;
3770 // Check that a constant initializer has the right type.
3773 Check_types_traverse::constant(Named_object
* named_object
, bool)
3775 Named_constant
* constant
= named_object
->const_value();
3776 Type
* ctype
= constant
->type();
3777 if (ctype
->integer_type() == NULL
3778 && ctype
->float_type() == NULL
3779 && ctype
->complex_type() == NULL
3780 && !ctype
->is_boolean_type()
3781 && !ctype
->is_string_type())
3783 if (ctype
->is_nil_type())
3784 go_error_at(constant
->location(), "const initializer cannot be nil");
3785 else if (!ctype
->is_error())
3786 go_error_at(constant
->location(), "invalid constant type");
3787 constant
->set_error();
3789 else if (constant
->expr()->is_error_expression())
3791 go_assert(saw_errors());
3792 constant
->set_error();
3794 else if (!constant
->expr()->is_constant())
3796 go_error_at(constant
->expr()->location(), "expression is not constant");
3797 constant
->set_error();
3799 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3802 go_error_at(constant
->location(),
3803 "initialization expression has wrong type");
3804 constant
->set_error();
3806 return TRAVERSE_CONTINUE
;
3809 // There are no types to check in a function, but this is where we
3810 // issue warnings about labels which are defined but not referenced.
3813 Check_types_traverse::function(Named_object
* no
)
3815 no
->func_value()->check_labels();
3816 return TRAVERSE_CONTINUE
;
3819 // Check that types are valid in a statement.
3822 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3824 s
->check_types(this->gogo_
);
3825 return TRAVERSE_CONTINUE
;
3828 // Check that types are valid in an expression.
3831 Check_types_traverse::expression(Expression
** expr
)
3833 (*expr
)->check_types(this->gogo_
);
3834 return TRAVERSE_CONTINUE
;
3837 // Check that types are valid.
3842 Check_types_traverse
traverse(this);
3843 this->traverse(&traverse
);
3845 Bindings
* bindings
= this->current_bindings();
3846 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3847 p
!= bindings
->end_declarations();
3850 // Also check the types in a function declaration's signature.
3851 Named_object
* no
= p
->second
;
3852 if (no
->is_function_declaration())
3853 no
->func_declaration_value()->check_types();
3857 // Check the types in a single block.
3860 Gogo::check_types_in_block(Block
* block
)
3862 Check_types_traverse
traverse(this);
3863 block
->traverse(&traverse
);
3866 // For each global variable defined in the current package, record the
3867 // set of variables that its initializer depends on. We do this after
3868 // lowering so that all unknown names are resolved to their final
3869 // locations. We do this before write barrier insertion because that
3870 // makes it harder to distinguish references from assignments in
3874 Gogo::record_global_init_refs()
3876 Bindings
* bindings
= this->package_
->bindings();
3877 for (Bindings::const_definitions_iterator pb
= bindings
->begin_definitions();
3878 pb
!= bindings
->end_definitions();
3881 Named_object
* no
= *pb
;
3882 if (!no
->is_variable())
3885 Variable
* var
= no
->var_value();
3886 go_assert(var
->is_global());
3888 Find_vars find_vars
;
3889 Expression
* init
= var
->init();
3891 Expression::traverse(&init
, &find_vars
);
3892 if (var
->has_pre_init())
3893 var
->preinit()->traverse(&find_vars
);
3894 Named_object
* dep
= this->var_depends_on(var
);
3897 Expression
* dinit
= dep
->var_value()->init();
3899 Expression::traverse(&dinit
, &find_vars
);
3900 if (dep
->var_value()->has_pre_init())
3901 dep
->var_value()->preinit()->traverse(&find_vars
);
3904 for (Find_vars::const_iterator pv
= find_vars
.begin();
3905 pv
!= find_vars
.end();
3907 var
->add_init_ref(*pv
);
3911 // A traversal class which finds all the expressions which must be
3912 // evaluated in order within a statement or larger expression. This
3913 // is used to implement the rules about order of evaluation.
3915 class Find_eval_ordering
: public Traverse
3918 typedef std::vector
<Expression
**> Expression_pointers
;
3921 Find_eval_ordering()
3922 : Traverse(traverse_blocks
3923 | traverse_statements
3924 | traverse_expressions
),
3930 { return this->exprs_
.size(); }
3932 typedef Expression_pointers::const_iterator const_iterator
;
3936 { return this->exprs_
.begin(); }
3940 { return this->exprs_
.end(); }
3945 { return TRAVERSE_SKIP_COMPONENTS
; }
3948 statement(Block
*, size_t*, Statement
*)
3949 { return TRAVERSE_SKIP_COMPONENTS
; }
3952 expression(Expression
**);
3955 // A list of pointers to expressions with side-effects.
3956 Expression_pointers exprs_
;
3959 // If an expression must be evaluated in order, put it on the list.
3962 Find_eval_ordering::expression(Expression
** expression_pointer
)
3964 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3966 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3968 // Shortcut expressions may potentially have side effects which need
3969 // to be ordered, so add them to the list.
3970 // We don't order its subexpressions here since they may be evaluated
3971 // conditionally. This is handled in remove_shortcuts.
3972 this->exprs_
.push_back(expression_pointer
);
3973 return TRAVERSE_SKIP_COMPONENTS
;
3976 // We have to look at subexpressions before this one.
3977 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3978 return TRAVERSE_EXIT
;
3979 if ((*expression_pointer
)->must_eval_in_order())
3980 this->exprs_
.push_back(expression_pointer
);
3981 return TRAVERSE_SKIP_COMPONENTS
;
3984 // A traversal class for ordering evaluations.
3986 class Order_eval
: public Traverse
3989 Order_eval(Gogo
* gogo
)
3990 : Traverse(traverse_variables
3991 | traverse_statements
),
3996 variable(Named_object
*);
3999 statement(Block
*, size_t*, Statement
*);
4006 // Implement the order of evaluation rules for a statement.
4009 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
4011 // FIXME: This approach doesn't work for switch statements, because
4012 // we add the new statements before the whole switch when we need to
4013 // instead add them just before the switch expression. The right
4014 // fix is probably to lower switch statements with nonconstant cases
4015 // to a series of conditionals.
4016 if (stmt
->switch_statement() != NULL
)
4017 return TRAVERSE_CONTINUE
;
4019 Find_eval_ordering find_eval_ordering
;
4021 // If S is a variable declaration, then ordinary traversal won't do
4022 // anything. We want to explicitly traverse the initialization
4023 // expression if there is one.
4024 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
4025 Expression
* init
= NULL
;
4026 Expression
* orig_init
= NULL
;
4028 stmt
->traverse_contents(&find_eval_ordering
);
4031 init
= vds
->var()->var_value()->init();
4033 return TRAVERSE_CONTINUE
;
4036 // It might seem that this could be
4037 // init->traverse_subexpressions. Unfortunately that can fail
4040 // newvar, err := call(arg())
4041 // Here newvar will have an init of call result 0 of
4042 // call(arg()). If we only traverse subexpressions, we will
4043 // only find arg(), and we won't bother to move anything out.
4044 // Then we get to the assignment to err, we will traverse the
4045 // whole statement, and this time we will find both call() and
4046 // arg(), and so we will move them out. This will cause them to
4047 // be put into temporary variables before the assignment to err
4048 // but after the declaration of newvar. To avoid that problem,
4049 // we traverse the entire expression here.
4050 Expression::traverse(&init
, &find_eval_ordering
);
4053 size_t c
= find_eval_ordering
.size();
4055 return TRAVERSE_CONTINUE
;
4057 // If there is only one expression with a side-effect, we can
4058 // usually leave it in place.
4061 switch (stmt
->classification())
4063 case Statement::STATEMENT_ASSIGNMENT
:
4064 // For an assignment statement, we need to evaluate an
4065 // expression on the right hand side before we evaluate any
4066 // index expression on the left hand side, so for that case
4067 // we always move the expression. Otherwise we mishandle
4068 // m[0] = len(m) where m is a map.
4071 case Statement::STATEMENT_EXPRESSION
:
4073 // If this is a call statement that doesn't return any
4074 // values, it will not have been counted as a value to
4075 // move. We need to move any subexpressions in case they
4076 // are themselves call statements that require passing a
4078 Expression
* expr
= stmt
->expression_statement()->expr();
4079 if (expr
->call_expression() != NULL
4080 && expr
->call_expression()->result_count() == 0)
4082 return TRAVERSE_CONTINUE
;
4086 // We can leave the expression in place.
4087 return TRAVERSE_CONTINUE
;
4091 bool is_thunk
= stmt
->thunk_statement() != NULL
;
4092 Expression_statement
* es
= stmt
->expression_statement();
4093 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4094 p
!= find_eval_ordering
.end();
4097 Expression
** pexpr
= *p
;
4099 // The last expression in a thunk will be the call passed to go
4100 // or defer, which we must not evaluate early.
4101 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
4104 Location loc
= (*pexpr
)->location();
4106 if ((*pexpr
)->call_expression() == NULL
4107 || (*pexpr
)->call_expression()->result_count() < 2)
4109 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4112 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4116 // A call expression which returns multiple results needs to
4117 // be handled specially. We can't create a temporary
4118 // because there is no type to give it. Any actual uses of
4119 // the values will be done via Call_result_expressions.
4121 // Since a given call expression can be shared by multiple
4122 // Call_result_expressions, avoid hoisting the call the
4123 // second time we see it here. In addition, don't try to
4124 // hoist the top-level multi-return call in the statement,
4125 // since doing this would result a tree with more than one copy
4127 if (this->remember_expression(*pexpr
))
4129 else if (es
!= NULL
&& *pexpr
== es
->expr())
4132 s
= Statement::make_statement(*pexpr
, true);
4137 block
->insert_statement_before(*pindex
, s
);
4142 if (init
!= orig_init
)
4143 vds
->var()->var_value()->set_init(init
);
4145 return TRAVERSE_CONTINUE
;
4148 // Implement the order of evaluation rules for the initializer of a
4152 Order_eval::variable(Named_object
* no
)
4154 if (no
->is_result_variable())
4155 return TRAVERSE_CONTINUE
;
4156 Variable
* var
= no
->var_value();
4157 Expression
* init
= var
->init();
4158 if (!var
->is_global() || init
== NULL
)
4159 return TRAVERSE_CONTINUE
;
4161 Find_eval_ordering find_eval_ordering
;
4162 Expression::traverse(&init
, &find_eval_ordering
);
4164 if (find_eval_ordering
.size() <= 1)
4166 // If there is only one expression with a side-effect, we can
4167 // leave it in place.
4168 return TRAVERSE_SKIP_COMPONENTS
;
4171 Expression
* orig_init
= init
;
4173 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4174 p
!= find_eval_ordering
.end();
4177 Expression
** pexpr
= *p
;
4178 Location loc
= (*pexpr
)->location();
4180 if ((*pexpr
)->call_expression() == NULL
4181 || (*pexpr
)->call_expression()->result_count() < 2)
4183 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4186 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4190 // A call expression which returns multiple results needs to
4191 // be handled specially.
4192 s
= Statement::make_statement(*pexpr
, true);
4194 var
->add_preinit_statement(this->gogo_
, s
);
4197 if (init
!= orig_init
)
4198 var
->set_init(init
);
4200 return TRAVERSE_SKIP_COMPONENTS
;
4203 // Use temporary variables to implement the order of evaluation rules.
4206 Gogo::order_evaluations()
4208 Order_eval
order_eval(this);
4209 this->traverse(&order_eval
);
4212 // Order evaluations in a block.
4215 Gogo::order_block(Block
* block
)
4217 Order_eval
order_eval(this);
4218 block
->traverse(&order_eval
);
4221 // A traversal class used to find a single shortcut operator within an
4224 class Find_shortcut
: public Traverse
4228 : Traverse(traverse_blocks
4229 | traverse_statements
4230 | traverse_expressions
),
4234 // A pointer to the expression which was found, or NULL if none was
4238 { return this->found_
; }
4243 { return TRAVERSE_SKIP_COMPONENTS
; }
4246 statement(Block
*, size_t*, Statement
*)
4247 { return TRAVERSE_SKIP_COMPONENTS
; }
4250 expression(Expression
**);
4253 Expression
** found_
;
4256 // Find a shortcut expression.
4259 Find_shortcut::expression(Expression
** pexpr
)
4261 Expression
* expr
= *pexpr
;
4262 Binary_expression
* be
= expr
->binary_expression();
4264 return TRAVERSE_CONTINUE
;
4265 Operator op
= be
->op();
4266 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
4267 return TRAVERSE_CONTINUE
;
4268 go_assert(this->found_
== NULL
);
4269 this->found_
= pexpr
;
4270 return TRAVERSE_EXIT
;
4273 // A traversal class used to turn shortcut operators into explicit if
4276 class Shortcuts
: public Traverse
4279 Shortcuts(Gogo
* gogo
)
4280 : Traverse(traverse_variables
4281 | traverse_statements
),
4287 variable(Named_object
*);
4290 statement(Block
*, size_t*, Statement
*);
4293 // Convert a shortcut operator.
4295 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
4301 // Remove shortcut operators in a single statement.
4304 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
4306 // FIXME: This approach doesn't work for switch statements, because
4307 // we add the new statements before the whole switch when we need to
4308 // instead add them just before the switch expression. The right
4309 // fix is probably to lower switch statements with nonconstant cases
4310 // to a series of conditionals.
4311 if (s
->switch_statement() != NULL
)
4312 return TRAVERSE_CONTINUE
;
4316 Find_shortcut find_shortcut
;
4318 // If S is a variable declaration, then ordinary traversal won't
4319 // do anything. We want to explicitly traverse the
4320 // initialization expression if there is one.
4321 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
4322 Expression
* init
= NULL
;
4324 s
->traverse_contents(&find_shortcut
);
4327 init
= vds
->var()->var_value()->init();
4329 return TRAVERSE_CONTINUE
;
4330 init
->traverse(&init
, &find_shortcut
);
4332 Expression
** pshortcut
= find_shortcut
.found();
4333 if (pshortcut
== NULL
)
4334 return TRAVERSE_CONTINUE
;
4336 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
4337 block
->insert_statement_before(*pindex
, snew
);
4340 if (pshortcut
== &init
)
4341 vds
->var()->var_value()->set_init(init
);
4345 // Remove shortcut operators in the initializer of a global variable.
4348 Shortcuts::variable(Named_object
* no
)
4350 if (no
->is_result_variable())
4351 return TRAVERSE_CONTINUE
;
4352 Variable
* var
= no
->var_value();
4353 Expression
* init
= var
->init();
4354 if (!var
->is_global() || init
== NULL
)
4355 return TRAVERSE_CONTINUE
;
4359 Find_shortcut find_shortcut
;
4360 init
->traverse(&init
, &find_shortcut
);
4361 Expression
** pshortcut
= find_shortcut
.found();
4362 if (pshortcut
== NULL
)
4363 return TRAVERSE_CONTINUE
;
4365 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
4366 var
->add_preinit_statement(this->gogo_
, snew
);
4367 if (pshortcut
== &init
)
4368 var
->set_init(init
);
4372 // Given an expression which uses a shortcut operator, return a
4373 // statement which implements it, and update *PSHORTCUT accordingly.
4376 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
4378 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
4379 Expression
* left
= shortcut
->left();
4380 Expression
* right
= shortcut
->right();
4381 Location loc
= shortcut
->location();
4383 Block
* retblock
= new Block(enclosing
, loc
);
4384 retblock
->set_end_location(loc
);
4386 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
4388 retblock
->add_statement(ts
);
4390 Block
* block
= new Block(retblock
, loc
);
4391 block
->set_end_location(loc
);
4392 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4393 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4394 block
->add_statement(assign
);
4396 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4397 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4398 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4400 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4402 if_statement
->determine_types(this->gogo_
);
4403 retblock
->add_statement(if_statement
);
4405 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4409 // Now convert any shortcut operators in LEFT and RIGHT.
4410 // LEFT and RIGHT were skipped in the top level
4411 // Gogo::order_evaluations. We need to order their
4412 // components first.
4413 Order_eval
order_eval(this->gogo_
);
4414 retblock
->traverse(&order_eval
);
4415 Shortcuts
shortcuts(this->gogo_
);
4416 retblock
->traverse(&shortcuts
);
4418 return Statement::make_block_statement(retblock
, loc
);
4421 // Turn shortcut operators into explicit if statements. Doing this
4422 // considerably simplifies the order of evaluation rules.
4425 Gogo::remove_shortcuts()
4427 Shortcuts
shortcuts(this);
4428 this->traverse(&shortcuts
);
4431 // Turn shortcut operators into explicit if statements in a block.
4434 Gogo::remove_shortcuts_in_block(Block
* block
)
4436 Shortcuts
shortcuts(this);
4437 block
->traverse(&shortcuts
);
4440 // Traversal to flatten parse tree after order of evaluation rules are applied.
4442 class Flatten
: public Traverse
4445 Flatten(Gogo
* gogo
, Named_object
* function
)
4446 : Traverse(traverse_variables
4447 | traverse_functions
4448 | traverse_statements
4449 | traverse_expressions
),
4450 gogo_(gogo
), function_(function
), inserter_()
4454 set_inserter(const Statement_inserter
* inserter
)
4455 { this->inserter_
= *inserter
; }
4458 variable(Named_object
*);
4461 function(Named_object
*);
4464 statement(Block
*, size_t* pindex
, Statement
*);
4467 expression(Expression
**);
4472 // The function we are traversing.
4473 Named_object
* function_
;
4474 // Current statement inserter for use by expressions.
4475 Statement_inserter inserter_
;
4478 // Flatten variables.
4481 Flatten::variable(Named_object
* no
)
4483 if (!no
->is_variable())
4484 return TRAVERSE_CONTINUE
;
4486 if (no
->is_variable() && no
->var_value()->is_global())
4488 // Global variables can have loops in their initialization
4489 // expressions. This is handled in flatten_init_expression.
4490 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4492 return TRAVERSE_CONTINUE
;
4495 if (!no
->var_value()->is_parameter()
4496 && !no
->var_value()->is_receiver()
4497 && !no
->var_value()->is_closure()
4498 && no
->var_value()->is_non_escaping_address_taken()
4499 && !no
->var_value()->is_in_heap()
4500 && no
->var_value()->toplevel_decl() == NULL
)
4502 // Local variable that has address taken but not escape.
4503 // It needs to be live beyond its lexical scope. So we
4504 // create a top-level declaration for it.
4505 // No need to do it if it is already in the top level.
4506 Block
* top_block
= function_
->func_value()->block();
4507 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4509 Variable
* var
= no
->var_value();
4510 Temporary_statement
* ts
=
4511 Statement::make_temporary(var
->type(), NULL
, var
->location());
4512 ts
->set_is_address_taken();
4513 top_block
->add_statement_at_front(ts
);
4514 var
->set_toplevel_decl(ts
);
4518 go_assert(!no
->var_value()->has_pre_init());
4520 return TRAVERSE_SKIP_COMPONENTS
;
4523 // Flatten the body of a function. Record the function while flattening it,
4524 // so that we can pass it down when flattening an expression.
4527 Flatten::function(Named_object
* no
)
4529 go_assert(this->function_
== NULL
);
4530 this->function_
= no
;
4531 int t
= no
->func_value()->traverse(this);
4532 this->function_
= NULL
;
4534 if (t
== TRAVERSE_EXIT
)
4536 return TRAVERSE_SKIP_COMPONENTS
;
4539 // Flatten statement parse trees.
4542 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4544 // Because we explicitly traverse the statement's contents
4545 // ourselves, we want to skip block statements here. There is
4546 // nothing to flatten in a block statement.
4547 if (sorig
->is_block_statement())
4548 return TRAVERSE_CONTINUE
;
4550 Statement_inserter
hold_inserter(this->inserter_
);
4551 this->inserter_
= Statement_inserter(block
, pindex
);
4553 // Flatten the expressions first.
4554 int t
= sorig
->traverse_contents(this);
4555 if (t
== TRAVERSE_EXIT
)
4557 this->inserter_
= hold_inserter
;
4561 // Keep flattening until nothing changes.
4562 Statement
* s
= sorig
;
4565 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4570 t
= s
->traverse_contents(this);
4571 if (t
== TRAVERSE_EXIT
)
4573 this->inserter_
= hold_inserter
;
4579 block
->replace_statement(*pindex
, s
);
4581 this->inserter_
= hold_inserter
;
4582 return TRAVERSE_SKIP_COMPONENTS
;
4585 // Flatten expression parse trees.
4588 Flatten::expression(Expression
** pexpr
)
4590 // Keep flattening until nothing changes.
4593 Expression
* e
= *pexpr
;
4594 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4595 return TRAVERSE_EXIT
;
4597 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4603 return TRAVERSE_SKIP_COMPONENTS
;
4609 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4611 Flatten
flatten(this, function
);
4612 block
->traverse(&flatten
);
4615 // Flatten an expression. INSERTER may be NULL, in which case the
4616 // expression had better not need to create any temporaries.
4619 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4622 Flatten
flatten(this, function
);
4623 if (inserter
!= NULL
)
4624 flatten
.set_inserter(inserter
);
4625 flatten
.expression(pexpr
);
4631 Flatten
flatten(this, NULL
);
4632 this->traverse(&flatten
);
4635 // Traversal to convert calls to the predeclared recover function to
4636 // pass in an argument indicating whether it can recover from a panic
4639 class Convert_recover
: public Traverse
4642 Convert_recover(Named_object
* arg
)
4643 : Traverse(traverse_expressions
),
4649 expression(Expression
**);
4652 // The argument to pass to the function.
4656 // Convert calls to recover.
4659 Convert_recover::expression(Expression
** pp
)
4661 Call_expression
* ce
= (*pp
)->call_expression();
4662 if (ce
!= NULL
&& ce
->is_recover_call())
4663 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4665 return TRAVERSE_CONTINUE
;
4668 // Traversal for build_recover_thunks.
4670 class Build_recover_thunks
: public Traverse
4673 Build_recover_thunks(Gogo
* gogo
)
4674 : Traverse(traverse_functions
),
4679 function(Named_object
*);
4683 can_recover_arg(Location
);
4689 // If this function calls recover, turn it into a thunk.
4692 Build_recover_thunks::function(Named_object
* orig_no
)
4694 Function
* orig_func
= orig_no
->func_value();
4695 if (!orig_func
->calls_recover()
4696 || orig_func
->is_recover_thunk()
4697 || orig_func
->has_recover_thunk())
4698 return TRAVERSE_CONTINUE
;
4700 Gogo
* gogo
= this->gogo_
;
4701 Location location
= orig_func
->location();
4706 Function_type
* orig_fntype
= orig_func
->type();
4707 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4708 std::string receiver_name
;
4709 if (orig_fntype
->is_method())
4711 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4712 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4714 receiver_name
= buf
;
4715 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4716 receiver
->location()));
4718 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4719 if (orig_params
!= NULL
&& !orig_params
->empty())
4721 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4722 p
!= orig_params
->end();
4725 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4727 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4731 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4733 std::string can_recover_name
= buf
;
4734 new_params
->push_back(Typed_identifier(can_recover_name
,
4735 Type::lookup_bool_type(),
4736 orig_fntype
->location()));
4738 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4739 Typed_identifier_list
* new_results
;
4740 if (orig_results
== NULL
|| orig_results
->empty())
4744 new_results
= new Typed_identifier_list();
4745 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4746 p
!= orig_results
->end();
4748 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4751 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4753 orig_fntype
->location());
4754 if (orig_fntype
->is_varargs())
4755 new_fntype
->set_is_varargs();
4758 if (orig_fntype
->is_method())
4759 rtype
= orig_fntype
->receiver()->type();
4760 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4761 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4763 Function
*new_func
= new_no
->func_value();
4764 if (orig_func
->enclosing() != NULL
)
4765 new_func
->set_enclosing(orig_func
->enclosing());
4767 // We build the code for the original function attached to the new
4768 // function, and then swap the original and new function bodies.
4769 // This means that existing references to the original function will
4770 // then refer to the new function. That makes this code a little
4771 // confusing, in that the reference to NEW_NO really refers to the
4772 // other function, not the one we are building.
4774 Expression
* closure
= NULL
;
4775 if (orig_func
->needs_closure())
4777 // For the new function we are creating, declare a new parameter
4778 // variable NEW_CLOSURE_NO and set it to be the closure variable
4779 // of the function. This will be set to the closure value
4780 // passed in by the caller. Then pass a reference to this
4781 // variable as the closure value when calling the original
4782 // function. In other words, simply pass the closure value
4783 // through the thunk we are creating.
4784 Named_object
* orig_closure_no
= orig_func
->closure_var();
4785 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4786 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4787 false, false, location
);
4788 new_var
->set_is_closure();
4789 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4791 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4793 new_func
->set_closure_var(new_closure_no
);
4794 closure
= Expression::make_var_reference(new_closure_no
, location
);
4797 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4799 Expression_list
* args
= new Expression_list();
4800 if (new_params
!= NULL
)
4802 // Note that we skip the last parameter, which is the boolean
4803 // indicating whether recover can succed.
4804 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4805 p
+ 1 != new_params
->end();
4808 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4809 go_assert(p_no
!= NULL
4810 && p_no
->is_variable()
4811 && p_no
->var_value()->is_parameter());
4812 args
->push_back(Expression::make_var_reference(p_no
, location
));
4815 args
->push_back(this->can_recover_arg(location
));
4817 gogo
->start_block(location
);
4819 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4821 // Any varargs call has already been lowered.
4822 call
->set_varargs_are_lowered();
4824 Statement
* s
= Statement::make_return_from_call(new_no
, call
, location
);
4825 s
->determine_types(this->gogo_
);
4826 gogo
->add_statement(s
);
4828 Block
* b
= gogo
->finish_block(location
);
4830 gogo
->add_block(b
, location
);
4832 // Lower the call in case it returns multiple results.
4833 gogo
->lower_block(new_no
, b
);
4835 gogo
->finish_function(location
);
4837 // Swap the function bodies and types.
4838 new_func
->swap_for_recover(orig_func
);
4839 orig_func
->set_is_recover_thunk();
4840 new_func
->set_calls_recover();
4841 new_func
->set_has_recover_thunk();
4843 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4844 Bindings
* new_bindings
= new_func
->block()->bindings();
4845 if (orig_fntype
->is_method())
4847 // We changed the receiver to be a regular parameter. We have
4848 // to update the binding accordingly in both functions.
4849 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4850 go_assert(orig_rec_no
!= NULL
4851 && orig_rec_no
->is_variable()
4852 && !orig_rec_no
->var_value()->is_receiver());
4853 orig_rec_no
->var_value()->set_is_receiver();
4855 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4856 if (new_receiver_name
.empty())
4858 // Find the receiver. It was named "r.NNN" in
4859 // Gogo::start_function.
4860 for (Bindings::const_definitions_iterator p
=
4861 new_bindings
->begin_definitions();
4862 p
!= new_bindings
->end_definitions();
4865 const std::string
& pname((*p
)->name());
4866 if (pname
[0] == 'r' && pname
[1] == '.')
4868 new_receiver_name
= pname
;
4872 go_assert(!new_receiver_name
.empty());
4874 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4875 if (new_rec_no
== NULL
)
4876 go_assert(saw_errors());
4879 go_assert(new_rec_no
->is_variable()
4880 && new_rec_no
->var_value()->is_receiver());
4881 new_rec_no
->var_value()->set_is_not_receiver();
4885 // Because we flipped blocks but not types, the can_recover
4886 // parameter appears in the (now) old bindings as a parameter.
4887 // Change it to a local variable, whereupon it will be discarded.
4888 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4889 go_assert(can_recover_no
!= NULL
4890 && can_recover_no
->is_variable()
4891 && can_recover_no
->var_value()->is_parameter());
4892 orig_bindings
->remove_binding(can_recover_no
);
4894 // Add the can_recover argument to the (now) new bindings, and
4895 // attach it to any recover statements.
4896 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4897 false, true, false, location
);
4898 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4900 Convert_recover
convert_recover(can_recover_no
);
4901 new_func
->traverse(&convert_recover
);
4903 // Update the function pointers in any named results.
4904 new_func
->update_result_variables();
4905 orig_func
->update_result_variables();
4907 return TRAVERSE_CONTINUE
;
4910 // Return the expression to pass for the .can_recover parameter to the
4911 // new function. This indicates whether a call to recover may return
4912 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4915 Build_recover_thunks::can_recover_arg(Location location
)
4917 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4918 static Named_object
* can_recover
;
4919 if (can_recover
== NULL
)
4921 const Location bloc
= Linemap::predeclared_location();
4922 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4923 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4924 Type
* boolean_type
= Type::lookup_bool_type();
4925 Typed_identifier_list
* results
= new Typed_identifier_list();
4926 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4927 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4930 Named_object::make_function_declaration("runtime_canrecover",
4931 NULL
, fntype
, bloc
);
4932 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4935 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4936 Expression
* call
= Runtime::make_call(this->gogo_
,
4937 Runtime::BUILTIN_RETURN_ADDRESS
,
4938 location
, 1, zexpr
);
4939 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4941 Expression_list
* args
= new Expression_list();
4942 args
->push_back(call
);
4944 Expression
* fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4945 return Expression::make_call(fn
, args
, false, location
);
4948 // Build thunks for functions which call recover. We build a new
4949 // function with an extra parameter, which is whether a call to
4950 // recover can succeed. We then move the body of this function to
4951 // that one. We then turn this function into a thunk which calls the
4952 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4953 // The function will be marked as not splitting the stack. This will
4954 // cooperate with the implementation of defer to make recover do the
4958 Gogo::build_recover_thunks()
4960 Build_recover_thunks
build_recover_thunks(this);
4961 this->traverse(&build_recover_thunks
);
4964 // Look for named types to see whether we need to create an interface
4967 class Build_method_tables
: public Traverse
4970 Build_method_tables(Gogo
* gogo
,
4971 const std::vector
<Interface_type
*>& interfaces
)
4972 : Traverse(traverse_types
),
4973 gogo_(gogo
), interfaces_(interfaces
)
4982 // A list of locally defined interfaces which have hidden methods.
4983 const std::vector
<Interface_type
*>& interfaces_
;
4986 // Build all required interface method tables for types. We need to
4987 // ensure that we have an interface method table for every interface
4988 // which has a hidden method, for every named type which implements
4989 // that interface. Normally we can just build interface method tables
4990 // as we need them. However, in some cases we can require an
4991 // interface method table for an interface defined in a different
4992 // package for a type defined in that package. If that interface and
4993 // type both use a hidden method, that is OK. However, we will not be
4994 // able to build that interface method table when we need it, because
4995 // the type's hidden method will be static. So we have to build it
4996 // here, and just refer it from other packages as needed.
4999 Gogo::build_interface_method_tables()
5004 std::vector
<Interface_type
*> hidden_interfaces
;
5005 hidden_interfaces
.reserve(this->interface_types_
.size());
5006 for (std::vector
<Interface_type
*>::const_iterator pi
=
5007 this->interface_types_
.begin();
5008 pi
!= this->interface_types_
.end();
5011 const Typed_identifier_list
* methods
= (*pi
)->methods();
5012 if (methods
== NULL
)
5014 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
5015 pm
!= methods
->end();
5018 if (Gogo::is_hidden_name(pm
->name()))
5020 hidden_interfaces
.push_back(*pi
);
5026 if (!hidden_interfaces
.empty())
5028 // Now traverse the tree looking for all named types.
5029 Build_method_tables
bmt(this, hidden_interfaces
);
5030 this->traverse(&bmt
);
5033 // We no longer need the list of interfaces.
5035 this->interface_types_
.clear();
5038 // This is called for each type. For a named type, for each of the
5039 // interfaces with hidden methods that it implements, create the
5043 Build_method_tables::type(Type
* type
)
5045 Named_type
* nt
= type
->named_type();
5046 Struct_type
* st
= type
->struct_type();
5047 if (nt
!= NULL
|| st
!= NULL
)
5049 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
5050 for (std::vector
<Interface_type
*>::const_iterator p
=
5051 this->interfaces_
.begin();
5052 p
!= this->interfaces_
.end();
5055 // We ask whether a pointer to the named type implements the
5056 // interface, because a pointer can implement more methods
5060 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
5063 nt
->interface_method_table(*p
, false)->get_backend(&context
);
5064 nt
->interface_method_table(*p
, true)->get_backend(&context
);
5069 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
5072 st
->interface_method_table(*p
, false)->get_backend(&context
);
5073 st
->interface_method_table(*p
, true)->get_backend(&context
);
5078 return TRAVERSE_CONTINUE
;
5081 // Return an expression which allocates memory to hold values of type TYPE.
5084 Gogo::allocate_memory(Type
* type
, Location location
)
5086 Expression
* td
= Expression::make_type_descriptor(type
, location
);
5087 return Runtime::make_call(this, Runtime::NEW
, location
, 1, td
);
5090 // Traversal class used to check for return statements.
5092 class Check_return_statements_traverse
: public Traverse
5095 Check_return_statements_traverse()
5096 : Traverse(traverse_functions
)
5100 function(Named_object
*);
5103 // Check that a function has a return statement if it needs one.
5106 Check_return_statements_traverse::function(Named_object
* no
)
5108 Function
* func
= no
->func_value();
5109 const Function_type
* fntype
= func
->type();
5110 const Typed_identifier_list
* results
= fntype
->results();
5112 // We only need a return statement if there is a return value.
5113 if (results
== NULL
|| results
->empty())
5114 return TRAVERSE_CONTINUE
;
5116 if (func
->block()->may_fall_through())
5117 go_error_at(func
->block()->end_location(),
5118 "missing return at end of function");
5120 return TRAVERSE_CONTINUE
;
5123 // Check return statements.
5126 Gogo::check_return_statements()
5128 Check_return_statements_traverse traverse
;
5129 this->traverse(&traverse
);
5132 // Traversal class to decide whether a function body is less than the
5133 // inlining budget. This adjusts *available as it goes, and stops the
5134 // traversal if it goes negative.
5136 class Inline_within_budget
: public Traverse
5139 Inline_within_budget(int* available
)
5140 : Traverse(traverse_statements
5141 | traverse_expressions
),
5142 available_(available
)
5146 statement(Block
*, size_t*, Statement
*);
5149 expression(Expression
**);
5152 // Pointer to remaining budget.
5156 // Adjust the budget for the inlining cost of a statement.
5159 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
5161 if (*this->available_
< 0)
5162 return TRAVERSE_EXIT
;
5163 *this->available_
-= s
->inlining_cost();
5164 return TRAVERSE_CONTINUE
;
5167 // Adjust the budget for the inlining cost of an expression.
5170 Inline_within_budget::expression(Expression
** pexpr
)
5172 if (*this->available_
< 0)
5173 return TRAVERSE_EXIT
;
5174 *this->available_
-= (*pexpr
)->inlining_cost();
5175 return TRAVERSE_CONTINUE
;
5178 // Traversal class to find functions whose body should be exported for
5179 // inlining by other packages.
5181 class Mark_inline_candidates
: public Traverse
5184 Mark_inline_candidates(Unordered_set(Named_object
*)* marked
)
5185 : Traverse(traverse_functions
5187 marked_functions_(marked
)
5191 function(Named_object
*);
5197 // We traverse the function body trying to determine how expensive
5198 // it is for inlining. We start with a budget, and decrease that
5199 // budget for each statement and expression. If the budget goes
5200 // negative, we do not export the function body. The value of this
5201 // budget is a heuristic. In the usual GCC spirit, we could
5202 // consider setting this via a command line option.
5203 const int budget_heuristic
= 80;
5205 // Set of named objects that are marked as inline candidates.
5206 Unordered_set(Named_object
*)* marked_functions_
;
5209 // Mark a function if it is an inline candidate.
5212 Mark_inline_candidates::function(Named_object
* no
)
5214 Function
* func
= no
->func_value();
5215 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5216 return TRAVERSE_CONTINUE
;
5217 int budget
= budget_heuristic
;
5218 Inline_within_budget
iwb(&budget
);
5219 func
->block()->traverse(&iwb
);
5222 func
->set_export_for_inlining();
5223 this->marked_functions_
->insert(no
);
5225 return TRAVERSE_CONTINUE
;
5228 // Mark methods if they are inline candidates.
5231 Mark_inline_candidates::type(Type
* t
)
5233 Named_type
* nt
= t
->named_type();
5234 if (nt
== NULL
|| nt
->is_alias())
5235 return TRAVERSE_CONTINUE
;
5236 const Bindings
* methods
= nt
->local_methods();
5237 if (methods
== NULL
)
5238 return TRAVERSE_CONTINUE
;
5239 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
5240 p
!= methods
->end_definitions();
5243 Named_object
* no
= *p
;
5244 go_assert(no
->is_function());
5245 Function
*func
= no
->func_value();
5246 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5248 int budget
= budget_heuristic
;
5249 Inline_within_budget
iwb(&budget
);
5250 func
->block()->traverse(&iwb
);
5253 func
->set_export_for_inlining();
5254 this->marked_functions_
->insert(no
);
5257 return TRAVERSE_CONTINUE
;
5260 // Export identifiers as requested.
5268 // Mark any functions whose body should be exported for inlining by
5270 Unordered_set(Named_object
*) marked_functions
;
5271 Mark_inline_candidates
mic(&marked_functions
);
5272 this->traverse(&mic
);
5274 // For now we always stream to a section. Later we may want to
5275 // support streaming to a separate file.
5276 Stream_to_section
stream(this->backend());
5278 // Write out either the prefix or pkgpath depending on how we were
5281 std::string pkgpath
;
5282 if (this->pkgpath_from_option_
)
5283 pkgpath
= this->pkgpath_
;
5284 else if (this->prefix_from_option_
)
5285 prefix
= this->prefix_
;
5286 else if (this->is_main_package())
5291 std::string init_fn_name
;
5292 if (this->is_main_package())
5294 else if (this->need_init_fn_
)
5295 init_fn_name
= this->get_init_fn_name();
5297 init_fn_name
= this->dummy_init_fn_name();
5299 Export
exp(&stream
);
5300 exp
.register_builtin_types(this);
5301 exp
.export_globals(this->package_name(),
5307 this->imported_init_fns_
,
5308 this->package_
->bindings(),
5311 if (!this->c_header_
.empty() && !saw_errors())
5312 this->write_c_header();
5315 // Write the top level named struct types in C format to a C header
5316 // file. This is used when building the runtime package, to share
5317 // struct definitions between C and Go.
5320 Gogo::write_c_header()
5323 out
.open(this->c_header_
.c_str());
5326 go_error_at(Linemap::unknown_location(),
5327 "cannot open %s: %m", this->c_header_
.c_str());
5331 std::list
<Named_object
*> types
;
5332 Bindings
* top
= this->package_
->bindings();
5333 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
5334 p
!= top
->end_definitions();
5337 Named_object
* no
= *p
;
5339 // Skip names that start with underscore followed by something
5340 // other than an uppercase letter, as when compiling the runtime
5341 // package they are mostly types defined by mkrsysinfo.sh based
5342 // on the C system header files. We don't need to translate
5343 // types to C and back to Go. But do accept the special cases
5344 // _defer, _panic, and _type.
5345 std::string name
= Gogo::unpack_hidden_name(no
->name());
5347 && (name
[1] < 'A' || name
[1] > 'Z')
5348 && (name
!= "_defer" && name
!= "_panic" && name
!= "_type"))
5351 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
5352 types
.push_back(no
);
5354 && no
->const_value()->type()->integer_type() != NULL
5355 && !no
->const_value()->is_sink())
5357 Numeric_constant nc
;
5359 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
5360 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
5362 out
<< "#define " << no
->message_name() << ' ' << val
5368 std::vector
<const Named_object
*> written
;
5370 while (!types
.empty())
5372 Named_object
* no
= types
.front();
5375 std::vector
<const Named_object
*> needs
;
5376 std::vector
<const Named_object
*> declare
;
5377 if (!no
->type_value()->struct_type()->can_write_to_c_header(&needs
,
5382 for (std::vector
<const Named_object
*>::const_iterator pr
5384 pr
!= needs
.end() && ok
;
5387 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5388 pt
!= types
.end() && ok
;
5398 // This should be impossible since the code parsed and
5403 types
.push_back(no
);
5407 for (std::vector
<const Named_object
*>::const_iterator pd
5409 pd
!= declare
.end();
5415 std::vector
<const Named_object
*> dneeds
;
5416 std::vector
<const Named_object
*> ddeclare
;
5417 if (!(*pd
)->type_value()->struct_type()->
5418 can_write_to_c_header(&dneeds
, &ddeclare
))
5422 for (std::vector
<const Named_object
*>::const_iterator pw
5424 pw
!= written
.end();
5436 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5437 written
.push_back(*pd
);
5442 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5443 no
->type_value()->struct_type()->write_to_c_header(out
);
5444 out
<< "};" << std::endl
;
5445 written
.push_back(no
);
5450 go_error_at(Linemap::unknown_location(),
5451 "error writing to %s: %m", this->c_header_
.c_str());
5454 // Find the blocks in order to convert named types defined in blocks.
5456 class Convert_named_types
: public Traverse
5459 Convert_named_types(Gogo
* gogo
)
5460 : Traverse(traverse_blocks
),
5466 block(Block
* block
);
5473 Convert_named_types::block(Block
* block
)
5475 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5476 return TRAVERSE_CONTINUE
;
5479 // Convert all named types to the backend representation. Since named
5480 // types can refer to other types, this needs to be done in the right
5481 // sequence, which is handled by Named_type::convert. Here we arrange
5482 // to call that for each named type.
5485 Gogo::convert_named_types()
5487 this->convert_named_types_in_bindings(this->globals_
);
5488 for (Packages::iterator p
= this->packages_
.begin();
5489 p
!= this->packages_
.end();
5492 Package
* package
= p
->second
;
5493 this->convert_named_types_in_bindings(package
->bindings());
5496 Convert_named_types
cnt(this);
5497 this->traverse(&cnt
);
5499 // Make all the builtin named types used for type descriptors, and
5500 // then convert them. They will only be written out if they are
5502 Type::make_type_descriptor_type();
5503 Type::make_type_descriptor_ptr_type();
5504 Function_type::make_function_type_descriptor_type();
5505 Pointer_type::make_pointer_type_descriptor_type();
5506 Struct_type::make_struct_type_descriptor_type();
5507 Array_type::make_array_type_descriptor_type();
5508 Array_type::make_slice_type_descriptor_type();
5509 Map_type::make_map_type_descriptor_type();
5510 Channel_type::make_chan_type_descriptor_type();
5511 Interface_type::make_interface_type_descriptor_type();
5512 Expression::make_func_descriptor_type();
5513 Type::convert_builtin_named_types(this);
5515 Runtime::convert_types(this);
5517 this->named_types_are_converted_
= true;
5519 Type::finish_pointer_types(this);
5522 // Convert all names types in a set of bindings.
5525 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5527 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5528 p
!= bindings
->end_definitions();
5531 if ((*p
)->is_type())
5532 (*p
)->type_value()->convert(this);
5537 debug_go_gogo(Gogo
* gogo
)
5546 std::cerr
<< "Packages:\n";
5547 for (Packages::const_iterator p
= this->packages_
.begin();
5548 p
!= this->packages_
.end();
5551 const char *tag
= " ";
5552 if (p
->second
== this->package_
)
5554 std::cerr
<< tag
<< "'" << p
->first
<< "' "
5555 << p
->second
->pkgpath() << " " << ((void*)p
->second
) << "\n";
5561 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5563 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5564 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5565 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5566 pragmas_(0), nested_functions_(0), is_sink_(false),
5567 results_are_named_(false), is_unnamed_type_stub_method_(false),
5568 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5569 calls_defer_retaddr_(false), is_type_specific_function_(false),
5570 in_unique_section_(false), export_for_inlining_(false),
5571 is_inline_only_(false), is_referenced_by_inline_(false),
5572 is_exported_by_linkname_(false)
5576 // Create the named result variables.
5579 Function::create_result_variables(Gogo
* gogo
)
5581 const Typed_identifier_list
* results
= this->type_
->results();
5582 if (results
== NULL
|| results
->empty())
5585 if (!results
->front().name().empty())
5586 this->results_are_named_
= true;
5588 this->results_
= new Results();
5589 this->results_
->reserve(results
->size());
5591 Block
* block
= this->block_
;
5593 for (Typed_identifier_list::const_iterator p
= results
->begin();
5594 p
!= results
->end();
5597 std::string name
= p
->name();
5598 if (name
.empty() || Gogo::is_sink_name(name
))
5600 static int result_counter
;
5602 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5604 name
= gogo
->pack_hidden_name(buf
, false);
5606 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5608 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5609 if (no
->is_result_variable())
5610 this->results_
->push_back(no
);
5613 static int dummy_result_count
;
5615 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5616 ++dummy_result_count
;
5617 name
= gogo
->pack_hidden_name(buf
, false);
5618 no
= block
->bindings()->add_result_variable(name
, result
);
5619 go_assert(no
->is_result_variable());
5620 this->results_
->push_back(no
);
5625 // Update the named result variables when cloning a function which
5629 Function::update_result_variables()
5631 if (this->results_
== NULL
)
5634 for (Results::iterator p
= this->results_
->begin();
5635 p
!= this->results_
->end();
5637 (*p
)->result_var_value()->set_function(this);
5640 // Whether this method should not be included in the type descriptor.
5643 Function::nointerface() const
5645 go_assert(this->is_method());
5646 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5649 // Record that this method should not be included in the type
5653 Function::set_nointerface()
5655 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5658 // Return the closure variable, creating it if necessary.
5661 Function::closure_var()
5663 if (this->closure_var_
== NULL
)
5665 go_assert(this->descriptor_
== NULL
);
5666 // We don't know the type of the variable yet. We add fields as
5668 Location loc
= this->type_
->location();
5669 Struct_field_list
* sfl
= new Struct_field_list
;
5670 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5671 struct_type
->set_is_struct_incomparable();
5672 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5673 NULL
, false, false, false, loc
);
5675 var
->set_is_closure();
5676 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5677 // Note that the new variable is not in any binding contour.
5679 return this->closure_var_
;
5682 // Set the type of the closure variable.
5685 Function::set_closure_type()
5687 if (this->closure_var_
== NULL
)
5689 Named_object
* closure
= this->closure_var_
;
5690 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5692 // The first field of a closure is always a pointer to the function
5694 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5695 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5698 unsigned int index
= 1;
5699 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5700 p
!= this->closure_fields_
.end();
5703 Named_object
* no
= p
->first
;
5705 snprintf(buf
, sizeof buf
, "%u", index
);
5706 std::string n
= no
->name() + buf
;
5708 if (no
->is_variable())
5709 var_type
= no
->var_value()->type();
5711 var_type
= no
->result_var_value()->type();
5712 Type
* field_type
= Type::make_pointer_type(var_type
);
5713 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5717 // Return whether this function is a method.
5720 Function::is_method() const
5722 return this->type_
->is_method();
5725 // Add a label definition.
5728 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5731 Label
* lnull
= NULL
;
5732 std::pair
<Labels::iterator
, bool> ins
=
5733 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5735 if (label_name
== "_")
5737 label
= Label::create_dummy_label();
5739 ins
.first
->second
= label
;
5741 else if (ins
.second
)
5743 // This is a new label.
5744 label
= new Label(label_name
);
5745 ins
.first
->second
= label
;
5749 // The label was already in the hash table.
5750 label
= ins
.first
->second
;
5751 if (label
->is_defined())
5753 go_error_at(location
, "label %qs already defined",
5754 Gogo::message_name(label_name
).c_str());
5755 go_inform(label
->location(), "previous definition of %qs was here",
5756 Gogo::message_name(label_name
).c_str());
5757 return new Label(label_name
);
5761 label
->define(location
, gogo
->bindings_snapshot(location
));
5763 // Issue any errors appropriate for any previous goto's to this
5765 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5766 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5769 (*p
)->check_goto_to(gogo
->current_block());
5770 label
->clear_refs();
5775 // Add a reference to a label.
5778 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5779 Location location
, bool issue_goto_errors
)
5781 Label
* lnull
= NULL
;
5782 std::pair
<Labels::iterator
, bool> ins
=
5783 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5787 // The label was already in the hash table.
5788 label
= ins
.first
->second
;
5792 go_assert(ins
.first
->second
== NULL
);
5793 label
= new Label(label_name
);
5794 ins
.first
->second
= label
;
5797 label
->set_is_used();
5799 if (issue_goto_errors
)
5801 Bindings_snapshot
* snapshot
= label
->snapshot();
5802 if (snapshot
!= NULL
)
5803 snapshot
->check_goto_from(gogo
->current_block(), location
);
5805 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5811 // Warn about labels that are defined but not used.
5814 Function::check_labels() const
5816 for (Labels::const_iterator p
= this->labels_
.begin();
5817 p
!= this->labels_
.end();
5820 Label
* label
= p
->second
;
5821 if (!label
->is_used())
5822 go_error_at(label
->location(), "label %qs defined and not used",
5823 Gogo::message_name(label
->name()).c_str());
5827 // Set the receiver type. This is used to remove aliases.
5830 Function::set_receiver_type(Type
* rtype
)
5832 Function_type
* oft
= this->type_
;
5833 Typed_identifier
* rec
= new Typed_identifier(oft
->receiver()->name(),
5835 oft
->receiver()->location());
5836 Typed_identifier_list
* parameters
= NULL
;
5837 if (oft
->parameters() != NULL
)
5838 parameters
= oft
->parameters()->copy();
5839 Typed_identifier_list
* results
= NULL
;
5840 if (oft
->results() != NULL
)
5841 results
= oft
->results()->copy();
5842 Function_type
* nft
= Type::make_function_type(rec
, parameters
, results
,
5847 // Swap one function with another. This is used when building the
5848 // thunk we use to call a function which calls recover. It may not
5849 // work for any other case.
5852 Function::swap_for_recover(Function
*x
)
5854 go_assert(this->enclosing_
== x
->enclosing_
);
5855 std::swap(this->results_
, x
->results_
);
5856 std::swap(this->closure_var_
, x
->closure_var_
);
5857 std::swap(this->block_
, x
->block_
);
5858 go_assert(this->location_
== x
->location_
);
5859 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5860 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5863 // Traverse the tree.
5866 Function::traverse(Traverse
* traverse
)
5868 unsigned int traverse_mask
= traverse
->traverse_mask();
5871 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5874 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5875 return TRAVERSE_EXIT
;
5878 // FIXME: We should check traverse_functions here if nested
5879 // functions are stored in block bindings.
5880 if (this->block_
!= NULL
5882 & (Traverse::traverse_variables
5883 | Traverse::traverse_constants
5884 | Traverse::traverse_blocks
5885 | Traverse::traverse_statements
5886 | Traverse::traverse_expressions
5887 | Traverse::traverse_types
)) != 0)
5889 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5890 return TRAVERSE_EXIT
;
5893 return TRAVERSE_CONTINUE
;
5896 // Work out types for unspecified variables and constants.
5899 Function::determine_types(Gogo
* gogo
)
5901 this->set_closure_type();
5902 if (this->block_
!= NULL
)
5903 this->block_
->determine_types(gogo
);
5906 // Return the function descriptor, the value you get when you refer to
5907 // the function in Go code without calling it.
5910 Function::descriptor(Gogo
*, Named_object
* no
)
5912 go_assert(!this->is_method());
5913 go_assert(this->closure_var_
== NULL
);
5914 if (this->descriptor_
== NULL
)
5915 this->descriptor_
= Expression::make_func_descriptor(no
);
5916 return this->descriptor_
;
5919 // Get a pointer to the variable representing the defer stack for this
5920 // function, making it if necessary. The value of the variable is set
5921 // by the runtime routines to true if the function is returning,
5922 // rather than panicing through. A pointer to this variable is used
5923 // as a marker for the functions on the defer stack associated with
5924 // this function. A function-specific variable permits inlining a
5925 // function which uses defer.
5928 Function::defer_stack(Location location
)
5930 if (this->defer_stack_
== NULL
)
5932 Type
* t
= Type::lookup_bool_type();
5933 Expression
* n
= Expression::make_boolean(false, location
);
5934 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5935 this->defer_stack_
->set_is_address_taken();
5937 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5939 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5942 // Export the function.
5945 Function::export_func(Export
* exp
, const Named_object
* no
) const
5947 Block
* block
= NULL
;
5948 if (this->export_for_inlining())
5949 block
= this->block_
;
5950 Function::export_func_with_type(exp
, no
, this->type_
, this->results_
,
5951 this->is_method() && this->nointerface(),
5952 this->asm_name(), block
, this->location_
);
5955 // Export a function with a type.
5958 Function::export_func_with_type(Export
* exp
, const Named_object
* no
,
5959 const Function_type
* fntype
,
5960 Function::Results
* result_vars
,
5961 bool nointerface
, const std::string
& asm_name
,
5962 Block
* block
, Location loc
)
5964 exp
->write_c_string("func ");
5968 go_assert(fntype
->is_method());
5969 exp
->write_c_string("/*nointerface*/ ");
5972 if (!asm_name
.empty())
5974 exp
->write_c_string("/*asm ");
5975 exp
->write_string(asm_name
);
5976 exp
->write_c_string(" */ ");
5979 if (fntype
->is_method())
5981 exp
->write_c_string("(");
5982 const Typed_identifier
* receiver
= fntype
->receiver();
5983 exp
->write_name(receiver
->name());
5984 exp
->write_escape(receiver
->note());
5985 exp
->write_c_string(" ");
5986 exp
->write_type(receiver
->type()->unalias());
5987 exp
->write_c_string(") ");
5990 if (no
->package() != NULL
&& !fntype
->is_method())
5993 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
5994 exp
->write_c_string(buf
);
5997 const std::string
& name(no
->name());
5998 if (!Gogo::is_hidden_name(name
))
5999 exp
->write_string(name
);
6002 exp
->write_c_string(".");
6003 exp
->write_string(Gogo::unpack_hidden_name(name
));
6006 exp
->write_c_string(" (");
6007 const Typed_identifier_list
* parameters
= fntype
->parameters();
6008 if (parameters
!= NULL
)
6011 bool is_varargs
= fntype
->is_varargs();
6013 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
6014 p
!= parameters
->end();
6020 exp
->write_c_string(", ");
6021 exp
->write_name(p
->name());
6022 exp
->write_escape(p
->note());
6023 exp
->write_c_string(" ");
6024 if (!is_varargs
|| p
+ 1 != parameters
->end())
6025 exp
->write_type(p
->type());
6028 exp
->write_c_string("...");
6029 exp
->write_type(p
->type()->array_type()->element_type());
6033 exp
->write_c_string(")");
6035 const Typed_identifier_list
* result_decls
= fntype
->results();
6036 if (result_decls
!= NULL
)
6038 if (result_decls
->size() == 1
6039 && result_decls
->begin()->name().empty()
6042 exp
->write_c_string(" ");
6043 exp
->write_type(result_decls
->begin()->type());
6047 exp
->write_c_string(" (");
6049 Results::const_iterator pr
;
6050 if (result_vars
!= NULL
)
6051 pr
= result_vars
->begin();
6052 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
6053 pd
!= result_decls
->end();
6059 exp
->write_c_string(", ");
6060 // We only use pr->name, which may be artificial, if
6061 // need it for inlining.
6062 if (block
== NULL
|| result_vars
== NULL
)
6063 exp
->write_name(pd
->name());
6065 exp
->write_name((*pr
)->name());
6066 exp
->write_escape(pd
->note());
6067 exp
->write_c_string(" ");
6068 exp
->write_type(pd
->type());
6069 if (result_vars
!= NULL
)
6072 if (result_vars
!= NULL
)
6073 go_assert(pr
== result_vars
->end());
6074 exp
->write_c_string(")");
6079 exp
->write_c_string("\n");
6083 if (fntype
->is_method())
6086 Export_function_body
efb(exp
, indent
);
6089 efb
.write_c_string("// ");
6090 efb
.write_string(Linemap::location_to_file(block
->start_location()));
6091 efb
.write_char(':');
6093 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
6094 efb
.write_c_string(buf
);
6095 efb
.write_char('\n');
6096 block
->export_block(&efb
);
6098 const std::string
& body(efb
.body());
6100 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
6101 static_cast<unsigned long>(body
.length()));
6102 exp
->write_c_string(buf
);
6104 exp
->write_string(body
);
6108 // Import a function.
6111 Function::import_func(Import
* imp
, std::string
* pname
,
6112 Package
** ppkg
, bool* pis_exported
,
6113 Typed_identifier
** preceiver
,
6114 Typed_identifier_list
** pparameters
,
6115 Typed_identifier_list
** presults
,
6118 std::string
* asm_name
,
6121 imp
->require_c_string("func ");
6123 *nointerface
= false;
6124 while (imp
->match_c_string("/*"))
6127 if (imp
->match_c_string("nointerface"))
6129 imp
->require_c_string("nointerface*/ ");
6130 *nointerface
= true;
6132 else if (imp
->match_c_string("asm"))
6134 imp
->require_c_string("asm ");
6135 *asm_name
= imp
->read_identifier();
6136 imp
->require_c_string(" */ ");
6140 go_error_at(imp
->location(),
6141 "import error at %d: unrecognized function comment",
6149 // Only a method can be nointerface.
6150 go_assert(imp
->peek_char() == '(');
6154 if (imp
->peek_char() == '(')
6156 imp
->require_c_string("(");
6157 std::string name
= imp
->read_name();
6158 std::string escape_note
= imp
->read_escape();
6159 imp
->require_c_string(" ");
6160 Type
* rtype
= imp
->read_type();
6161 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
6162 (*preceiver
)->set_note(escape_note
);
6163 imp
->require_c_string(") ");
6166 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
6168 go_error_at(imp
->location(),
6169 "import error at %d: bad function name in export data",
6174 Typed_identifier_list
* parameters
;
6175 *is_varargs
= false;
6176 imp
->require_c_string(" (");
6177 if (imp
->peek_char() == ')')
6181 parameters
= new Typed_identifier_list();
6184 std::string name
= imp
->read_name();
6185 std::string escape_note
= imp
->read_escape();
6186 imp
->require_c_string(" ");
6188 if (imp
->match_c_string("..."))
6194 Type
* ptype
= imp
->read_type();
6196 ptype
= Type::make_array_type(ptype
, NULL
);
6197 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
6198 t
.set_note(escape_note
);
6199 parameters
->push_back(t
);
6200 if (imp
->peek_char() != ',')
6202 go_assert(!*is_varargs
);
6203 imp
->require_c_string(", ");
6206 imp
->require_c_string(")");
6207 *pparameters
= parameters
;
6209 Typed_identifier_list
* results
;
6210 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
6214 results
= new Typed_identifier_list();
6215 imp
->require_c_string(" ");
6216 if (imp
->peek_char() != '(')
6218 Type
* rtype
= imp
->read_type();
6219 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
6223 imp
->require_c_string("(");
6226 std::string name
= imp
->read_name();
6227 std::string note
= imp
->read_escape();
6228 imp
->require_c_string(" ");
6229 Type
* rtype
= imp
->read_type();
6230 Typed_identifier t
= Typed_identifier(name
, rtype
,
6233 results
->push_back(t
);
6234 if (imp
->peek_char() != ',')
6236 imp
->require_c_string(", ");
6238 imp
->require_c_string(")");
6241 *presults
= results
;
6243 if (!imp
->match_c_string(" <inl:"))
6245 imp
->require_semicolon_if_old_version();
6246 imp
->require_c_string("\n");
6251 imp
->require_c_string(" <inl:");
6256 c
= imp
->peek_char();
6257 if (c
< '0' || c
> '9')
6262 imp
->require_c_string(">\n");
6266 long llen
= strtol(lenstr
.c_str(), &end
, 10);
6269 || (llen
== LONG_MAX
&& errno
== ERANGE
))
6271 go_error_at(imp
->location(), "invalid inline function length %s",
6276 imp
->read(static_cast<size_t>(llen
), body
);
6282 // Get the backend name.
6285 Function::backend_name(Gogo
* gogo
, Named_object
* no
, Backend_name
*bname
)
6287 if (!this->asm_name_
.empty())
6288 bname
->set_asm_name(this->asm_name_
);
6289 else if (no
->package() == NULL
&& no
->name() == gogo
->get_init_fn_name())
6291 // These names appear in the export data and are used
6292 // directly in the assembler code. If we change this here
6293 // we need to change Gogo::init_imports.
6294 bname
->set_asm_name(no
->name());
6296 else if (this->enclosing_
!= NULL
)
6298 // Rewrite the nested name to use the enclosing function name.
6299 // We don't do this earlier because we just store simple names
6300 // in a Named_object, not Backend_names.
6302 // The name was set by nested_function_name, which always
6303 // appends ..funcNNN. We want that to be our suffix.
6304 size_t pos
= no
->name().find("..func");
6305 go_assert(pos
!= std::string::npos
);
6307 Named_object
* enclosing
= this->enclosing_
;
6310 Named_object
* parent
= enclosing
->func_value()->enclosing();
6317 if (enclosing
->func_value()->type()->is_method())
6318 rtype
= enclosing
->func_value()->type()->receiver()->type();
6319 gogo
->function_backend_name(enclosing
->name(), enclosing
->package(),
6321 bname
->append_suffix(no
->name().substr(pos
));
6326 if (this->type_
->is_method())
6327 rtype
= this->type_
->receiver()->type();
6328 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6332 // Get the backend representation.
6335 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6337 if (this->fndecl_
== NULL
)
6339 unsigned int flags
= 0;
6340 if (no
->package() != NULL
)
6342 // Functions defined in other packages must be visible.
6343 flags
|= Backend::function_is_visible
;
6345 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
6347 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
6348 && !this->type_
->is_method())
6350 else if (no
->name() == gogo
->get_init_fn_name())
6351 flags
|= Backend::function_is_visible
;
6352 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
6353 && gogo
->is_main_package())
6354 flags
|= Backend::function_is_visible
;
6355 // Methods have to be public even if they are hidden because
6356 // they can be pulled into type descriptors when using
6357 // anonymous fields.
6358 else if (!Gogo::is_hidden_name(no
->name())
6359 || this->type_
->is_method())
6361 if (!this->is_unnamed_type_stub_method_
)
6362 flags
|= Backend::function_is_visible
;
6365 if (!this->asm_name_
.empty())
6367 // If an assembler name is explicitly specified, there must
6368 // be some reason to refer to the symbol from a different
6370 flags
|= Backend::function_is_visible
;
6373 // If an inline body refers to this function, then it
6374 // needs to be visible in the symbol table.
6375 if (this->is_referenced_by_inline_
)
6376 flags
|= Backend::function_is_visible
;
6378 // A go:linkname directive can be used to force a function to be
6380 if (this->is_exported_by_linkname_
)
6381 flags
|= Backend::function_is_visible
;
6383 // If a function calls the predeclared recover function, we
6384 // can't inline it, because recover behaves differently in a
6385 // function passed directly to defer. If this is a recover
6386 // thunk that we built to test whether a function can be
6387 // recovered, we can't inline it, because that will mess up
6388 // our return address comparison.
6389 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
6391 // If a function calls __go_set_defer_retaddr, then mark it as
6392 // uninlinable. This prevents the GCC backend from splitting
6393 // the function; splitting the function is a bad idea because we
6394 // want the return address label to be in the same function as
6396 if (this->calls_defer_retaddr_
)
6397 is_inlinable
= false;
6399 // Check the //go:noinline compiler directive.
6400 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
6401 is_inlinable
= false;
6404 flags
|= Backend::function_is_inlinable
;
6406 // If this is a thunk created to call a function which calls
6407 // the predeclared recover function, we need to disable
6408 // stack splitting for the thunk.
6409 bool disable_split_stack
= this->is_recover_thunk_
;
6411 // Check the //go:nosplit compiler directive.
6412 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
6413 disable_split_stack
= true;
6415 if (disable_split_stack
)
6416 flags
|= Backend::function_no_split_stack
;
6418 // This should go into a unique section if that has been
6419 // requested elsewhere, or if this is a nointerface function.
6420 // We want to put a nointerface function into a unique section
6421 // because there is a good chance that the linker garbage
6422 // collection can discard it.
6423 if (this->in_unique_section_
6424 || (this->is_method() && this->nointerface()))
6425 flags
|= Backend::function_in_unique_section
;
6427 if (this->is_inline_only_
)
6428 flags
|= Backend::function_only_inline
;
6430 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
6433 this->backend_name(gogo
, no
, &bname
);
6435 this->fndecl_
= gogo
->backend()->function(functype
,
6437 bname
.optional_asm_name(),
6441 return this->fndecl_
;
6444 // Get the backend name.
6447 Function_declaration::backend_name(Gogo
* gogo
, Named_object
* no
,
6448 Backend_name
* bname
)
6450 if (!this->asm_name_
.empty())
6451 bname
->set_asm_name(this->asm_name_
);
6455 if (this->fntype_
->is_method())
6456 rtype
= this->fntype_
->receiver()->type();
6457 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6461 // Get the backend representation.
6464 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6466 if (this->fndecl_
== NULL
)
6468 unsigned int flags
=
6469 (Backend::function_is_visible
6470 | Backend::function_is_declaration
6471 | Backend::function_is_inlinable
);
6473 // Let Go code use an asm declaration to pick up a builtin
6475 if (!this->asm_name_
.empty())
6477 Bfunction
* builtin_decl
=
6478 gogo
->backend()->lookup_builtin(this->asm_name_
);
6479 if (builtin_decl
!= NULL
)
6481 this->fndecl_
= builtin_decl
;
6482 return this->fndecl_
;
6485 if (this->asm_name_
== "runtime.gopanic"
6486 || this->asm_name_
.compare(0, 13, "runtime.panic") == 0
6487 || this->asm_name_
.compare(0, 15, "runtime.goPanic") == 0
6488 || this->asm_name_
== "runtime.block")
6489 flags
|= Backend::function_does_not_return
;
6492 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
6495 this->backend_name(gogo
, no
, &bname
);
6497 this->fndecl_
= gogo
->backend()->function(functype
,
6499 bname
.optional_asm_name(),
6504 return this->fndecl_
;
6507 // Build the descriptor for a function declaration. This won't
6508 // necessarily happen if the package has just a declaration for the
6509 // function and no other reference to it, but we may still need the
6510 // descriptor for references from other packages.
6512 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
6514 if (this->descriptor_
!= NULL
)
6516 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6517 this->descriptor_
->get_backend(&context
);
6521 // Check that the types used in this declaration's signature are defined.
6522 // Reports errors for any undefined type.
6525 Function_declaration::check_types() const
6527 // Calling Type::base will give errors for any undefined types.
6528 Function_type
* fntype
= this->type();
6529 if (fntype
->receiver() != NULL
)
6530 fntype
->receiver()->type()->base();
6531 if (fntype
->parameters() != NULL
)
6533 const Typed_identifier_list
* params
= fntype
->parameters();
6534 for (Typed_identifier_list::const_iterator p
= params
->begin();
6541 // Return the function's decl after it has been built.
6544 Function::get_decl() const
6546 go_assert(this->fndecl_
!= NULL
);
6547 return this->fndecl_
;
6550 // Build the backend representation for the function code.
6553 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6555 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6557 // A list of parameter variables for this function.
6558 std::vector
<Bvariable
*> param_vars
;
6560 // Variables that need to be declared for this function and their
6562 std::vector
<Bvariable
*> vars
;
6563 std::vector
<Expression
*> var_inits
;
6564 std::vector
<Statement
*> var_decls_stmts
;
6565 for (Bindings::const_definitions_iterator p
=
6566 this->block_
->bindings()->begin_definitions();
6567 p
!= this->block_
->bindings()->end_definitions();
6570 Location loc
= (*p
)->location();
6571 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6573 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6574 Bvariable
* parm_bvar
= bvar
;
6576 // We always pass the receiver to a method as a pointer. If
6577 // the receiver is declared as a non-pointer type, then we
6578 // copy the value into a local variable. For direct interface
6579 // type we pack the pointer into the type.
6580 if ((*p
)->var_value()->is_receiver()
6581 && (*p
)->var_value()->type()->points_to() == NULL
)
6583 std::string name
= (*p
)->name() + ".pointer";
6584 Type
* var_type
= (*p
)->var_value()->type();
6585 Variable
* parm_var
=
6586 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6588 Named_object
* parm_no
=
6589 Named_object::make_variable(name
, NULL
, parm_var
);
6590 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6592 vars
.push_back(bvar
);
6594 Expression
* parm_ref
=
6595 Expression::make_var_reference(parm_no
, loc
);
6596 Type
* recv_type
= (*p
)->var_value()->type();
6597 if (recv_type
->is_direct_iface_type())
6598 parm_ref
= Expression::pack_direct_iface(recv_type
, parm_ref
, loc
);
6601 Expression::make_dereference(parm_ref
,
6602 Expression::NIL_CHECK_NEEDED
,
6604 if ((*p
)->var_value()->is_in_heap())
6605 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6606 var_inits
.push_back(parm_ref
);
6608 else if ((*p
)->var_value()->is_in_heap())
6610 // If we take the address of a parameter, then we need
6611 // to copy it into the heap.
6612 std::string parm_name
= (*p
)->name() + ".param";
6613 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6614 false, true, false, loc
);
6615 Named_object
* parm_no
=
6616 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6617 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6619 vars
.push_back(bvar
);
6620 Expression
* var_ref
=
6621 Expression::make_var_reference(parm_no
, loc
);
6622 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6623 var_inits
.push_back(var_ref
);
6625 param_vars
.push_back(parm_bvar
);
6627 else if ((*p
)->is_result_variable())
6629 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6631 Type
* type
= (*p
)->result_var_value()->type();
6633 if (!(*p
)->result_var_value()->is_in_heap())
6635 Btype
* btype
= type
->get_backend(gogo
);
6636 Bexpression
* binit
= gogo
->backend()->zero_expression(btype
);
6637 init
= Expression::make_backend(binit
, type
, loc
);
6640 init
= Expression::make_allocation(type
, loc
);
6642 vars
.push_back(bvar
);
6643 var_inits
.push_back(init
);
6645 else if (this->defer_stack_
!= NULL
6646 && (*p
)->is_variable()
6647 && (*p
)->var_value()->is_non_escaping_address_taken()
6648 && !(*p
)->var_value()->is_in_heap())
6650 // Local variable captured by deferred closure needs to be live
6651 // until the end of the function. We create a top-level
6652 // declaration for it.
6653 // TODO: we don't need to do this if the variable is not captured
6654 // by the defer closure. There is no easy way to check it here,
6655 // so we do this for all address-taken variables for now.
6656 Variable
* var
= (*p
)->var_value();
6657 Temporary_statement
* ts
=
6658 Statement::make_temporary(var
->type(), NULL
, var
->location());
6659 ts
->set_is_address_taken();
6660 var
->set_toplevel_decl(ts
);
6661 var_decls_stmts
.push_back(ts
);
6664 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6666 go_assert(saw_errors());
6670 // If we need a closure variable, make sure to create it.
6671 // It gets installed in the function as a side effect of creation.
6672 if (this->closure_var_
!= NULL
)
6674 go_assert(this->closure_var_
->var_value()->is_closure());
6675 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6678 if (this->block_
!= NULL
)
6680 // Declare variables if necessary.
6681 Bblock
* var_decls
= NULL
;
6682 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6683 Bstatement
* defer_init
= NULL
;
6684 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6687 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6688 this->block_
->start_location(),
6689 this->block_
->end_location());
6691 if (this->defer_stack_
!= NULL
)
6693 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6695 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6696 var_decls_bstmt_list
.push_back(defer_init
);
6697 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6698 p
!= var_decls_stmts
.end();
6701 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6702 var_decls_bstmt_list
.push_back(bstmt
);
6707 // Build the backend representation for all the statements in the
6709 Translate_context
bcontext(gogo
, named_function
, NULL
, NULL
);
6710 Bblock
* code_block
= this->block_
->get_backend(&bcontext
);
6712 // Initialize variables if necessary.
6713 Translate_context
icontext(gogo
, named_function
, this->block_
,
6715 std::vector
<Bstatement
*> init
;
6716 go_assert(vars
.size() == var_inits
.size());
6717 for (size_t i
= 0; i
< vars
.size(); ++i
)
6719 Bexpression
* binit
= var_inits
[i
]->get_backend(&icontext
);
6720 Bstatement
* init_stmt
=
6721 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6723 init
.push_back(init_stmt
);
6725 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6727 // Initialize all variables before executing this code block.
6728 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6729 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6731 // If we have a defer stack, initialize it at the start of a
6733 Bstatement
* except
= NULL
;
6734 Bstatement
* fini
= NULL
;
6735 if (defer_init
!= NULL
)
6737 // Clean up the defer stack when we leave the function.
6738 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6740 // Wrap the code for this function in an exception handler to handle
6743 gogo
->backend()->exception_handler_statement(code_stmt
,
6748 // Stick the code into the block we built for the receiver, if
6750 if (var_decls
!= NULL
)
6752 var_decls_bstmt_list
.push_back(code_stmt
);
6753 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6754 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6757 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6759 go_assert(saw_errors());
6764 // If we created a descriptor for the function, make sure we emit it.
6765 if (this->descriptor_
!= NULL
)
6767 Translate_context
dcontext(gogo
, NULL
, NULL
, NULL
);
6768 this->descriptor_
->get_backend(&dcontext
);
6772 // Build the wrappers around function code needed if the function has
6773 // any defer statements. This sets *EXCEPT to an exception handler
6774 // and *FINI to a finally handler.
6777 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6778 Bstatement
** except
, Bstatement
** fini
)
6780 Location end_loc
= this->block_
->end_location();
6782 // Add an exception handler. This is used if a panic occurs. Its
6783 // purpose is to stop the stack unwinding if a deferred function
6784 // calls recover. There are more details in
6785 // libgo/runtime/go-unwind.c.
6787 std::vector
<Bstatement
*> stmts
;
6788 Expression
* call
= Runtime::make_call(gogo
, Runtime::CHECKDEFER
, end_loc
, 1,
6789 this->defer_stack(end_loc
));
6790 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6791 Bexpression
* defer
= call
->get_backend(&context
);
6792 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6794 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6795 if (ret_bstmt
!= NULL
)
6796 stmts
.push_back(ret_bstmt
);
6798 go_assert(*except
== NULL
);
6799 *except
= gogo
->backend()->statement_list(stmts
);
6801 call
= Runtime::make_call(gogo
, Runtime::CHECKDEFER
, end_loc
, 1,
6802 this->defer_stack(end_loc
));
6803 defer
= call
->get_backend(&context
);
6805 call
= Runtime::make_call(gogo
, Runtime::DEFERRETURN
, end_loc
, 1,
6806 this->defer_stack(end_loc
));
6807 Bexpression
* undefer
= call
->get_backend(&context
);
6808 Bstatement
* function_defer
=
6809 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6811 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6812 if (this->type_
->results() != NULL
6813 && !this->type_
->results()->empty()
6814 && !this->type_
->results()->front().name().empty())
6816 // If the result variables are named, and we are returning from
6817 // this function rather than panicing through it, we need to
6818 // return them again, because they might have been changed by a
6819 // defer function. The runtime routines set the defer_stack
6820 // variable to true if we are returning from this function.
6822 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6823 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6825 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6827 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6828 Bexpression
* bref
= ref
->get_backend(&context
);
6829 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6830 NULL
, bref
, ret
, NULL
,
6832 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6835 go_assert(*fini
== NULL
);
6836 *fini
= gogo
->backend()->statement_list(stmts
);
6839 // Return the statement that assigns values to this function's result struct.
6842 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6843 Location location
) const
6845 const Typed_identifier_list
* results
= this->type_
->results();
6846 if (results
== NULL
|| results
->empty())
6849 go_assert(this->results_
!= NULL
);
6850 if (this->results_
->size() != results
->size())
6852 go_assert(saw_errors());
6853 return gogo
->backend()->error_statement();
6856 std::vector
<Bexpression
*> vals(results
->size());
6857 for (size_t i
= 0; i
< vals
.size(); ++i
)
6859 Named_object
* no
= (*this->results_
)[i
];
6860 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6861 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6862 if (no
->result_var_value()->is_in_heap())
6864 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6865 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6869 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6874 Block::Block(Block
* enclosing
, Location location
)
6875 : enclosing_(enclosing
), statements_(),
6876 bindings_(new Bindings(enclosing
== NULL
6878 : enclosing
->bindings())),
6879 start_location_(location
),
6880 end_location_(Linemap::unknown_location())
6884 // Add a statement to a block.
6887 Block::add_statement(Statement
* statement
)
6889 this->statements_
.push_back(statement
);
6892 // Add a statement to the front of a block. This is slow but is only
6893 // used for reference counts of parameters.
6896 Block::add_statement_at_front(Statement
* statement
)
6898 this->statements_
.insert(this->statements_
.begin(), statement
);
6901 // Replace a statement in a block.
6904 Block::replace_statement(size_t index
, Statement
* s
)
6906 go_assert(index
< this->statements_
.size());
6907 this->statements_
[index
] = s
;
6910 // Add a statement before another statement.
6913 Block::insert_statement_before(size_t index
, Statement
* s
)
6915 go_assert(index
< this->statements_
.size());
6916 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6919 // Add a statement after another statement.
6922 Block::insert_statement_after(size_t index
, Statement
* s
)
6924 go_assert(index
< this->statements_
.size());
6925 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6928 // Traverse the tree.
6931 Block::traverse(Traverse
* traverse
)
6933 unsigned int traverse_mask
= traverse
->traverse_mask();
6935 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6937 int t
= traverse
->block(this);
6938 if (t
== TRAVERSE_EXIT
)
6939 return TRAVERSE_EXIT
;
6940 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6941 return TRAVERSE_CONTINUE
;
6945 & (Traverse::traverse_variables
6946 | Traverse::traverse_constants
6947 | Traverse::traverse_expressions
6948 | Traverse::traverse_types
)) != 0)
6950 for (Bindings::const_definitions_iterator pb
=
6951 this->bindings_
->begin_definitions();
6952 pb
!= this->bindings_
->end_definitions();
6955 if ((*pb
)->traverse(traverse
, false) == TRAVERSE_EXIT
)
6956 return TRAVERSE_EXIT
;
6960 // No point in checking traverse_mask here--if we got here we always
6961 // want to walk the statements. The traversal can insert new
6962 // statements before or after the current statement. Inserting
6963 // statements before the current statement requires updating I via
6964 // the pointer; those statements will not be traversed. Any new
6965 // statements inserted after the current statement will be traversed
6967 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6969 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6970 return TRAVERSE_EXIT
;
6973 return TRAVERSE_CONTINUE
;
6976 // Work out types for unspecified variables and constants.
6979 Block::determine_types(Gogo
* gogo
)
6981 for (Bindings::const_definitions_iterator pb
=
6982 this->bindings_
->begin_definitions();
6983 pb
!= this->bindings_
->end_definitions();
6986 if ((*pb
)->is_variable())
6987 (*pb
)->var_value()->determine_type(gogo
);
6988 else if ((*pb
)->is_const())
6989 (*pb
)->const_value()->determine_type(gogo
);
6992 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6993 ps
!= this->statements_
.end();
6995 (*ps
)->determine_types(gogo
);
6998 // Return true if the statements in this block may fall through.
7001 Block::may_fall_through() const
7003 if (this->statements_
.empty())
7005 return this->statements_
.back()->may_fall_through();
7008 // Write export data for a block.
7011 Block::export_block(Export_function_body
* efb
)
7013 for (Block::iterator p
= this->begin();
7019 efb
->increment_indent();
7020 (*p
)->export_statement(efb
);
7021 efb
->decrement_indent();
7023 Location loc
= (*p
)->location();
7024 if ((*p
)->is_block_statement())
7026 // For a block we put the start location on the first brace
7027 // in Block_statement::do_export_statement. Here we put the
7028 // end location on the final brace.
7029 loc
= (*p
)->block_statement()->block()->end_location();
7032 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
7033 efb
->write_c_string(buf
);
7037 // Add exported block data to SET, reading from BODY starting at OFF.
7038 // Returns whether the import succeeded.
7041 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
7043 Location eloc
= ifb
->location();
7044 Location sloc
= loc
;
7045 const std::string
& body(ifb
->body());
7046 size_t off
= ifb
->off();
7047 while (off
< body
.length())
7049 int indent
= ifb
->indent();
7050 if (off
+ indent
>= body
.length())
7053 "invalid export data for %qs: insufficient indentation",
7054 ifb
->name().c_str());
7057 for (int i
= 0; i
< indent
- 1; i
++)
7059 if (body
[off
+ i
] != ' ')
7062 "invalid export data for %qs: bad indentation",
7063 ifb
->name().c_str());
7068 bool at_end
= false;
7069 if (body
[off
+ indent
- 1] == '}')
7071 else if (body
[off
+ indent
- 1] != ' ')
7074 "invalid export data for %qs: bad indentation",
7075 ifb
->name().c_str());
7081 size_t nl
= body
.find('\n', off
);
7082 if (nl
== std::string::npos
)
7084 go_error_at(eloc
, "invalid export data for %qs: missing newline",
7085 ifb
->name().c_str());
7089 size_t lineno_pos
= body
.find(" //", off
);
7090 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
7092 go_error_at(eloc
, "invalid export data for %qs: missing line number",
7093 ifb
->name().c_str());
7097 unsigned int lineno
= 0;
7098 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
7101 if (c
< '0' || c
> '9')
7104 "invalid export data for %qs: invalid line number",
7105 ifb
->name().c_str());
7108 lineno
= lineno
* 10 + c
- '0';
7111 ifb
->gogo()->linemap()->start_line(lineno
, 1);
7112 sloc
= ifb
->gogo()->linemap()->get_location(0);
7116 // An if statement can have an "else" following the "}", in
7117 // which case we want to leave the offset where it is, just
7118 // after the "}". We don't get the block ending location
7119 // quite right for if statements.
7120 if (body
.compare(off
, 6, " else ") != 0)
7126 Statement
* s
= Statement::import_statement(ifb
, sloc
);
7130 set
->add_statement(s
);
7132 size_t at
= ifb
->off();
7140 set
->set_end_location(sloc
);
7144 // Convert a block to the backend representation.
7147 Block::get_backend(Translate_context
* context
)
7149 Gogo
* gogo
= context
->gogo();
7150 Named_object
* function
= context
->function();
7151 std::vector
<Bvariable
*> vars
;
7152 vars
.reserve(this->bindings_
->size_definitions());
7153 for (Bindings::const_definitions_iterator pv
=
7154 this->bindings_
->begin_definitions();
7155 pv
!= this->bindings_
->end_definitions();
7158 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
7159 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
7162 go_assert(function
!= NULL
);
7163 Bfunction
* bfunction
=
7164 function
->func_value()->get_or_make_decl(gogo
, function
);
7165 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
7166 vars
, this->start_location_
,
7167 this->end_location_
);
7169 Translate_context
subcontext(gogo
, function
, this, ret
);
7170 std::vector
<Bstatement
*> bstatements
;
7171 bstatements
.reserve(this->statements_
.size());
7172 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
7173 p
!= this->statements_
.end();
7175 bstatements
.push_back((*p
)->get_backend(&subcontext
));
7177 context
->backend()->block_add_statements(ret
, bstatements
);
7182 // Class Bindings_snapshot.
7184 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
7185 : block_(b
), counts_(), location_(location
)
7189 this->counts_
.push_back(b
->bindings()->size_definitions());
7194 // Report errors appropriate for a goto from B to this.
7197 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
7200 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
7202 this->check_goto_defs(loc
, this->block_
,
7203 this->block_
->bindings()->size_definitions(),
7207 // Report errors appropriate for a goto from this to B.
7210 Bindings_snapshot::check_goto_to(const Block
* b
)
7213 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
7215 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
7216 b
->bindings()->size_definitions());
7219 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7220 // Return true if all is well, false if we reported an error. If this
7221 // returns true, it sets *PINDEX to the number of blocks BTO is above
7225 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
7226 const Block
* bto
, size_t* pindex
)
7228 // It is an error if BTO is not either BFROM or above BFROM.
7230 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
7234 go_error_at(loc
, "goto jumps into block");
7235 go_inform(bto
->start_location(), "goto target block starts here");
7243 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7244 // CFROM is the number of names defined at the point of the goto and
7245 // CTO is the number of names defined at the point of the label.
7248 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
7249 size_t cfrom
, size_t cto
)
7253 Bindings::const_definitions_iterator p
=
7254 block
->bindings()->begin_definitions();
7255 for (size_t i
= 0; i
< cfrom
; ++i
)
7257 go_assert(p
!= block
->bindings()->end_definitions());
7260 go_assert(p
!= block
->bindings()->end_definitions());
7262 for (; p
!= block
->bindings()->end_definitions(); ++p
)
7264 if ((*p
)->is_variable())
7266 std::string n
= (*p
)->message_name();
7267 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
7268 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
7274 // Class Function_declaration.
7276 // Whether this declares a method.
7279 Function_declaration::is_method() const
7281 return this->fntype_
->is_method();
7284 // Whether this method should not be included in the type descriptor.
7287 Function_declaration::nointerface() const
7289 go_assert(this->is_method());
7290 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
7293 // Record that this method should not be included in the type
7297 Function_declaration::set_nointerface()
7299 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
7302 // Set the receiver type. This is used to remove aliases.
7305 Function_declaration::set_receiver_type(Type
* rtype
)
7307 Function_type
* oft
= this->fntype_
;
7308 Typed_identifier
* rec
= new Typed_identifier(oft
->receiver()->name(),
7310 oft
->receiver()->location());
7311 Typed_identifier_list
* parameters
= NULL
;
7312 if (oft
->parameters() != NULL
)
7313 parameters
= oft
->parameters()->copy();
7314 Typed_identifier_list
* results
= NULL
;
7315 if (oft
->results() != NULL
)
7316 results
= oft
->results()->copy();
7317 Function_type
* nft
= Type::make_function_type(rec
, parameters
, results
,
7319 this->fntype_
= nft
;
7322 // Import an inlinable function. This is used for an inlinable
7323 // function whose body is recorded in the export data. Parse the
7324 // export data into a Block and create a regular function using that
7325 // Block as its body. Redeclare this function declaration as the
7329 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
7331 go_assert(no
->func_declaration_value() == this);
7332 go_assert(no
->package() != NULL
);
7333 const std::string
& body(this->imported_body_
);
7334 go_assert(!body
.empty());
7336 // Read the "//FILE:LINE" comment starts the export data.
7339 if (this->is_method())
7342 for (; i
< indent
; i
++)
7344 if (body
.at(i
) != ' ')
7346 go_error_at(this->location_
,
7347 "invalid export body for %qs: bad initial indentation",
7348 no
->message_name().c_str());
7353 if (body
.substr(i
, 2) != "//")
7355 go_error_at(this->location_
,
7356 "invalid export body for %qs: missing file comment",
7357 no
->message_name().c_str());
7361 size_t colon
= body
.find(':', i
+ 2);
7362 size_t nl
= body
.find('\n', i
+ 2);
7363 if (nl
== std::string::npos
)
7365 go_error_at(this->location_
,
7366 "invalid export body for %qs: missing file name",
7367 no
->message_name().c_str());
7370 if (colon
== std::string::npos
|| nl
< colon
)
7372 go_error_at(this->location_
,
7373 "invalid export body for %qs: missing initial line number",
7374 no
->message_name().c_str());
7378 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
7379 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
7381 long linenol
= strtol(linestr
.c_str(), &end
, 10);
7384 go_error_at(this->location_
,
7385 "invalid export body for %qs: invalid initial line number",
7386 no
->message_name().c_str());
7389 unsigned int lineno
= static_cast<unsigned int>(linenol
);
7391 // Turn the file/line into a location.
7393 char* alc
= new char[file
.length() + 1];
7394 memcpy(alc
, file
.data(), file
.length());
7395 alc
[file
.length()] = '\0';
7396 gogo
->linemap()->start_file(alc
, lineno
);
7397 gogo
->linemap()->start_line(lineno
, 1);
7398 Location start_loc
= gogo
->linemap()->get_location(0);
7400 // Define the function with an outer block that declares the
7403 Function_type
* fntype
= this->fntype_
;
7405 Block
* outer
= new Block(NULL
, start_loc
);
7407 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
7408 fn
->set_is_inline_only();
7410 if (fntype
->is_method())
7412 if (this->nointerface())
7413 fn
->set_nointerface();
7414 const Typed_identifier
* receiver
= fntype
->receiver();
7415 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
7416 true, true, start_loc
);
7418 std::string rname
= receiver
->name();
7419 unsigned rcounter
= 0;
7421 // We need to give a nameless receiver a name to avoid having it
7422 // clash with some other nameless param. FIXME.
7423 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
7425 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
7428 const Typed_identifier_list
* params
= fntype
->parameters();
7429 bool is_varargs
= fntype
->is_varargs();
7430 unsigned pcounter
= 0;
7433 for (Typed_identifier_list::const_iterator p
= params
->begin();
7437 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
7439 if (is_varargs
&& p
+ 1 == params
->end())
7440 param
->set_is_varargs_parameter();
7442 std::string pname
= p
->name();
7444 // We need to give each nameless parameter a non-empty name to avoid
7445 // having it clash with some other nameless param. FIXME.
7446 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
7448 outer
->bindings()->add_variable(pname
, NULL
, param
);
7452 fn
->create_result_variables(gogo
);
7454 if (!fntype
->is_method())
7456 const Package
* package
= no
->package();
7457 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
7461 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
7462 go_assert(rtype
!= NULL
);
7463 no
= rtype
->add_method(no
->name(), fn
);
7464 const Package
* package
= rtype
->named_object()->package();
7465 package
->bindings()->add_method(no
);
7468 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
7470 if (!Block::import_block(outer
, &ifb
, start_loc
))
7473 outer
->determine_types(gogo
);
7474 gogo
->lower_block(no
, outer
);
7476 gogo
->add_imported_inline_function(no
);
7479 // Return the function descriptor.
7482 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
7484 go_assert(!this->fntype_
->is_method());
7485 if (this->descriptor_
== NULL
)
7486 this->descriptor_
= Expression::make_func_descriptor(no
);
7487 return this->descriptor_
;
7492 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
7493 bool is_parameter
, bool is_receiver
,
7495 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
7496 toplevel_decl_(NULL
), init_refs_(NULL
), embeds_(NULL
), backend_(NULL
),
7497 is_global_(is_global
), is_parameter_(is_parameter
), is_closure_(false),
7498 is_receiver_(is_receiver
), is_varargs_parameter_(false),
7499 is_global_sink_(false), is_used_(false), is_address_taken_(false),
7500 is_non_escaping_address_taken_(false), seen_(false),
7501 init_is_lowered_(false), init_is_flattened_(false),
7502 type_from_init_tuple_(false), type_from_range_index_(false),
7503 type_from_range_value_(false), type_from_chan_element_(false),
7504 is_type_switch_var_(false), determined_type_(false),
7505 in_unique_section_(false), is_referenced_by_inline_(false)
7507 go_assert(type
!= NULL
|| init
!= NULL
);
7508 go_assert(!is_parameter
|| init
== NULL
);
7511 // Traverse the initializer expression.
7514 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7516 if (this->preinit_
!= NULL
)
7518 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7519 return TRAVERSE_EXIT
;
7521 if (this->init_
!= NULL
7523 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7526 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7527 return TRAVERSE_EXIT
;
7529 return TRAVERSE_CONTINUE
;
7532 // Lower the initialization expression after parsing is complete.
7535 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7536 Statement_inserter
* inserter
)
7538 Named_object
* dep
= gogo
->var_depends_on(this);
7539 if (dep
!= NULL
&& dep
->is_variable())
7540 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7542 if (this->embeds_
!= NULL
)
7544 // Now that we have seen any possible type aliases, convert the
7545 // go:embed directives into an initializer.
7546 go_assert(this->init_
== NULL
&& this->type_
!= NULL
);
7547 this->init_
= gogo
->initializer_for_embeds(this->type_
, this->embeds_
,
7549 delete this->embeds_
;
7550 this->embeds_
= NULL
;
7553 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7557 // We will give an error elsewhere, this is just to prevent
7558 // an infinite loop.
7563 Statement_inserter global_inserter
;
7564 if (this->is_global_
)
7566 global_inserter
= Statement_inserter(gogo
, this);
7567 inserter
= &global_inserter
;
7570 gogo
->lower_expression(function
, inserter
, &this->init_
);
7572 this->seen_
= false;
7574 this->init_is_lowered_
= true;
7578 // Flatten the initialization expression after ordering evaluations.
7581 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7582 Statement_inserter
* inserter
)
7584 Named_object
* dep
= gogo
->var_depends_on(this);
7585 if (dep
!= NULL
&& dep
->is_variable())
7586 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7588 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7592 // We will give an error elsewhere, this is just to prevent
7593 // an infinite loop.
7598 Statement_inserter global_inserter
;
7599 if (this->is_global_
)
7601 global_inserter
= Statement_inserter(gogo
, this);
7602 inserter
= &global_inserter
;
7605 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7607 // If an interface conversion is needed, we need a temporary
7609 if (this->type_
!= NULL
7610 && !Type::are_identical(this->type_
, this->init_
->type(),
7611 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7613 && this->init_
->type()->interface_type() != NULL
7614 && !this->init_
->is_multi_eval_safe())
7616 Temporary_statement
* temp
=
7617 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7618 inserter
->insert(temp
);
7619 this->init_
= Expression::make_temporary_reference(temp
,
7623 this->seen_
= false;
7624 this->init_is_flattened_
= true;
7628 // Get the preinit block.
7631 Variable::preinit_block(Gogo
* gogo
)
7633 go_assert(this->is_global_
);
7634 if (this->preinit_
== NULL
)
7635 this->preinit_
= new Block(NULL
, this->location());
7637 // If a global variable has a preinitialization statement, then we
7638 // need to have an initialization function.
7639 gogo
->set_need_init_fn();
7641 return this->preinit_
;
7644 // Add a statement to be run before the initialization expression.
7647 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7649 Block
* b
= this->preinit_block(gogo
);
7650 b
->add_statement(s
);
7651 b
->set_end_location(s
->location());
7654 // Whether this variable has a type.
7657 Variable::has_type() const
7659 if (this->type_
== NULL
)
7662 // A variable created in a type switch case nil does not actually
7663 // have a type yet. It will be changed to use the initializer's
7664 // type in determine_type.
7665 if (this->is_type_switch_var_
7666 && this->type_
->is_nil_constant_as_type())
7672 // In an assignment which sets a variable to a tuple of EXPR, return
7673 // the type of the first element of the tuple.
7676 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7678 if (Index_expression::is_map_index(expr
))
7681 if (expr
->map_index_expression() != NULL
)
7682 mt
= expr
->map_index_expression()->get_map_type();
7684 mt
= expr
->index_expression()->left()->type()->map_type();
7686 return Type::make_error_type();
7687 return mt
->val_type();
7689 else if (expr
->receive_expression() != NULL
)
7691 Expression
* channel
= expr
->receive_expression()->channel();
7692 Type
* channel_type
= channel
->type();
7693 if (channel_type
->channel_type() == NULL
)
7694 return Type::make_error_type();
7695 return channel_type
->channel_type()->element_type();
7700 go_error_at(this->location(), "invalid tuple definition");
7701 return Type::make_error_type();
7705 // Given EXPR used in a range clause, return either the index type or
7706 // the value type of the range, depending upon GET_INDEX_TYPE.
7709 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7710 bool report_error
) const
7712 Type
* t
= expr
->type();
7713 if (t
->is_error_type())
7715 else if (t
->array_type() != NULL
7716 || (t
->points_to() != NULL
7717 && t
->points_to()->array_type() != NULL
7718 && !t
->points_to()->is_slice_type()))
7721 return Type::lookup_integer_type("int");
7723 return t
->deref()->array_type()->element_type();
7725 else if (t
->is_string_type())
7728 return Type::lookup_integer_type("int");
7730 return Type::lookup_integer_type("int32");
7732 else if (t
->map_type() != NULL
)
7735 return t
->map_type()->key_type();
7737 return t
->map_type()->val_type();
7739 else if (t
->channel_type() != NULL
)
7742 return t
->channel_type()->element_type();
7746 go_error_at(this->location(),
7747 ("invalid definition of value variable "
7748 "for channel range"));
7749 return Type::make_error_type();
7755 go_error_at(this->location(), "invalid type for range clause");
7756 return Type::make_error_type();
7760 // EXPR should be a channel. Return the channel's element type.
7763 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7765 Type
* t
= expr
->type();
7766 if (t
->channel_type() != NULL
)
7767 return t
->channel_type()->element_type();
7771 go_error_at(this->location(), "expected channel");
7772 return Type::make_error_type();
7776 // Return the type of the Variable. This may be called before
7777 // Variable::determine_type is called, which means that we may need to
7778 // get the type from the initializer. FIXME: If we combine lowering
7779 // with type determination, then this should be unnecessary.
7784 // A variable in a type switch with a nil case will have the wrong
7785 // type here. This gets fixed up in determine_type, below.
7786 Type
* type
= this->type_
;
7787 Expression
* init
= this->init_
;
7788 if (this->is_type_switch_var_
7790 && this->type_
->is_nil_constant_as_type())
7792 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7793 go_assert(tge
!= NULL
);
7800 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7802 go_error_at(this->location_
, "variable initializer refers to itself");
7803 this->type_
= Type::make_error_type();
7812 else if (this->type_from_init_tuple_
)
7813 type
= this->type_from_tuple(init
, false);
7814 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7815 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7816 else if (this->type_from_chan_element_
)
7817 type
= this->type_from_chan_element(init
, false);
7820 go_assert(init
!= NULL
);
7821 type
= init
->type();
7822 go_assert(type
!= NULL
);
7824 // Variables should not have abstract types.
7825 if (type
->is_abstract())
7826 type
= type
->make_non_abstract_type();
7828 if (type
->is_void_type())
7829 type
= Type::make_error_type();
7832 this->seen_
= false;
7837 // Fetch the type from a const pointer, in which case it should have
7838 // been set already.
7841 Variable::type() const
7843 go_assert(this->type_
!= NULL
);
7847 // Set the type if necessary.
7850 Variable::determine_type(Gogo
* gogo
)
7852 if (this->determined_type_
)
7854 this->determined_type_
= true;
7856 if (this->preinit_
!= NULL
)
7857 this->preinit_
->determine_types(gogo
);
7859 // A variable in a type switch with a nil case will have the wrong
7860 // type here. It will have an initializer which is a type guard.
7861 // We want to initialize it to the value without the type guard, and
7862 // use the type of that value as well.
7863 if (this->is_type_switch_var_
7864 && this->type_
!= NULL
7865 && this->type_
->is_nil_constant_as_type())
7867 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7868 go_assert(tge
!= NULL
);
7870 this->init_
= tge
->expr();
7873 if (this->init_
== NULL
)
7874 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7875 else if (this->type_from_init_tuple_
)
7877 Expression
*init
= this->init_
;
7878 init
->determine_type_no_context(gogo
);
7879 this->type_
= this->type_from_tuple(init
, true);
7882 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7884 Expression
* init
= this->init_
;
7885 init
->determine_type_no_context(gogo
);
7886 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7890 else if (this->type_from_chan_element_
)
7892 Expression
* init
= this->init_
;
7893 init
->determine_type_no_context(gogo
);
7894 this->type_
= this->type_from_chan_element(init
, true);
7899 Type_context
context(this->type_
, false);
7900 this->init_
->determine_type(gogo
, &context
);
7901 if (this->type_
== NULL
)
7903 Type
* type
= this->init_
->type();
7904 go_assert(type
!= NULL
);
7905 if (type
->is_abstract())
7906 type
= type
->make_non_abstract_type();
7908 if (type
->is_void_type())
7910 go_error_at(this->location_
, "variable has no type");
7911 type
= Type::make_error_type();
7913 else if (type
->is_nil_type())
7915 go_error_at(this->location_
, "variable defined to nil type");
7916 type
= Type::make_error_type();
7918 else if (type
->is_call_multiple_result_type())
7920 go_error_at(this->location_
,
7921 "single variable set to multiple-value function call");
7922 type
= Type::make_error_type();
7930 // Get the initial value of a variable. This does not
7931 // consider whether the variable is in the heap--it returns the
7932 // initial value as though it were always stored in the stack.
7935 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7937 go_assert(this->preinit_
== NULL
);
7938 Location loc
= this->location();
7939 if (this->init_
== NULL
)
7941 go_assert(!this->is_parameter_
);
7942 if (this->is_global_
|| this->is_in_heap())
7944 Btype
* btype
= this->type()->get_backend(gogo
);
7945 return gogo
->backend()->zero_expression(btype
);
7949 Translate_context
context(gogo
, function
, NULL
, NULL
);
7950 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7951 return init
->get_backend(&context
);
7955 // Get the initial value of a variable when a block is required.
7956 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7959 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7960 Bvariable
* var_decl
)
7962 go_assert(this->preinit_
!= NULL
);
7964 // We want to add the variable assignment to the end of the preinit
7967 Translate_context
context(gogo
, function
, NULL
, NULL
);
7968 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7969 Bfunction
* bfunction
=
7970 function
->func_value()->get_or_make_decl(gogo
, function
);
7972 // It's possible to have pre-init statements without an initializer
7973 // if the pre-init statements set the variable.
7974 Bstatement
* decl_init
= NULL
;
7975 if (this->init_
!= NULL
)
7977 if (var_decl
== NULL
)
7979 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7980 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7985 Location loc
= this->location();
7986 Expression
* val_expr
=
7987 Expression::make_cast(this->type(), this->init_
, loc
);
7988 Bexpression
* val
= val_expr
->get_backend(&context
);
7989 Bexpression
* var_ref
=
7990 gogo
->backend()->var_expression(var_decl
, loc
);
7991 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7995 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7996 if (decl_init
!= NULL
)
7997 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
8001 // Add an initializer reference.
8004 Variable::add_init_ref(Named_object
* var
)
8006 if (this->init_refs_
== NULL
)
8007 this->init_refs_
= new std::vector
<Named_object
*>;
8008 this->init_refs_
->push_back(var
);
8011 // Export the variable
8014 Variable::export_var(Export
* exp
, const Named_object
* no
) const
8016 go_assert(this->is_global_
);
8017 exp
->write_c_string("var ");
8018 if (no
->package() != NULL
)
8021 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
8022 exp
->write_c_string(buf
);
8025 if (!Gogo::is_hidden_name(no
->name()))
8026 exp
->write_string(no
->name());
8029 exp
->write_c_string(".");
8030 exp
->write_string(Gogo::unpack_hidden_name(no
->name()));
8033 exp
->write_c_string(" ");
8034 exp
->write_type(this->type());
8035 exp
->write_c_string("\n");
8038 // Import a variable.
8041 Variable::import_var(Import
* imp
, std::string
* pname
, Package
** ppkg
,
8042 bool* pis_exported
, Type
** ptype
)
8044 imp
->require_c_string("var ");
8045 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
8047 go_error_at(imp
->location(),
8048 "import error at %d: bad variable name in export data",
8052 imp
->require_c_string(" ");
8053 *ptype
= imp
->read_type();
8054 imp
->require_semicolon_if_old_version();
8055 imp
->require_c_string("\n");
8059 // Convert a variable to the backend representation.
8062 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8063 const Package
* package
, const std::string
& name
)
8065 if (this->backend_
== NULL
)
8067 Backend
* backend
= gogo
->backend();
8068 Type
* type
= this->type_
;
8069 if (type
->is_error_type()
8070 || (type
->is_undefined()
8071 && (!this->is_global_
|| package
== NULL
)))
8072 this->backend_
= backend
->error_variable();
8075 bool is_parameter
= this->is_parameter_
;
8076 if (this->is_receiver_
&& type
->points_to() == NULL
)
8077 is_parameter
= false;
8078 if (this->is_in_heap())
8080 is_parameter
= false;
8081 type
= Type::make_pointer_type(type
);
8084 Btype
* btype
= type
->get_backend(gogo
);
8087 if (Map_type::is_zero_value(this))
8088 bvar
= Map_type::backend_zero_value(gogo
);
8089 else if (this->is_global_
)
8092 gogo
->global_var_backend_name(name
, package
, &bname
);
8094 bool is_hidden
= Gogo::is_hidden_name(name
);
8095 // Hack to export runtime.writeBarrier. FIXME.
8096 // This is because go:linkname doesn't work on variables.
8097 if (gogo
->compiling_runtime()
8098 && bname
.name() == "runtime.writeBarrier")
8101 // If an inline body refers to this variable, then it
8102 // needs to be visible in the symbol table.
8103 if (this->is_referenced_by_inline_
)
8106 // If this variable is in a different package, then it
8107 // can't be treated as a hidden symbol. This case can
8108 // arise when an inlined function refers to a
8109 // package-scope unexported variable.
8110 if (package
!= NULL
)
8113 unsigned int flags
= 0;
8114 if (this->is_address_taken_
8115 || this->is_non_escaping_address_taken_
)
8116 flags
|= Backend::variable_address_is_taken
;
8117 if (package
!= NULL
)
8118 flags
|= Backend::variable_is_external
;
8120 flags
|= Backend::variable_is_hidden
;
8121 if (this->in_unique_section_
)
8122 flags
|= Backend::variable_in_unique_section
;
8124 // For some reason asm_name can't be the empty string
8125 // for global_variable, so we call asm_name rather than
8126 // optional_asm_name here. FIXME.
8128 bvar
= backend
->global_variable(bname
.name(),
8133 else if (function
== NULL
)
8135 go_assert(saw_errors());
8136 bvar
= backend
->error_variable();
8140 const std::string n
= Gogo::unpack_hidden_name(name
);
8141 Bfunction
* bfunction
= function
->func_value()->get_decl();
8142 unsigned int flags
= 0;
8143 if (this->is_non_escaping_address_taken_
8144 && !this->is_in_heap())
8145 flags
|= Backend::variable_address_is_taken
;
8146 if (this->is_closure())
8147 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
8148 flags
, this->location_
);
8149 else if (is_parameter
)
8150 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
8151 flags
, this->location_
);
8154 Bvariable
* bvar_decl
= NULL
;
8155 if (this->toplevel_decl_
!= NULL
)
8157 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
8158 bvar_decl
= this->toplevel_decl_
->temporary_statement()
8159 ->get_backend_variable(&context
);
8161 bvar
= backend
->local_variable(bfunction
, n
, btype
,
8166 this->backend_
= bvar
;
8169 return this->backend_
;
8172 // Class Result_variable.
8174 // Convert a result variable to the backend representation.
8177 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8178 const std::string
& name
)
8180 if (this->backend_
== NULL
)
8182 Backend
* backend
= gogo
->backend();
8183 Type
* type
= this->type_
;
8184 if (type
->is_error())
8185 this->backend_
= backend
->error_variable();
8188 if (this->is_in_heap())
8189 type
= Type::make_pointer_type(type
);
8190 Btype
* btype
= type
->get_backend(gogo
);
8191 Bfunction
* bfunction
= function
->func_value()->get_decl();
8192 std::string n
= Gogo::unpack_hidden_name(name
);
8193 unsigned int flags
= 0;
8194 if (this->is_non_escaping_address_taken_
8195 && !this->is_in_heap())
8196 flags
|= Backend::variable_address_is_taken
;
8197 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
8202 return this->backend_
;
8205 // Class Named_constant.
8207 // Set the type of a named constant. This is only used to set the
8208 // type to an error type.
8211 Named_constant::set_type(Type
* t
)
8213 go_assert(this->type_
== NULL
|| t
->is_error_type());
8217 // Traverse the initializer expression.
8220 Named_constant::traverse_expression(Traverse
* traverse
)
8222 return Expression::traverse(&this->expr_
, traverse
);
8225 // Set the iota value in a constant expression.
8227 class Set_iota_value
: public Traverse
8230 Set_iota_value(int iota_value
)
8231 : Traverse(traverse_expressions
),
8232 iota_value_(iota_value
)
8236 expression(Expression
**);
8243 Set_iota_value::expression(Expression
** pexpr
)
8245 Expression
* expr
= *pexpr
;
8246 if (expr
->const_expression() != NULL
)
8247 expr
->const_expression()->set_iota_value(this->iota_value_
);
8248 else if (expr
->unknown_expression() != NULL
)
8250 // This case can happen for an array length that is not set in
8251 // the determine types pass.
8252 expr
->unknown_expression()->set_iota_value(this->iota_value_
);
8254 return TRAVERSE_CONTINUE
;
8257 // Determine the type of the constant.
8260 Named_constant::determine_type(Gogo
* gogo
)
8262 if (this->type_is_determined_
)
8264 this->type_is_determined_
= true;
8266 if (this->type_
!= NULL
)
8268 Type_context
context(this->type_
, this->type_
->is_abstract());
8269 this->expr_
->determine_type(gogo
, &context
);
8273 // A constant may have an abstract type.
8274 Type_context
context(NULL
, true);
8275 this->expr_
->determine_type(gogo
, &context
);
8276 this->type_
= this->expr_
->type();
8277 go_assert(this->type_
!= NULL
);
8280 Set_iota_value
siv(this->iota_value_
);
8281 this->traverse_expression(&siv
);
8284 // Indicate that we found and reported an error for this constant.
8287 Named_constant::set_error()
8289 this->type_
= Type::make_error_type();
8290 this->expr_
= Expression::make_error(this->location_
);
8293 // Export a constant.
8296 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
8298 exp
->write_c_string("const ");
8299 exp
->write_string(name
);
8300 exp
->write_c_string(" ");
8301 if (!this->type_
->is_abstract())
8303 exp
->write_type(this->type_
);
8304 exp
->write_c_string(" ");
8306 exp
->write_c_string("= ");
8308 Export_function_body
efb(exp
, 0);
8309 if (!this->type_
->is_abstract())
8310 efb
.set_type_context(this->type_
);
8311 this->expr()->export_expression(&efb
);
8312 exp
->write_string(efb
.body());
8314 exp
->write_c_string("\n");
8317 // Import a constant.
8320 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
8323 imp
->require_c_string("const ");
8324 *pname
= imp
->read_identifier();
8325 imp
->require_c_string(" ");
8326 if (imp
->peek_char() == '=')
8330 *ptype
= imp
->read_type();
8331 imp
->require_c_string(" ");
8333 imp
->require_c_string("= ");
8334 *pexpr
= Expression::import_expression(imp
, imp
->location());
8335 imp
->require_semicolon_if_old_version();
8336 imp
->require_c_string("\n");
8339 // Get the backend representation.
8342 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
8344 if (this->bconst_
== NULL
)
8346 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
8347 Type
* type
= this->type();
8348 Location loc
= this->location();
8350 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
8351 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
8352 if (type
!= NULL
&& type
->is_numeric_type())
8354 Btype
* btype
= type
->get_backend(gogo
);
8356 if (const_no
->package() == NULL
)
8357 name
= gogo
->pkgpath();
8359 name
= const_no
->package()->pkgpath();
8360 name
.push_back('.');
8361 name
.append(Gogo::unpack_hidden_name(const_no
->name()));
8363 gogo
->backend()->named_constant_expression(btype
, name
,
8366 this->bconst_
= const_decl
;
8368 return this->bconst_
;
8374 Type_declaration::add_method(const std::string
& name
, Function
* function
)
8376 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
8377 this->methods_
.push_back(ret
);
8381 // Add a method declaration.
8384 Type_declaration::add_method_declaration(const std::string
& name
,
8386 Function_type
* type
,
8389 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
8391 this->methods_
.push_back(ret
);
8395 // Return whether any methods are defined.
8398 Type_declaration::has_methods() const
8400 return !this->methods_
.empty();
8403 // Define methods for the real type.
8406 Type_declaration::define_methods(Named_type
* nt
)
8408 if (this->methods_
.empty())
8411 while (nt
->is_alias())
8413 Type
*t
= nt
->real_type()->forwarded();
8414 if (t
->named_type() != NULL
)
8415 nt
= t
->named_type();
8416 else if (t
->forward_declaration_type() != NULL
)
8418 Named_object
* no
= t
->forward_declaration_type()->named_object();
8419 Type_declaration
* td
= no
->type_declaration_value();
8420 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
8421 this->methods_
.end());
8422 this->methods_
.clear();
8427 for (std::vector
<Named_object
*>::const_iterator p
=
8428 this->methods_
.begin();
8429 p
!= this->methods_
.end();
8431 go_error_at((*p
)->location(),
8432 ("invalid receiver type "
8433 "(receiver must be a named type)"));
8438 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
8439 p
!= this->methods_
.end();
8442 if ((*p
)->is_function_declaration()
8443 || !(*p
)->func_value()->is_sink())
8444 nt
->add_existing_method(*p
);
8448 // We are using the type. Return true if we should issue a warning.
8451 Type_declaration::using_type()
8453 bool ret
= !this->issued_warning_
;
8454 this->issued_warning_
= true;
8458 // Class Unknown_name.
8460 // Set the real named object.
8463 Unknown_name::set_real_named_object(Named_object
* no
)
8465 go_assert(this->real_named_object_
== NULL
);
8466 go_assert(!no
->is_unknown());
8467 this->real_named_object_
= no
;
8470 // Class Named_object.
8472 Named_object::Named_object(const std::string
& name
,
8473 const Package
* package
,
8474 Classification classification
)
8475 : name_(name
), package_(package
), classification_(classification
),
8476 is_redefinition_(false)
8478 if (Gogo::is_sink_name(name
))
8479 go_assert(classification
== NAMED_OBJECT_SINK
);
8482 // Make an unknown name. This is used by the parser. The name must
8483 // be resolved later. Unknown names are only added in the current
8487 Named_object::make_unknown_name(const std::string
& name
,
8490 Named_object
* named_object
= new Named_object(name
, NULL
,
8491 NAMED_OBJECT_UNKNOWN
);
8492 Unknown_name
* value
= new Unknown_name(location
);
8493 named_object
->u_
.unknown_value
= value
;
8494 return named_object
;
8500 Named_object::make_constant(const Typed_identifier
& tid
,
8501 const Package
* package
, Expression
* expr
,
8504 Named_object
* named_object
= new Named_object(tid
.name(), package
,
8505 NAMED_OBJECT_CONST
);
8506 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
8509 named_object
->u_
.const_value
= named_constant
;
8510 return named_object
;
8513 // Make a named type.
8516 Named_object::make_type(const std::string
& name
, const Package
* package
,
8517 Type
* type
, Location location
)
8519 Named_object
* named_object
= new Named_object(name
, package
,
8521 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
8522 named_object
->u_
.type_value
= named_type
;
8523 return named_object
;
8526 // Make a type declaration.
8529 Named_object::make_type_declaration(const std::string
& name
,
8530 const Package
* package
,
8533 Named_object
* named_object
= new Named_object(name
, package
,
8534 NAMED_OBJECT_TYPE_DECLARATION
);
8535 Type_declaration
* type_declaration
= new Type_declaration(location
);
8536 named_object
->u_
.type_declaration
= type_declaration
;
8537 return named_object
;
8543 Named_object::make_variable(const std::string
& name
, const Package
* package
,
8546 Named_object
* named_object
= new Named_object(name
, package
,
8548 named_object
->u_
.var_value
= variable
;
8549 return named_object
;
8552 // Make a result variable.
8555 Named_object::make_result_variable(const std::string
& name
,
8556 Result_variable
* result
)
8558 Named_object
* named_object
= new Named_object(name
, NULL
,
8559 NAMED_OBJECT_RESULT_VAR
);
8560 named_object
->u_
.result_var_value
= result
;
8561 return named_object
;
8564 // Make a sink. This is used for the special blank identifier _.
8567 Named_object::make_sink()
8569 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
8572 // Make a named function.
8575 Named_object::make_function(const std::string
& name
, const Package
* package
,
8578 Named_object
* named_object
= new Named_object(name
, package
,
8580 named_object
->u_
.func_value
= function
;
8581 return named_object
;
8584 // Make a function declaration.
8587 Named_object::make_function_declaration(const std::string
& name
,
8588 const Package
* package
,
8589 Function_type
* fntype
,
8592 Named_object
* named_object
= new Named_object(name
, package
,
8593 NAMED_OBJECT_FUNC_DECLARATION
);
8594 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
8595 named_object
->u_
.func_declaration_value
= func_decl
;
8596 return named_object
;
8602 Named_object::make_package(const std::string
& alias
, Package
* package
)
8604 Named_object
* named_object
= new Named_object(alias
, NULL
,
8605 NAMED_OBJECT_PACKAGE
);
8606 named_object
->u_
.package_value
= package
;
8607 return named_object
;
8610 // Return the name to use in an error message.
8613 Named_object::message_name() const
8615 if (this->package_
== NULL
)
8616 return Gogo::message_name(this->name_
);
8618 if (this->package_
->has_package_name())
8619 ret
= this->package_
->package_name();
8621 ret
= this->package_
->pkgpath();
8622 ret
= Gogo::message_name(ret
);
8624 ret
+= Gogo::message_name(this->name_
);
8628 // Set the type when a declaration is defined.
8631 Named_object::set_type_value(Named_type
* named_type
)
8633 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8634 Type_declaration
* td
= this->u_
.type_declaration
;
8635 td
->define_methods(named_type
);
8637 Named_object
* in_function
= td
->in_function(&index
);
8638 if (in_function
!= NULL
)
8639 named_type
->set_in_function(in_function
, index
);
8641 this->classification_
= NAMED_OBJECT_TYPE
;
8642 this->u_
.type_value
= named_type
;
8645 // Define a function which was previously declared.
8648 Named_object::set_function_value(Function
* function
)
8650 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8651 if (this->func_declaration_value()->has_descriptor())
8653 Expression
* descriptor
=
8654 this->func_declaration_value()->descriptor(NULL
, NULL
);
8655 function
->set_descriptor(descriptor
);
8657 this->classification_
= NAMED_OBJECT_FUNC
;
8658 // FIXME: We should free the old value.
8659 this->u_
.func_value
= function
;
8662 // Declare an unknown object as a type declaration.
8665 Named_object::declare_as_type()
8667 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8668 Unknown_name
* unk
= this->u_
.unknown_value
;
8669 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8670 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8674 // Return the location of a named object.
8677 Named_object::location() const
8679 switch (this->classification_
)
8682 case NAMED_OBJECT_UNINITIALIZED
:
8685 case NAMED_OBJECT_ERRONEOUS
:
8686 return Linemap::unknown_location();
8688 case NAMED_OBJECT_UNKNOWN
:
8689 return this->unknown_value()->location();
8691 case NAMED_OBJECT_CONST
:
8692 return this->const_value()->location();
8694 case NAMED_OBJECT_TYPE
:
8695 return this->type_value()->location();
8697 case NAMED_OBJECT_TYPE_DECLARATION
:
8698 return this->type_declaration_value()->location();
8700 case NAMED_OBJECT_VAR
:
8701 return this->var_value()->location();
8703 case NAMED_OBJECT_RESULT_VAR
:
8704 return this->result_var_value()->location();
8706 case NAMED_OBJECT_SINK
:
8709 case NAMED_OBJECT_FUNC
:
8710 return this->func_value()->location();
8712 case NAMED_OBJECT_FUNC_DECLARATION
:
8713 return this->func_declaration_value()->location();
8715 case NAMED_OBJECT_PACKAGE
:
8716 return this->package_value()->location();
8720 // Traverse a Named_object.
8723 Named_object::traverse(Traverse
* traverse
, bool is_global
)
8725 const unsigned int traverse_mask
= traverse
->traverse_mask();
8726 const unsigned int e_or_t
= (Traverse::traverse_expressions
8727 | Traverse::traverse_types
);
8728 const unsigned int e_or_t_or_s
= (e_or_t
8729 | Traverse::traverse_statements
);
8731 int t
= TRAVERSE_CONTINUE
;
8732 switch (this->classification_
)
8734 case Named_object::NAMED_OBJECT_CONST
:
8735 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
8736 t
= traverse
->constant(this, is_global
);
8737 if (t
== TRAVERSE_CONTINUE
8738 && (traverse_mask
& e_or_t
) != 0)
8740 Type
* tc
= this->const_value()->type();
8743 if (Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
8744 return TRAVERSE_EXIT
;
8746 t
= this->const_value()->traverse_expression(traverse
);
8750 case Named_object::NAMED_OBJECT_VAR
:
8751 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8752 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
8753 t
= traverse
->variable(this);
8754 if (t
== TRAVERSE_CONTINUE
8755 && (traverse_mask
& e_or_t
) != 0)
8757 if (this->is_result_variable() || this->var_value()->has_type())
8759 Type
* tv
= (this->is_variable()
8760 ? this->var_value()->type()
8761 : this->result_var_value()->type());
8764 if (Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
8765 return TRAVERSE_EXIT
;
8769 if (t
== TRAVERSE_CONTINUE
8770 && (traverse_mask
& e_or_t_or_s
) != 0
8771 && this->is_variable())
8772 t
= this->var_value()->traverse_expression(traverse
,
8776 case Named_object::NAMED_OBJECT_FUNC
:
8777 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
8778 t
= traverse
->function(this);
8779 if (t
== TRAVERSE_CONTINUE
8781 & (Traverse::traverse_variables
8782 | Traverse::traverse_constants
8783 | Traverse::traverse_functions
8784 | Traverse::traverse_blocks
8785 | Traverse::traverse_statements
8786 | Traverse::traverse_expressions
8787 | Traverse::traverse_types
)) != 0)
8788 t
= this->func_value()->traverse(traverse
);
8791 case Named_object::NAMED_OBJECT_TYPE
:
8792 if ((traverse_mask
& e_or_t
) != 0)
8793 t
= Type::traverse(this->type_value(), traverse
);
8796 case Named_object::NAMED_OBJECT_PACKAGE
:
8797 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8798 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8799 case Named_object::NAMED_OBJECT_UNKNOWN
:
8800 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8803 case Named_object::NAMED_OBJECT_SINK
:
8813 // Export a named object.
8816 Named_object::export_named_object(Export
* exp
) const
8818 switch (this->classification_
)
8821 case NAMED_OBJECT_UNINITIALIZED
:
8822 case NAMED_OBJECT_UNKNOWN
:
8825 case NAMED_OBJECT_ERRONEOUS
:
8828 case NAMED_OBJECT_CONST
:
8829 this->const_value()->export_const(exp
, this->name_
);
8832 case NAMED_OBJECT_TYPE
:
8833 // Types are handled by export::write_types.
8836 case NAMED_OBJECT_TYPE_DECLARATION
:
8837 go_error_at(this->type_declaration_value()->location(),
8838 "attempt to export %<%s%> which was declared but not defined",
8839 this->message_name().c_str());
8842 case NAMED_OBJECT_FUNC_DECLARATION
:
8843 this->func_declaration_value()->export_func(exp
, this);
8846 case NAMED_OBJECT_VAR
:
8847 this->var_value()->export_var(exp
, this);
8850 case NAMED_OBJECT_RESULT_VAR
:
8851 case NAMED_OBJECT_SINK
:
8854 case NAMED_OBJECT_FUNC
:
8855 this->func_value()->export_func(exp
, this);
8860 // Convert a variable to the backend representation.
8863 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8865 if (this->classification_
== NAMED_OBJECT_VAR
)
8866 return this->var_value()->get_backend_variable(gogo
, function
,
8867 this->package_
, this->name_
);
8868 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8869 return this->result_var_value()->get_backend_variable(gogo
, function
,
8876 debug_go_named_object(Named_object
* no
)
8880 std::cerr
<< "<null>";
8883 std::cerr
<< "'" << no
->name() << "': ";
8885 switch (no
->classification())
8887 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8888 tag
= "uninitialized";
8890 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8893 case Named_object::NAMED_OBJECT_UNKNOWN
:
8896 case Named_object::NAMED_OBJECT_CONST
:
8899 case Named_object::NAMED_OBJECT_TYPE
:
8902 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8905 case Named_object::NAMED_OBJECT_VAR
:
8908 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8911 case Named_object::NAMED_OBJECT_SINK
:
8914 case Named_object::NAMED_OBJECT_FUNC
:
8917 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8920 case Named_object::NAMED_OBJECT_PACKAGE
:
8924 tag
= "<unknown named object classification>";
8927 std::cerr
<< tag
<< "\n";
8930 // Get the backend representation for this named object.
8933 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8934 std::vector
<Btype
*>& type_decls
,
8935 std::vector
<Bfunction
*>& func_decls
)
8937 // If this is a definition, avoid trying to get the backend
8938 // representation, as that can crash.
8939 if (this->is_redefinition_
)
8941 go_assert(saw_errors());
8945 switch (this->classification_
)
8947 case NAMED_OBJECT_CONST
:
8948 if (!Gogo::is_erroneous_name(this->name_
))
8949 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8952 case NAMED_OBJECT_TYPE
:
8954 Named_type
* named_type
= this->u_
.type_value
;
8956 // No need to do anything for aliases-- whatever has to be done
8957 // can be done for the alias target.
8958 if (named_type
->is_alias())
8961 if (!Gogo::is_erroneous_name(this->name_
))
8962 type_decls
.push_back(named_type
->get_backend(gogo
));
8964 // We need to produce a type descriptor for every named
8965 // type, and for a pointer to every named type, since
8966 // other files or packages might refer to them. We need
8967 // to do this even for hidden types, because they might
8968 // still be returned by some function. Simply calling the
8969 // type_descriptor method is enough to create the type
8970 // descriptor, even though we don't do anything with it.
8971 if (this->package_
== NULL
&& !saw_errors())
8974 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8975 Type
* pn
= Type::make_pointer_type(named_type
);
8976 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8977 if (named_type
->in_heap())
8979 named_type
->gc_symbol_pointer(gogo
);
8980 pn
->gc_symbol_pointer(gogo
);
8986 case NAMED_OBJECT_TYPE_DECLARATION
:
8987 go_error_at(Linemap::unknown_location(),
8988 "reference to undefined type %qs",
8989 this->message_name().c_str());
8992 case NAMED_OBJECT_VAR
:
8993 case NAMED_OBJECT_RESULT_VAR
:
8994 case NAMED_OBJECT_SINK
:
8997 case NAMED_OBJECT_FUNC
:
8999 Function
* func
= this->u_
.func_value
;
9000 if (!Gogo::is_erroneous_name(this->name_
))
9001 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
9003 if (func
->block() != NULL
)
9004 func
->build(gogo
, this);
9008 case NAMED_OBJECT_ERRONEOUS
:
9018 Bindings::Bindings(Bindings
* enclosing
)
9019 : enclosing_(enclosing
), named_objects_(), bindings_()
9026 Bindings::clear_file_scope(Gogo
* gogo
)
9028 Contour::iterator p
= this->bindings_
.begin();
9029 while (p
!= this->bindings_
.end())
9032 if (p
->second
->package() != NULL
)
9034 else if (p
->second
->is_package())
9036 else if (p
->second
->is_function()
9037 && !p
->second
->func_value()->type()->is_method()
9038 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
9047 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
9048 p
= this->bindings_
.erase(p
);
9053 // Look up a symbol.
9056 Bindings::lookup(const std::string
& name
) const
9058 Contour::const_iterator p
= this->bindings_
.find(name
);
9059 if (p
!= this->bindings_
.end())
9060 return p
->second
->resolve();
9061 else if (this->enclosing_
!= NULL
)
9062 return this->enclosing_
->lookup(name
);
9067 // Look up a symbol locally.
9070 Bindings::lookup_local(const std::string
& name
) const
9072 Contour::const_iterator p
= this->bindings_
.find(name
);
9073 if (p
== this->bindings_
.end())
9078 // Remove an object from a set of bindings. This is used for a
9079 // special case in thunks for functions which call recover.
9082 Bindings::remove_binding(Named_object
* no
)
9084 Contour::iterator pb
= this->bindings_
.find(no
->name());
9085 go_assert(pb
!= this->bindings_
.end());
9086 this->bindings_
.erase(pb
);
9087 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
9088 pn
!= this->named_objects_
.end();
9093 this->named_objects_
.erase(pn
);
9100 // Add a method to the list of objects. This is not added to the
9101 // lookup table. This is so that we have a single list of objects
9102 // declared at the top level, which we walk through when it's time to
9103 // convert to trees.
9106 Bindings::add_method(Named_object
* method
)
9108 this->named_objects_
.push_back(method
);
9111 // Add a generic Named_object to a Contour.
9114 Bindings::add_named_object_to_contour(Contour
* contour
,
9115 Named_object
* named_object
)
9117 go_assert(named_object
== named_object
->resolve());
9118 const std::string
& name(named_object
->name());
9119 go_assert(!Gogo::is_sink_name(name
));
9121 std::pair
<Contour::iterator
, bool> ins
=
9122 contour
->insert(std::make_pair(name
, named_object
));
9125 // The name was already there.
9126 if (named_object
->package() != NULL
9127 && ins
.first
->second
->package() == named_object
->package()
9128 && (ins
.first
->second
->classification()
9129 == named_object
->classification()))
9131 // This is a second import of the same object.
9132 return ins
.first
->second
;
9134 ins
.first
->second
= this->new_definition(ins
.first
->second
,
9136 return ins
.first
->second
;
9140 // Don't push declarations on the list. We push them on when
9141 // and if we find the definitions. That way we genericize the
9142 // functions in order.
9143 if (!named_object
->is_type_declaration()
9144 && !named_object
->is_function_declaration()
9145 && !named_object
->is_unknown())
9146 this->named_objects_
.push_back(named_object
);
9147 return named_object
;
9151 // We had an existing named object OLD_OBJECT, and we've seen a new
9152 // one NEW_OBJECT with the same name. FIXME: This does not free the
9153 // new object when we don't need it.
9156 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
9158 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
9162 switch (old_object
->classification())
9165 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
9168 case Named_object::NAMED_OBJECT_ERRONEOUS
:
9171 case Named_object::NAMED_OBJECT_UNKNOWN
:
9173 Named_object
* real
= old_object
->unknown_value()->real_named_object();
9175 return this->new_definition(real
, new_object
);
9176 go_assert(!new_object
->is_unknown());
9177 old_object
->unknown_value()->set_real_named_object(new_object
);
9178 if (!new_object
->is_type_declaration()
9179 && !new_object
->is_function_declaration())
9180 this->named_objects_
.push_back(new_object
);
9184 case Named_object::NAMED_OBJECT_CONST
:
9187 case Named_object::NAMED_OBJECT_TYPE
:
9188 if (new_object
->is_type_declaration())
9192 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
9193 if (new_object
->is_type_declaration())
9195 if (new_object
->is_type())
9197 old_object
->set_type_value(new_object
->type_value());
9198 new_object
->type_value()->set_named_object(old_object
);
9199 this->named_objects_
.push_back(old_object
);
9204 case Named_object::NAMED_OBJECT_VAR
:
9205 case Named_object::NAMED_OBJECT_RESULT_VAR
:
9206 // We have already given an error in the parser for cases where
9207 // one parameter or result variable redeclares another one.
9208 if ((new_object
->is_variable()
9209 && new_object
->var_value()->is_parameter())
9210 || new_object
->is_result_variable())
9214 case Named_object::NAMED_OBJECT_SINK
:
9217 case Named_object::NAMED_OBJECT_FUNC
:
9220 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
9222 // We declare the hash and equality functions before defining
9223 // them, because we sometimes see that we need the declaration
9224 // while we are in the middle of a different function.
9226 // We declare the main function before the user defines it, to
9227 // give better error messages.
9229 // We declare inline functions before we define them, as we
9230 // only define them if we need them.
9231 if (new_object
->is_function()
9232 && ((Linemap::is_predeclared_location(old_object
->location())
9233 && Linemap::is_predeclared_location(new_object
->location()))
9234 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
9235 && Linemap::is_unknown_location(old_object
->location()))
9236 || (new_object
->package() != NULL
9237 && old_object
->func_declaration_value()->has_imported_body()
9238 && new_object
->func_value()->is_inline_only())))
9240 Function_type
* old_type
=
9241 old_object
->func_declaration_value()->type();
9242 Function_type
* new_type
= new_object
->func_value()->type();
9243 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
9245 Function_declaration
* fd
=
9246 old_object
->func_declaration_value();
9247 go_assert(fd
->asm_name().empty());
9248 old_object
->set_function_value(new_object
->func_value());
9249 this->named_objects_
.push_back(old_object
);
9256 case Named_object::NAMED_OBJECT_PACKAGE
:
9260 std::string n
= old_object
->message_name();
9262 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
9264 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
9266 old_object
->set_is_redefinition();
9267 new_object
->set_is_redefinition();
9269 if (!Linemap::is_unknown_location(old_object
->location())
9270 && !Linemap::is_predeclared_location(old_object
->location()))
9271 go_inform(old_object
->location(), "previous definition of %qs was here",
9277 // Add a named type.
9280 Bindings::add_named_type(Named_type
* named_type
)
9282 return this->add_named_object(named_type
->named_object());
9288 Bindings::add_function(const std::string
& name
, const Package
* package
,
9291 return this->add_named_object(Named_object::make_function(name
, package
,
9295 // Add a function declaration.
9298 Bindings::add_function_declaration(const std::string
& name
,
9299 const Package
* package
,
9300 Function_type
* type
,
9303 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
9305 return this->add_named_object(no
);
9308 // Define a type which was previously declared.
9311 Bindings::define_type(Named_object
* no
, Named_type
* type
)
9313 no
->set_type_value(type
);
9314 this->named_objects_
.push_back(no
);
9317 // Mark all local variables as used. This is used for some types of
9321 Bindings::mark_locals_used()
9323 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
9324 p
!= this->named_objects_
.end();
9326 if ((*p
)->is_variable())
9327 (*p
)->var_value()->set_is_used();
9330 // Traverse bindings.
9333 Bindings::traverse(Traverse
* traverse
, bool is_global
)
9335 unsigned int traverse_mask
= traverse
->traverse_mask();
9337 // We don't use an iterator because we permit the traversal to add
9338 // new global objects.
9339 const unsigned int e_or_t
= (Traverse::traverse_expressions
9340 | Traverse::traverse_types
);
9341 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9343 Named_object
* p
= this->named_objects_
[i
];
9344 if (p
->traverse(traverse
, is_global
) == TRAVERSE_EXIT
)
9345 return TRAVERSE_EXIT
;
9348 // If we need to traverse types, check the function declarations,
9349 // which have types. Also check any methods of a type declaration.
9350 if ((traverse_mask
& e_or_t
) != 0)
9352 for (Bindings::const_declarations_iterator p
=
9353 this->begin_declarations();
9354 p
!= this->end_declarations();
9357 if (p
->second
->is_function_declaration())
9359 if (Type::traverse(p
->second
->func_declaration_value()->type(),
9362 return TRAVERSE_EXIT
;
9364 else if (p
->second
->is_type_declaration())
9366 const std::vector
<Named_object
*>* methods
=
9367 p
->second
->type_declaration_value()->methods();
9368 for (std::vector
<Named_object
*>::const_iterator pm
=
9370 pm
!= methods
->end();
9373 Named_object
* no
= *pm
;
9375 if (no
->is_function())
9376 t
= no
->func_value()->type();
9377 else if (no
->is_function_declaration())
9378 t
= no
->func_declaration_value()->type();
9381 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
9382 return TRAVERSE_EXIT
;
9388 // Traverse function declarations when needed.
9389 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
9391 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
9392 p
!= this->end_declarations();
9395 if (p
->second
->is_function_declaration())
9397 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
9398 return TRAVERSE_EXIT
;
9403 return TRAVERSE_CONTINUE
;
9406 // Determine types for the objects.
9409 Bindings::determine_types(Gogo
* gogo
)
9411 // We don't use an iterator because the traversal can add new
9413 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9415 Named_object
* no
= this->named_objects_
[i
];
9416 if (no
->is_function())
9417 no
->func_value()->determine_types(gogo
);
9418 else if (no
->is_variable())
9419 no
->var_value()->determine_type(gogo
);
9420 else if (no
->is_const())
9421 no
->const_value()->determine_type(gogo
);
9423 // See if a variable requires us to build an initialization
9424 // function. We know that we will see all global variables
9426 if (!gogo
->need_init_fn() && no
->is_variable())
9428 Variable
* variable
= no
->var_value();
9430 // If this is a global variable which requires runtime
9431 // initialization, we need an initialization function.
9433 if (!variable
->is_global())
9436 if (variable
->init() == NULL
)
9438 else if (variable
->type()->interface_type() != NULL
)
9439 gogo
->set_need_init_fn();
9440 else if (variable
->init()->is_constant())
9442 else if (!variable
->init()->is_composite_literal())
9443 gogo
->set_need_init_fn();
9444 else if (variable
->init()->is_nonconstant_composite_literal())
9445 gogo
->set_need_init_fn();
9447 // If this global variable holds a pointer value, we need an
9448 // initialization function to register it as a GC root.
9449 if (variable
->type()->has_pointer())
9450 gogo
->set_need_init_fn();
9456 Bindings::debug_dump()
9458 std::set
<Named_object
*> defs
;
9459 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9460 defs
.insert(this->named_objects_
[i
]);
9461 for (Contour::iterator p
= this->bindings_
.begin();
9462 p
!= this->bindings_
.end();
9465 const char* tag
= " ";
9466 if (defs
.find(p
->second
) != defs
.end())
9469 debug_go_named_object(p
->second
);
9474 debug_go_bindings(Bindings
* bindings
)
9476 if (bindings
!= NULL
)
9477 bindings
->debug_dump();
9482 // Clear any references to this label.
9487 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
9488 p
!= this->refs_
.end();
9491 this->refs_
.clear();
9494 // Get the backend representation for a label.
9497 Label::get_backend_label(Translate_context
* context
)
9499 if (this->blabel_
== NULL
)
9501 Function
* function
= context
->function()->func_value();
9502 Bfunction
* bfunction
= function
->get_decl();
9503 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
9506 return this->blabel_
;
9509 // Return an expression for the address of this label.
9512 Label::get_addr(Translate_context
* context
, Location location
)
9514 Blabel
* label
= this->get_backend_label(context
);
9515 return context
->backend()->label_address(label
, location
);
9518 // Return the dummy label that represents any instance of the blank label.
9521 Label::create_dummy_label()
9523 static Label
* dummy_label
;
9524 if (dummy_label
== NULL
)
9526 dummy_label
= new Label("_");
9527 dummy_label
->set_is_used();
9532 // Class Unnamed_label.
9534 // Get the backend representation for an unnamed label.
9537 Unnamed_label::get_blabel(Translate_context
* context
)
9539 if (this->blabel_
== NULL
)
9541 Function
* function
= context
->function()->func_value();
9542 Bfunction
* bfunction
= function
->get_decl();
9543 this->blabel_
= context
->backend()->label(bfunction
, "",
9546 return this->blabel_
;
9549 // Return a statement which defines this unnamed label.
9552 Unnamed_label::get_definition(Translate_context
* context
)
9554 Blabel
* blabel
= this->get_blabel(context
);
9555 return context
->backend()->label_definition_statement(blabel
);
9558 // Return a goto statement to this unnamed label.
9561 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
9563 Blabel
* blabel
= this->get_blabel(context
);
9564 return context
->backend()->goto_statement(blabel
, location
);
9569 Package::Package(const std::string
& pkgpath
,
9570 const std::string
& pkgpath_symbol
, Location location
)
9571 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
9572 package_name_(), bindings_(new Bindings(NULL
)),
9575 go_assert(!pkgpath
.empty());
9578 // Set the package name.
9581 Package::set_package_name(const std::string
& package_name
, Location location
)
9583 go_assert(!package_name
.empty());
9584 if (this->package_name_
.empty())
9585 this->package_name_
= package_name
;
9586 else if (this->package_name_
!= package_name
)
9587 go_error_at(location
,
9588 ("saw two different packages with "
9589 "the same package path %s: %s, %s"),
9590 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
9591 package_name
.c_str());
9594 // Return the pkgpath symbol, which is a prefix for symbols defined in
9598 Package::pkgpath_symbol() const
9600 if (this->pkgpath_symbol_
.empty())
9601 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
9602 return this->pkgpath_symbol_
;
9605 // Set the package path symbol.
9608 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
9610 go_assert(!pkgpath_symbol
.empty());
9611 if (this->pkgpath_symbol_
.empty())
9612 this->pkgpath_symbol_
= pkgpath_symbol
;
9614 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
9617 // Note that symbol from this package was and qualified by ALIAS.
9620 Package::note_usage(const std::string
& alias
) const
9622 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9623 go_assert(p
!= this->aliases_
.end());
9624 p
->second
->note_usage();
9627 // Forget a given usage. If forgetting this usage means this package becomes
9628 // unused, report that error.
9631 Package::forget_usage(Expression
* usage
) const
9633 if (this->fake_uses_
.empty())
9636 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
9637 go_assert(p
!= this->fake_uses_
.end());
9638 this->fake_uses_
.erase(p
);
9640 if (this->fake_uses_
.empty())
9641 go_error_at(this->location(), "imported and not used: %s",
9642 Gogo::message_name(this->package_name()).c_str());
9645 // Clear the used field for the next file. If the only usages of this package
9646 // are possibly fake, keep the fake usages for lowering.
9649 Package::clear_used()
9651 std::string dot_alias
= "." + this->package_name();
9652 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
9653 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
9654 this->fake_uses_
.clear();
9656 this->aliases_
.clear();
9660 Package::add_alias(const std::string
& alias
, Location location
)
9662 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9663 if (p
== this->aliases_
.end())
9665 std::pair
<Aliases::iterator
, bool> ret
;
9666 ret
= this->aliases_
.insert(std::make_pair(alias
,
9667 new Package_alias(location
)));
9673 // Determine types of constants. Everything else in a package
9674 // (variables, function declarations) should already have a fixed
9675 // type. Constants may have abstract types.
9678 Package::determine_types(Gogo
* gogo
)
9680 Bindings
* bindings
= this->bindings_
;
9681 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
9682 p
!= bindings
->end_definitions();
9685 if ((*p
)->is_const())
9686 (*p
)->const_value()->determine_type(gogo
);
9694 Traverse::~Traverse()
9696 if (this->types_seen_
!= NULL
)
9697 delete this->types_seen_
;
9698 if (this->expressions_seen_
!= NULL
)
9699 delete this->expressions_seen_
;
9702 // Record that we are looking at a type, and return true if we have
9706 Traverse::remember_type(const Type
* type
)
9708 if (type
->is_error_type())
9710 go_assert((this->traverse_mask() & traverse_types
) != 0
9711 || (this->traverse_mask() & traverse_expressions
) != 0);
9712 // We mostly only have to remember named types. But it turns out
9713 // that an interface type can refer to itself without using a name
9714 // by relying on interface inheritance, as in
9716 // type I interface { F() interface{I} }
9718 // Similarly it is possible for array types to refer to themselves
9719 // without a name, e.g.
9721 // var x [uintptr(unsafe.Sizeof(&x))]byte
9723 if (type
->classification() != Type::TYPE_NAMED
9724 && type
->classification() != Type::TYPE_ARRAY
9725 && type
->classification() != Type::TYPE_INTERFACE
)
9727 if (this->types_seen_
== NULL
)
9728 this->types_seen_
= new Types_seen();
9729 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9733 // Record that we are looking at an expression, and return true if we
9734 // have already seen it. NB: this routine used to assert if the traverse
9735 // mask did not include expressions/types -- this is no longer the case,
9736 // since it can be useful to remember specific expressions during
9737 // walks that only cover statements.
9740 Traverse::remember_expression(const Expression
* expression
)
9742 if (this->expressions_seen_
== NULL
)
9743 this->expressions_seen_
= new Expressions_seen();
9744 std::pair
<Expressions_seen::iterator
, bool> ins
=
9745 this->expressions_seen_
->insert(expression
);
9749 // The default versions of these functions should never be called: the
9750 // traversal mask indicates which functions may be called.
9753 Traverse::variable(Named_object
*)
9759 Traverse::constant(Named_object
*, bool)
9765 Traverse::function(Named_object
*)
9771 Traverse::block(Block
*)
9777 Traverse::statement(Block
*, size_t*, Statement
*)
9783 Traverse::expression(Expression
**)
9789 Traverse::type(Type
*)
9795 Traverse::function_declaration(Named_object
*)
9800 // Class Statement_inserter.
9803 Statement_inserter::insert(Statement
* s
)
9805 if (this->statements_added_
!= NULL
)
9806 this->statements_added_
->insert(s
);
9808 if (this->block_
!= NULL
)
9810 go_assert(this->pindex_
!= NULL
);
9811 this->block_
->insert_statement_before(*this->pindex_
, s
);
9814 else if (this->var_
!= NULL
)
9815 this->var_
->add_preinit_statement(this->gogo_
, s
);
9817 go_assert(saw_errors());