1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #include "filenames.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
17 #include "go-optimize.h"
20 #include "statements.h"
21 #include "expressions.h"
30 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
35 globals_(new Bindings(NULL
)),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
58 nil_check_size_threshold_(4096),
61 specific_type_functions_(),
62 specific_type_functions_are_written_(false),
63 named_types_are_converted_(false),
66 imported_inlinable_functions_(),
67 imported_inline_functions_()
69 const Location loc
= Linemap::predeclared_location();
71 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
72 RUNTIME_TYPE_KIND_UINT8
);
73 this->add_named_type(uint8_type
);
74 this->add_named_type(Type::make_integer_type("uint16", true, 16,
75 RUNTIME_TYPE_KIND_UINT16
));
76 this->add_named_type(Type::make_integer_type("uint32", true, 32,
77 RUNTIME_TYPE_KIND_UINT32
));
78 this->add_named_type(Type::make_integer_type("uint64", true, 64,
79 RUNTIME_TYPE_KIND_UINT64
));
81 this->add_named_type(Type::make_integer_type("int8", false, 8,
82 RUNTIME_TYPE_KIND_INT8
));
83 this->add_named_type(Type::make_integer_type("int16", false, 16,
84 RUNTIME_TYPE_KIND_INT16
));
85 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
86 RUNTIME_TYPE_KIND_INT32
);
87 this->add_named_type(int32_type
);
88 this->add_named_type(Type::make_integer_type("int64", false, 64,
89 RUNTIME_TYPE_KIND_INT64
));
91 this->add_named_type(Type::make_float_type("float32", 32,
92 RUNTIME_TYPE_KIND_FLOAT32
));
93 this->add_named_type(Type::make_float_type("float64", 64,
94 RUNTIME_TYPE_KIND_FLOAT64
));
96 this->add_named_type(Type::make_complex_type("complex64", 64,
97 RUNTIME_TYPE_KIND_COMPLEX64
));
98 this->add_named_type(Type::make_complex_type("complex128", 128,
99 RUNTIME_TYPE_KIND_COMPLEX128
));
101 int int_type_size
= pointer_size
;
102 if (int_type_size
< 32)
104 this->add_named_type(Type::make_integer_type("uint", true,
106 RUNTIME_TYPE_KIND_UINT
));
107 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
108 RUNTIME_TYPE_KIND_INT
);
109 this->add_named_type(int_type
);
111 this->add_named_type(Type::make_integer_type("uintptr", true,
113 RUNTIME_TYPE_KIND_UINTPTR
));
115 // "byte" is an alias for "uint8".
116 uint8_type
->integer_type()->set_is_byte();
117 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
119 byte_type
->type_value()->set_is_alias();
120 this->add_named_type(byte_type
->type_value());
122 // "rune" is an alias for "int32".
123 int32_type
->integer_type()->set_is_rune();
124 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
126 rune_type
->type_value()->set_is_alias();
127 this->add_named_type(rune_type
->type_value());
129 this->add_named_type(Type::make_named_bool_type());
131 this->add_named_type(Type::make_named_string_type());
133 // "error" is interface { Error() string }.
135 Typed_identifier_list
*methods
= new Typed_identifier_list
;
136 Typed_identifier_list
*results
= new Typed_identifier_list
;
137 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
138 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
139 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
140 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
141 error_iface
->finalize_methods();
142 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
143 this->add_named_type(error_type
);
146 this->globals_
->add_constant(Typed_identifier("true",
147 Type::make_boolean_type(),
150 Expression::make_boolean(true, loc
),
152 this->globals_
->add_constant(Typed_identifier("false",
153 Type::make_boolean_type(),
156 Expression::make_boolean(false, loc
),
159 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
162 Expression::make_nil(loc
),
165 Type
* abstract_int_type
= Type::make_abstract_integer_type();
166 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
169 Expression::make_iota(),
172 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
173 new_type
->set_is_varargs();
174 new_type
->set_is_builtin();
175 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
177 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
178 make_type
->set_is_varargs();
179 make_type
->set_is_builtin();
180 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
182 Typed_identifier_list
* len_result
= new Typed_identifier_list();
183 len_result
->push_back(Typed_identifier("", int_type
, loc
));
184 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
186 len_type
->set_is_builtin();
187 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
189 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
190 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
191 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
193 cap_type
->set_is_builtin();
194 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
196 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
197 print_type
->set_is_varargs();
198 print_type
->set_is_builtin();
199 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
201 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
202 print_type
->set_is_varargs();
203 print_type
->set_is_builtin();
204 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
206 Type
*empty
= Type::make_empty_interface_type(loc
);
207 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
208 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
209 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
211 panic_type
->set_is_builtin();
212 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
214 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
215 recover_result
->push_back(Typed_identifier("", empty
, loc
));
216 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
219 recover_type
->set_is_builtin();
220 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
222 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
223 close_type
->set_is_varargs();
224 close_type
->set_is_builtin();
225 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
227 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
228 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
229 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
231 copy_type
->set_is_varargs();
232 copy_type
->set_is_builtin();
233 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
235 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
236 append_type
->set_is_varargs();
237 append_type
->set_is_builtin();
238 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
240 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
241 complex_type
->set_is_varargs();
242 complex_type
->set_is_builtin();
243 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
245 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
246 real_type
->set_is_varargs();
247 real_type
->set_is_builtin();
248 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
250 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
251 imag_type
->set_is_varargs();
252 imag_type
->set_is_builtin();
253 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
255 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
256 delete_type
->set_is_varargs();
257 delete_type
->set_is_builtin();
258 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
262 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
264 go_assert(!pkgpath
.empty());
265 return go_encode_id(pkgpath
);
268 // Return a hash code for a string, given a starting hash.
271 Gogo::hash_string(const std::string
& s
, unsigned int h
)
273 const char* p
= s
.data();
274 size_t len
= s
.length();
275 for (; len
> 0; --len
)
283 // Get the package path to use for type reflection data. This should
284 // ideally be unique across the entire link.
287 Gogo::pkgpath() const
289 go_assert(this->pkgpath_set_
);
290 return this->pkgpath_
;
293 // Set the package path from the -fgo-pkgpath command line option.
296 Gogo::set_pkgpath(const std::string
& arg
)
298 go_assert(!this->pkgpath_set_
);
299 this->pkgpath_
= arg
;
300 this->pkgpath_set_
= true;
301 this->pkgpath_from_option_
= true;
304 // Get the package path to use for symbol names.
307 Gogo::pkgpath_symbol() const
309 go_assert(this->pkgpath_set_
);
310 return this->pkgpath_symbol_
;
313 // Set the unique prefix to use to determine the package path, from
314 // the -fgo-prefix command line option.
317 Gogo::set_prefix(const std::string
& arg
)
319 go_assert(!this->prefix_from_option_
);
321 this->prefix_from_option_
= true;
324 // Given a name which may or may not have been hidden, append the
325 // appropriate version of the name to the result string. Take care
326 // to avoid creating a sequence that will be rejected by go_encode_id
327 // (avoid ..u, ..U, ..z).
329 Gogo::append_possibly_hidden_name(std::string
*result
, const std::string
& name
)
331 // FIXME: This adds in pkgpath twice for hidden symbols, which is
333 if (!Gogo::is_hidden_name(name
))
338 std::string pkgpath
= Gogo::hidden_name_pkgpath(name
);
339 char lastR
= result
->at(result
->length() - 1);
340 char firstP
= pkgpath
.at(0);
341 if (lastR
== '.' && (firstP
== 'u' || firstP
== 'U' || firstP
== 'z'))
345 n
.append(Gogo::unpack_hidden_name(name
));
350 // Munge name for use in an error message.
353 Gogo::message_name(const std::string
& name
)
355 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
358 // Get the package name.
361 Gogo::package_name() const
363 go_assert(this->package_
!= NULL
);
364 return this->package_
->package_name();
367 // Set the package name.
370 Gogo::set_package_name(const std::string
& package_name
,
373 if (this->package_
!= NULL
)
375 if (this->package_
->package_name() != package_name
)
376 go_error_at(location
, "expected package %<%s%>",
377 Gogo::message_name(this->package_
->package_name()).c_str());
381 // Now that we know the name of the package we are compiling, set
382 // the package path to use for reflect.Type.PkgPath and global
384 if (this->pkgpath_set_
)
385 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
388 if (!this->prefix_from_option_
&& package_name
== "main")
390 this->pkgpath_
= package_name
;
391 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
395 if (!this->prefix_from_option_
)
396 this->prefix_
= "go";
397 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
398 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
399 + Gogo::pkgpath_for_symbol(package_name
));
401 this->pkgpath_set_
= true;
404 this->package_
= this->register_package(this->pkgpath_
,
405 this->pkgpath_symbol_
, location
);
406 this->package_
->set_package_name(package_name
, location
);
408 if (this->is_main_package())
410 // Declare "main" as a function which takes no parameters and
412 Location uloc
= Linemap::unknown_location();
413 this->declare_function(Gogo::pack_hidden_name("main", false),
414 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
419 // Return whether this is the "main" package. This is not true if
420 // -fgo-pkgpath or -fgo-prefix was used.
423 Gogo::is_main_package() const
425 return (this->package_name() == "main"
426 && !this->pkgpath_from_option_
427 && !this->prefix_from_option_
);
433 Gogo::import_package(const std::string
& filename
,
434 const std::string
& local_name
,
435 bool is_local_name_exported
,
439 if (filename
.empty())
441 go_error_at(location
, "import path is empty");
445 const char *pf
= filename
.data();
446 const char *pend
= pf
+ filename
.length();
450 int adv
= Lex::fetch_char(pf
, &c
);
453 go_error_at(location
, "import path contains invalid UTF-8 sequence");
458 go_error_at(location
, "import path contains NUL");
461 if (c
< 0x20 || c
== 0x7f)
463 go_error_at(location
, "import path contains control character");
468 go_error_at(location
, "import path contains backslash; use slash");
471 if (Lex::is_unicode_space(c
))
473 go_error_at(location
, "import path contains space character");
476 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
478 go_error_at(location
,
479 "import path contains invalid character '%c'", c
);
485 if (IS_ABSOLUTE_PATH(filename
.c_str()))
487 go_error_at(location
, "import path cannot be absolute path");
491 if (local_name
== "init")
492 go_error_at(location
, "cannot import package as init");
494 if (filename
== "unsafe")
496 this->import_unsafe(local_name
, is_local_name_exported
, location
);
497 this->current_file_imported_unsafe_
= true;
501 Imports::const_iterator p
= this->imports_
.find(filename
);
502 if (p
!= this->imports_
.end())
504 Package
* package
= p
->second
;
505 package
->set_location(location
);
506 std::string ln
= local_name
;
507 bool is_ln_exported
= is_local_name_exported
;
510 ln
= package
->package_name();
511 go_assert(!ln
.empty());
512 is_ln_exported
= Lex::is_exported_name(ln
);
518 Bindings
* bindings
= package
->bindings();
519 for (Bindings::const_declarations_iterator p
=
520 bindings
->begin_declarations();
521 p
!= bindings
->end_declarations();
523 this->add_dot_import_object(p
->second
);
524 std::string dot_alias
= "." + package
->package_name();
525 package
->add_alias(dot_alias
, location
);
529 package
->add_alias(ln
, location
);
530 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
531 this->package_
->bindings()->add_package(ln
, package
);
536 Import::Stream
* stream
= Import::open_package(filename
, location
,
537 this->relative_import_path_
);
541 go_error_at(location
, "import file %qs not found", filename
.c_str());
545 Import
* imp
= new Import(stream
, location
);
546 imp
->register_builtin_types(this);
547 Package
* package
= imp
->import(this, local_name
, is_local_name_exported
);
550 if (package
->pkgpath() == this->pkgpath())
551 go_error_at(location
,
552 ("imported package uses same package path as package "
553 "being compiled (see -fgo-pkgpath option)"));
555 this->imports_
.insert(std::make_pair(filename
, package
));
561 // FIXME: we never delete imp; we may need it for inlinable functions.
565 Gogo::lookup_init(const std::string
& init_name
)
567 Import_init
tmp("", init_name
, -1);
568 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
569 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
572 // Add an import control function for an imported package to the list.
575 Gogo::add_import_init_fn(const std::string
& package_name
,
576 const std::string
& init_name
, int prio
)
578 for (Import_init_set::iterator p
=
579 this->imported_init_fns_
.begin();
580 p
!= this->imported_init_fns_
.end();
583 Import_init
*ii
= (*p
);
584 if (ii
->init_name() == init_name
)
586 // If a test of package P1, built as part of package P1,
587 // imports package P2, and P2 imports P1 (perhaps
588 // indirectly), then we will see the same import name with
589 // different import priorities. That is OK, so don't give
590 // an error about it.
591 if (ii
->package_name() != package_name
)
593 go_error_at(Linemap::unknown_location(),
594 "duplicate package initialization name %qs",
595 Gogo::message_name(init_name
).c_str());
596 go_inform(Linemap::unknown_location(), "used by package %qs",
597 Gogo::message_name(ii
->package_name()).c_str());
598 go_inform(Linemap::unknown_location(), " and by package %qs",
599 Gogo::message_name(package_name
).c_str());
601 ii
->set_priority(prio
);
606 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
607 this->imported_init_fns_
.insert(nii
);
610 // Return whether we are at the global binding level.
613 Gogo::in_global_scope() const
615 return this->functions_
.empty();
618 // Return the current binding contour.
621 Gogo::current_bindings()
623 if (!this->functions_
.empty())
624 return this->functions_
.back().blocks
.back()->bindings();
625 else if (this->package_
!= NULL
)
626 return this->package_
->bindings();
628 return this->globals_
;
632 Gogo::current_bindings() const
634 if (!this->functions_
.empty())
635 return this->functions_
.back().blocks
.back()->bindings();
636 else if (this->package_
!= NULL
)
637 return this->package_
->bindings();
639 return this->globals_
;
643 Gogo::update_init_priority(Import_init
* ii
,
644 std::set
<const Import_init
*>* visited
)
649 for (std::set
<std::string
>::const_iterator pci
=
650 ii
->precursors().begin();
651 pci
!= ii
->precursors().end();
654 Import_init
* succ
= this->lookup_init(*pci
);
655 if (visited
->find(succ
) == visited
->end())
656 update_init_priority(succ
, visited
);
657 succ_prior
= std::max(succ_prior
, succ
->priority());
659 if (ii
->priority() <= succ_prior
)
660 ii
->set_priority(succ_prior
+ 1);
664 Gogo::recompute_init_priorities()
666 std::set
<Import_init
*> nonroots
;
668 for (Import_init_set::const_iterator p
=
669 this->imported_init_fns_
.begin();
670 p
!= this->imported_init_fns_
.end();
673 const Import_init
*ii
= *p
;
674 for (std::set
<std::string
>::const_iterator pci
=
675 ii
->precursors().begin();
676 pci
!= ii
->precursors().end();
679 Import_init
* ii
= this->lookup_init(*pci
);
684 // Recursively update priorities starting at roots.
685 std::set
<const Import_init
*> visited
;
686 for (Import_init_set::iterator p
=
687 this->imported_init_fns_
.begin();
688 p
!= this->imported_init_fns_
.end();
691 Import_init
* ii
= *p
;
692 if (nonroots
.find(ii
) != nonroots
.end())
694 update_init_priority(ii
, &visited
);
698 // Add statements to INIT_STMTS which run the initialization
699 // functions for imported packages. This is only used for the "main"
703 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
705 go_assert(this->is_main_package());
707 if (this->imported_init_fns_
.empty())
710 Location unknown_loc
= Linemap::unknown_location();
711 Function_type
* func_type
=
712 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
713 Btype
* fntype
= func_type
->get_backend_fntype(this);
715 // Recompute init priorities based on a walk of the init graph.
716 recompute_init_priorities();
718 // We must call them in increasing priority order.
719 std::vector
<const Import_init
*> v
;
720 for (Import_init_set::const_iterator p
=
721 this->imported_init_fns_
.begin();
722 p
!= this->imported_init_fns_
.end();
725 if ((*p
)->priority() < 0)
726 go_error_at(Linemap::unknown_location(),
727 "internal error: failed to set init priority for %s",
728 (*p
)->package_name().c_str());
731 std::sort(v
.begin(), v
.end(), priority_compare
);
733 // We build calls to the init functions, which take no arguments.
734 std::vector
<Bexpression
*> empty_args
;
735 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
739 const Import_init
* ii
= *p
;
740 std::string user_name
= ii
->package_name() + ".init";
741 const std::string
& init_name(ii
->init_name());
742 const unsigned int flags
=
743 (Backend::function_is_visible
744 | Backend::function_is_declaration
745 | Backend::function_is_inlinable
);
746 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
748 Bexpression
* pfunc_code
=
749 this->backend()->function_code_expression(pfunc
, unknown_loc
);
750 Bexpression
* pfunc_call
=
751 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
753 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
758 // Register global variables with the garbage collector. We need to
759 // register all variables which can hold a pointer value. They become
760 // roots during the mark phase. We build a struct that is easy to
761 // hook into a list of roots.
763 // type gcRoot struct {
764 // decl unsafe.Pointer // Pointer to variable.
765 // size uintptr // Total size of variable.
766 // ptrdata uintptr // Length of variable's gcdata.
767 // gcdata *byte // Pointer mask.
770 // type gcRootList struct {
776 // The last entry in the roots array has a NULL decl field.
779 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
780 std::vector
<Bstatement
*>& init_stmts
,
783 if (var_gc
.empty() && this->gc_roots_
.empty())
786 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
787 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
788 Type
* byte_type
= this->lookup_global("byte")->type_value();
789 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
790 Struct_type
* root_type
=
791 Type::make_builtin_struct_type(4,
793 "size", uintptr_type
,
794 "ptrdata", uintptr_type
,
795 "gcdata", pointer_byte_type
);
797 Location builtin_loc
= Linemap::predeclared_location();
798 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
799 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
801 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
802 root_array_type
->set_is_array_incomparable();
804 Type
* int_type
= Type::lookup_integer_type("int");
805 Struct_type
* root_list_type
=
806 Type::make_builtin_struct_type(3,
809 "roots", root_array_type
);
811 // Build an initializer for the roots array.
813 Expression_list
* roots_init
= new Expression_list();
815 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
819 Expression_list
* init
= new Expression_list();
821 Location no_loc
= (*p
)->location();
822 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
823 Expression
* decl_addr
=
824 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
825 decl_addr
->unary_expression()->set_does_not_escape();
826 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
827 init
->push_back(decl_addr
);
830 Expression::make_type_info(decl
->type(),
831 Expression::TYPE_INFO_SIZE
);
832 init
->push_back(size
);
834 Expression
* ptrdata
=
835 Expression::make_type_info(decl
->type(),
836 Expression::TYPE_INFO_BACKEND_PTRDATA
);
837 init
->push_back(ptrdata
);
839 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
840 init
->push_back(gcdata
);
842 Expression
* root_ctor
=
843 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
844 roots_init
->push_back(root_ctor
);
847 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
848 p
!= this->gc_roots_
.end();
851 Expression_list
*init
= new Expression_list();
853 Expression
* expr
= *p
;
854 Location eloc
= expr
->location();
855 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
857 Type
* type
= expr
->type()->points_to();
858 go_assert(type
!= NULL
);
861 Expression::make_type_info(type
,
862 Expression::TYPE_INFO_SIZE
);
863 init
->push_back(size
);
865 Expression
* ptrdata
=
866 Expression::make_type_info(type
,
867 Expression::TYPE_INFO_BACKEND_PTRDATA
);
868 init
->push_back(ptrdata
);
870 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
871 init
->push_back(gcdata
);
873 Expression
* root_ctor
=
874 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
875 roots_init
->push_back(root_ctor
);
878 // Build a constructor for the struct.
880 Expression_list
* root_list_init
= new Expression_list();
881 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
882 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
885 Expression
* roots_ctor
=
886 Expression::make_array_composite_literal(root_array_type
, roots_init
,
888 root_list_init
->push_back(roots_ctor
);
890 Expression
* root_list_ctor
=
891 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
894 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
896 root_addr
->unary_expression()->set_is_gc_root();
897 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
898 builtin_loc
, 1, root_addr
);
900 Translate_context
context(this, NULL
, NULL
, NULL
);
901 Bexpression
* bcall
= register_roots
->get_backend(&context
);
902 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
905 // Build the decl for the initialization function.
908 Gogo::initialization_function_decl()
910 std::string name
= this->get_init_fn_name();
911 Location loc
= this->package_
->location();
913 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
914 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
915 return Named_object::make_function(name
, NULL
, initfn
);
918 // Create the magic initialization function. CODE_STMT is the
919 // code that it needs to run.
922 Gogo::create_initialization_function(Named_object
* initfn
,
923 Bstatement
* code_stmt
)
925 // Make sure that we thought we needed an initialization function,
926 // as otherwise we will not have reported it in the export data.
927 go_assert(this->is_main_package() || this->need_init_fn_
);
930 initfn
= this->initialization_function_decl();
932 // Bind the initialization function code to a block.
933 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
934 Location pkg_loc
= this->package_
->location();
935 std::vector
<Bvariable
*> vars
;
936 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
938 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
940 go_assert(saw_errors());
946 // Given an expression, collect all the global variables defined in
947 // this package that it references.
949 class Find_vars
: public Traverse
952 // The list of variables we accumulate.
953 typedef Unordered_set(Named_object
*) Vars
;
955 // A hash table we use to avoid looping. The index is a
956 // Named_object* or a Temporary_statement*. We only look through
957 // objects defined in this package.
958 typedef Unordered_set(const void*) Seen_objects
;
962 : Traverse(traverse_expressions
),
963 vars_(), seen_objects_()
966 // An iterator through the variables found, after the traversal.
967 typedef Vars::const_iterator const_iterator
;
971 { return this->vars_
.begin(); }
975 { return this->vars_
.end(); }
978 expression(Expression
**);
981 // Accumulated variables.
983 // Objects we have already seen.
984 Seen_objects seen_objects_
;
987 // Collect global variables referenced by EXPR. Look through function
988 // calls and variable initializations.
991 Find_vars::expression(Expression
** pexpr
)
993 Expression
* e
= *pexpr
;
995 Var_expression
* ve
= e
->var_expression();
998 Named_object
* v
= ve
->named_object();
999 if (!v
->is_variable() || v
->package() != NULL
)
1001 // This is a result parameter or a variable defined in a
1002 // different package. Either way we don't care about it.
1003 return TRAVERSE_CONTINUE
;
1006 std::pair
<Seen_objects::iterator
, bool> ins
=
1007 this->seen_objects_
.insert(v
);
1010 // We've seen this variable before.
1011 return TRAVERSE_CONTINUE
;
1014 if (v
->var_value()->is_global())
1015 this->vars_
.insert(v
);
1017 Expression
* init
= v
->var_value()->init();
1020 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1021 return TRAVERSE_EXIT
;
1025 // We traverse the code of any function or bound method we see. Note that
1026 // this means that we will traverse the code of a function or bound method
1027 // whose address is taken even if it is not called.
1028 Func_expression
* fe
= e
->func_expression();
1029 Bound_method_expression
* bme
= e
->bound_method_expression();
1030 if (fe
!= NULL
|| bme
!= NULL
)
1032 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1033 if (f
->is_function() && f
->package() == NULL
)
1035 std::pair
<Seen_objects::iterator
, bool> ins
=
1036 this->seen_objects_
.insert(f
);
1039 // This is the first time we have seen this name.
1040 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1041 return TRAVERSE_EXIT
;
1046 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1049 Temporary_statement
* ts
= tre
->statement();
1050 Expression
* init
= ts
->init();
1053 std::pair
<Seen_objects::iterator
, bool> ins
=
1054 this->seen_objects_
.insert(ts
);
1057 // This is the first time we have seen this temporary
1059 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1060 return TRAVERSE_EXIT
;
1065 return TRAVERSE_CONTINUE
;
1068 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1071 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1074 Find_vars find_vars
;
1076 Expression::traverse(&expr
, &find_vars
);
1077 if (preinit
!= NULL
)
1078 preinit
->traverse(&find_vars
);
1081 Expression
* init
= dep
->var_value()->init();
1083 Expression::traverse(&init
, &find_vars
);
1084 if (dep
->var_value()->has_pre_init())
1085 dep
->var_value()->preinit()->traverse(&find_vars
);
1088 for (Find_vars::const_iterator p
= find_vars
.begin();
1089 p
!= find_vars
.end();
1098 // Sort variable initializations. If the initialization expression
1099 // for variable A refers directly or indirectly to the initialization
1100 // expression for variable B, then we must initialize B before A.
1106 : var_(NULL
), init_(NULL
), refs_(NULL
), dep_count_(0)
1109 Var_init(Named_object
* var
, Bstatement
* init
)
1110 : var_(var
), init_(init
), refs_(NULL
), dep_count_(0)
1113 // Return the variable.
1116 { return this->var_
; }
1118 // Return the initialization expression.
1121 { return this->init_
; }
1125 add_ref(Named_object
* var
);
1127 // The variables which this variable's initializers refer to.
1128 const std::vector
<Named_object
*>*
1130 { return this->refs_
; }
1132 // Clear the references, if any.
1136 // Return the number of remaining dependencies.
1139 { return this->dep_count_
; }
1141 // Increment the number of dependencies.
1144 { ++this->dep_count_
; }
1146 // Decrement the number of dependencies.
1149 { --this->dep_count_
; }
1152 // The variable being initialized.
1154 // The backend initialization statement.
1156 // Variables this refers to.
1157 std::vector
<Named_object
*>* refs_
;
1158 // The number of initializations this is dependent on. A variable
1159 // initialization should not be emitted if any of its dependencies
1160 // have not yet been resolved.
1167 Var_init::add_ref(Named_object
* var
)
1169 if (this->refs_
== NULL
)
1170 this->refs_
= new std::vector
<Named_object
*>;
1171 this->refs_
->push_back(var
);
1174 // Clear the references, if any.
1177 Var_init::clear_refs()
1179 if (this->refs_
!= NULL
)
1186 // For comparing Var_init keys in a map.
1189 operator<(const Var_init
& v1
, const Var_init
& v2
)
1190 { return v1
.var()->name() < v2
.var()->name(); }
1192 typedef std::list
<Var_init
> Var_inits
;
1194 // Sort the variable initializations. The rule we follow is that we
1195 // emit them in the order they appear in the array, except that if the
1196 // initialization expression for a variable V1 depends upon another
1197 // variable V2 then we initialize V1 after V2.
1200 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1202 if (var_inits
->empty())
1205 std::map
<Named_object
*, Var_init
*> var_to_init
;
1207 // A mapping from a variable initialization to a set of
1208 // variable initializations that depend on it.
1209 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1210 Init_deps init_deps
;
1211 bool init_loop
= false;
1213 // Compute all variable references.
1214 for (Var_inits::iterator pvar
= var_inits
->begin();
1215 pvar
!= var_inits
->end();
1218 Named_object
* var
= pvar
->var();
1219 var_to_init
[var
] = &*pvar
;
1221 Find_vars find_vars
;
1222 Expression
* init
= var
->var_value()->init();
1224 Expression::traverse(&init
, &find_vars
);
1225 if (var
->var_value()->has_pre_init())
1226 var
->var_value()->preinit()->traverse(&find_vars
);
1227 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1230 Expression
* dinit
= dep
->var_value()->init();
1232 Expression::traverse(&dinit
, &find_vars
);
1233 if (dep
->var_value()->has_pre_init())
1234 dep
->var_value()->preinit()->traverse(&find_vars
);
1236 for (Find_vars::const_iterator p
= find_vars
.begin();
1237 p
!= find_vars
.end();
1242 // Add dependencies to init_deps, and check for cycles.
1243 for (Var_inits::iterator pvar
= var_inits
->begin();
1244 pvar
!= var_inits
->end();
1247 Named_object
* var
= pvar
->var();
1249 const std::vector
<Named_object
*>* refs
= pvar
->refs();
1252 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1253 pdep
!= refs
->end();
1256 Named_object
* dep
= *pdep
;
1259 // This is a reference from a variable to itself, which
1260 // may indicate a loop. We only report an error if
1261 // there is an initializer and there is no dependency.
1262 // When there is no initializer, it means that the
1263 // preinitializer sets the variable, which will appear
1264 // to be a loop here.
1265 if (var
->var_value()->init() != NULL
1266 && gogo
->var_depends_on(var
->var_value()) == NULL
)
1267 go_error_at(var
->location(),
1268 ("initialization expression for %qs "
1269 "depends upon itself"),
1270 var
->message_name().c_str());
1275 Var_init
* dep_init
= var_to_init
[dep
];
1276 if (dep_init
== NULL
)
1278 // This is a dependency on some variable that doesn't
1279 // have an initializer, so for purposes of
1280 // initialization ordering this is irrelevant.
1284 init_deps
[*dep_init
].insert(&(*pvar
));
1285 pvar
->add_dependency();
1287 // Check for cycles.
1288 const std::vector
<Named_object
*>* deprefs
= dep_init
->refs();
1289 if (deprefs
== NULL
)
1291 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1293 pdepdep
!= deprefs
->end();
1296 if (*pdepdep
== var
)
1298 go_error_at(var
->location(),
1299 ("initialization expressions for %qs and "
1300 "%qs depend upon each other"),
1301 var
->message_name().c_str(),
1302 dep
->message_name().c_str());
1303 go_inform(dep
->location(), "%qs defined here",
1304 dep
->message_name().c_str());
1312 var_to_init
.clear();
1313 for (Var_inits::iterator pvar
= var_inits
->begin();
1314 pvar
!= var_inits
->end();
1318 // If there are no dependencies then the declaration order is sorted.
1319 if (!init_deps
.empty() && !init_loop
)
1321 // Otherwise, sort variable initializations by emitting all variables with
1322 // no dependencies in declaration order. VAR_INITS is already in
1323 // declaration order.
1325 while (!var_inits
->empty())
1327 Var_inits::iterator v1
;;
1328 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1330 if (v1
->dep_count() == 0)
1333 go_assert(v1
!= var_inits
->end());
1335 // V1 either has no dependencies or its dependencies have already
1336 // been emitted, add it to READY next. When V1 is emitted, remove
1337 // a dependency from each V that depends on V1.
1338 ready
.splice(ready
.end(), *var_inits
, v1
);
1340 Init_deps::iterator p1
= init_deps
.find(*v1
);
1341 if (p1
!= init_deps
.end())
1343 std::set
<Var_init
*> resolved
= p1
->second
;
1344 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1345 pv
!= resolved
.end();
1347 (*pv
)->remove_dependency();
1348 init_deps
.erase(p1
);
1351 var_inits
->swap(ready
);
1352 go_assert(init_deps
.empty());
1356 // Give an error if the initialization expression for VAR depends on
1357 // itself. We only check if INIT is not NULL and there is no
1358 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1359 // which we will interpret as a loop.
1362 Gogo::check_self_dep(Named_object
* var
)
1364 Expression
* init
= var
->var_value()->init();
1365 Block
* preinit
= var
->var_value()->preinit();
1366 Named_object
* dep
= this->var_depends_on(var
->var_value());
1369 && expression_requires(init
, preinit
, NULL
, var
))
1370 go_error_at(var
->location(),
1371 "initialization expression for %qs depends upon itself",
1372 var
->message_name().c_str());
1375 // Write out the global definitions.
1378 Gogo::write_globals()
1380 this->build_interface_method_tables();
1382 Bindings
* bindings
= this->current_bindings();
1384 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1385 p
!= bindings
->end_declarations();
1388 // If any function declarations needed a descriptor, make sure
1390 Named_object
* no
= p
->second
;
1391 if (no
->is_function_declaration())
1392 no
->func_declaration_value()->build_backend_descriptor(this);
1395 // Lists of globally declared types, variables, constants, and functions
1396 // that must be defined.
1397 std::vector
<Btype
*> type_decls
;
1398 std::vector
<Bvariable
*> var_decls
;
1399 std::vector
<Bexpression
*> const_decls
;
1400 std::vector
<Bfunction
*> func_decls
;
1402 // The init function declaration and associated Bfunction, if necessary.
1403 Named_object
* init_fndecl
= NULL
;
1404 Bfunction
* init_bfn
= NULL
;
1406 std::vector
<Bstatement
*> init_stmts
;
1407 std::vector
<Bstatement
*> var_init_stmts
;
1409 if (this->is_main_package())
1411 init_fndecl
= this->initialization_function_decl();
1412 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1413 this->init_imports(init_stmts
, init_bfn
);
1416 // A list of variable initializations.
1417 Var_inits var_inits
;
1419 // A list of variables which need to be registered with the garbage
1421 size_t count_definitions
= bindings
->size_definitions();
1422 std::vector
<Named_object
*> var_gc
;
1423 var_gc
.reserve(count_definitions
);
1425 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1426 p
!= bindings
->end_definitions();
1429 Named_object
* no
= *p
;
1430 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1432 // There is nothing to do for a package.
1433 if (no
->is_package())
1436 // There is nothing to do for an object which was imported from
1437 // a different package into the global scope.
1438 if (no
->package() != NULL
)
1441 // Skip blank named functions and constants.
1442 if ((no
->is_function() && no
->func_value()->is_sink())
1443 || (no
->is_const() && no
->const_value()->is_sink()))
1446 // There is nothing useful we can output for constants which
1447 // have ideal or non-integral type.
1450 Type
* type
= no
->const_value()->type();
1452 type
= no
->const_value()->expr()->type();
1453 if (type
->is_abstract() || !type
->is_numeric_type())
1457 if (!no
->is_variable())
1458 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1461 Variable
* var
= no
->var_value();
1462 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1463 var_decls
.push_back(bvar
);
1465 // Check for a sink variable, which may be used to run an
1466 // initializer purely for its side effects.
1467 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1469 Bstatement
* var_init_stmt
= NULL
;
1470 if (!var
->has_pre_init())
1472 // If the backend representation of the variable initializer is
1473 // constant, we can just set the initial value using
1474 // global_var_set_init instead of during the init() function.
1475 // The initializer is constant if it is the zero-value of the
1476 // variable's type or if the initial value is an immutable value
1477 // that is not copied to the heap.
1478 bool is_static_initializer
= false;
1479 if (var
->init() == NULL
)
1480 is_static_initializer
= true;
1483 Type
* var_type
= var
->type();
1484 Expression
* init
= var
->init();
1485 Expression
* init_cast
=
1486 Expression::make_cast(var_type
, init
, var
->location());
1487 is_static_initializer
= init_cast
->is_static_initializer();
1490 // Non-constant variable initializations might need to create
1491 // temporary variables, which will need the initialization
1492 // function as context.
1493 Named_object
* var_init_fn
;
1494 if (is_static_initializer
)
1498 if (init_fndecl
== NULL
)
1500 init_fndecl
= this->initialization_function_decl();
1501 Function
* func
= init_fndecl
->func_value();
1502 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1504 var_init_fn
= init_fndecl
;
1506 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1508 if (var_binit
== NULL
)
1510 else if (is_static_initializer
)
1512 if (expression_requires(var
->init(), NULL
,
1513 this->var_depends_on(var
), no
))
1514 go_error_at(no
->location(),
1515 "initialization expression for %qs depends "
1517 no
->message_name().c_str());
1518 this->backend()->global_variable_set_init(bvar
, var_binit
);
1522 this->backend()->expression_statement(init_bfn
, var_binit
);
1525 Location loc
= var
->location();
1526 Bexpression
* var_expr
=
1527 this->backend()->var_expression(bvar
, loc
);
1529 this->backend()->assignment_statement(init_bfn
, var_expr
,
1535 // We are going to create temporary variables which
1536 // means that we need an fndecl.
1537 if (init_fndecl
== NULL
)
1538 init_fndecl
= this->initialization_function_decl();
1540 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1541 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1544 if (var_init_stmt
!= NULL
)
1546 if (var
->init() == NULL
&& !var
->has_pre_init())
1547 var_init_stmts
.push_back(var_init_stmt
);
1549 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1551 else if (this->var_depends_on(var
) != NULL
)
1553 // This variable is initialized from something that is
1554 // not in its init or preinit. This variable needs to
1555 // participate in dependency analysis sorting, in case
1556 // some other variable depends on this one.
1557 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1558 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1559 Bstatement
* zero_stmt
=
1560 this->backend()->expression_statement(init_bfn
, zero
);
1561 var_inits
.push_back(Var_init(no
, zero_stmt
));
1564 // Collect a list of all global variables with pointers,
1565 // to register them for the garbage collector.
1566 if (!is_sink
&& var
->type()->has_pointer())
1568 // Avoid putting runtime.gcRoots itself on the list.
1569 if (this->compiling_runtime()
1570 && this->package_name() == "runtime"
1571 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1572 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1575 var_gc
.push_back(no
);
1580 // Output inline functions, which are in different packages.
1581 for (std::vector
<Named_object
*>::const_iterator p
=
1582 this->imported_inline_functions_
.begin();
1583 p
!= this->imported_inline_functions_
.end();
1585 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1587 // Register global variables with the garbage collector.
1588 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1590 // Simple variable initializations, after all variables are
1592 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1594 // Complete variable initializations, first sorting them into a
1596 if (!var_inits
.empty())
1598 sort_var_inits(this, &var_inits
);
1599 for (Var_inits::const_iterator p
= var_inits
.begin();
1600 p
!= var_inits
.end();
1602 init_stmts
.push_back(p
->init());
1605 // After all the variables are initialized, call the init
1606 // functions if there are any. Init functions take no arguments, so
1607 // we pass in EMPTY_ARGS to call them.
1608 std::vector
<Bexpression
*> empty_args
;
1609 for (std::vector
<Named_object
*>::const_iterator p
=
1610 this->init_functions_
.begin();
1611 p
!= this->init_functions_
.end();
1614 Location func_loc
= (*p
)->location();
1615 Function
* func
= (*p
)->func_value();
1616 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1617 Bexpression
* func_code
=
1618 this->backend()->function_code_expression(initfn
, func_loc
);
1619 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1622 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1623 init_stmts
.push_back(ist
);
1626 // Set up a magic function to do all the initialization actions.
1627 // This will be called if this package is imported.
1628 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1629 if (this->need_init_fn_
|| this->is_main_package())
1632 this->create_initialization_function(init_fndecl
, init_fncode
);
1633 if (init_fndecl
!= NULL
)
1634 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1637 // We should not have seen any new bindings created during the conversion.
1638 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1640 // Define all globally declared values.
1642 this->backend()->write_global_definitions(type_decls
, const_decls
,
1643 func_decls
, var_decls
);
1646 // Return the current block.
1649 Gogo::current_block()
1651 if (this->functions_
.empty())
1654 return this->functions_
.back().blocks
.back();
1657 // Look up a name in the current binding contour. If PFUNCTION is not
1658 // NULL, set it to the function in which the name is defined, or NULL
1659 // if the name is defined in global scope.
1662 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1664 if (pfunction
!= NULL
)
1667 if (Gogo::is_sink_name(name
))
1668 return Named_object::make_sink();
1670 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1671 p
!= this->functions_
.rend();
1674 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1677 if (pfunction
!= NULL
)
1678 *pfunction
= p
->function
;
1683 if (this->package_
!= NULL
)
1685 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1688 if (ret
->package() != NULL
)
1690 std::string dot_alias
= "." + ret
->package()->package_name();
1691 ret
->package()->note_usage(dot_alias
);
1697 // We do not look in the global namespace. If we did, the global
1698 // namespace would effectively hide names which were defined in
1699 // package scope which we have not yet seen. Instead,
1700 // define_global_names is called after parsing is over to connect
1701 // undefined names at package scope with names defined at global
1707 // Look up a name in the current block, without searching enclosing
1711 Gogo::lookup_in_block(const std::string
& name
) const
1713 go_assert(!this->functions_
.empty());
1714 go_assert(!this->functions_
.back().blocks
.empty());
1715 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1718 // Look up a name in the global namespace.
1721 Gogo::lookup_global(const char* name
) const
1723 return this->globals_
->lookup(name
);
1726 // Add an imported package.
1729 Gogo::add_imported_package(const std::string
& real_name
,
1730 const std::string
& alias_arg
,
1731 bool is_alias_exported
,
1732 const std::string
& pkgpath
,
1733 const std::string
& pkgpath_symbol
,
1735 bool* padd_to_globals
)
1737 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1738 ret
->set_package_name(real_name
, location
);
1740 *padd_to_globals
= false;
1742 if (alias_arg
== "_")
1744 else if (alias_arg
== ".")
1746 *padd_to_globals
= true;
1747 std::string dot_alias
= "." + real_name
;
1748 ret
->add_alias(dot_alias
, location
);
1752 std::string alias
= alias_arg
;
1756 is_alias_exported
= Lex::is_exported_name(alias
);
1758 ret
->add_alias(alias
, location
);
1759 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1760 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1761 if (!no
->is_package())
1768 // Register a package. This package may or may not be imported. This
1769 // returns the Package structure for the package, creating if it
1770 // necessary. LOCATION is the location of the import statement that
1771 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1772 // for names in the package; it may be the empty string, in which case
1773 // we either get it later or make a guess when we need it.
1776 Gogo::register_package(const std::string
& pkgpath
,
1777 const std::string
& pkgpath_symbol
, Location location
)
1779 Package
* package
= NULL
;
1780 std::pair
<Packages::iterator
, bool> ins
=
1781 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1784 // We have seen this package name before.
1785 package
= ins
.first
->second
;
1786 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1787 if (!pkgpath_symbol
.empty())
1788 package
->set_pkgpath_symbol(pkgpath_symbol
);
1789 if (Linemap::is_unknown_location(package
->location()))
1790 package
->set_location(location
);
1794 // First time we have seen this package name.
1795 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1796 go_assert(ins
.first
->second
== NULL
);
1797 ins
.first
->second
= package
;
1803 // Return the pkgpath symbol for a package, given the pkgpath.
1806 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1808 Packages::iterator p
= this->packages_
.find(pkgpath
);
1809 go_assert(p
!= this->packages_
.end());
1810 return p
->second
->pkgpath_symbol();
1813 // Start compiling a function.
1816 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1817 bool add_method_to_type
, Location location
)
1819 bool at_top_level
= this->functions_
.empty();
1821 Block
* block
= new Block(NULL
, location
);
1823 Named_object
* enclosing
= (at_top_level
1825 : this->functions_
.back().function
);
1827 Function
* function
= new Function(type
, enclosing
, block
, location
);
1829 if (type
->is_method())
1831 const Typed_identifier
* receiver
= type
->receiver();
1832 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1833 true, true, location
);
1834 std::string rname
= receiver
->name();
1835 unsigned rcounter
= 0;
1837 // We need to give a nameless receiver parameter a synthesized name to
1838 // avoid having it clash with some other nameless param. FIXME.
1839 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
1841 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1844 const Typed_identifier_list
* parameters
= type
->parameters();
1845 bool is_varargs
= type
->is_varargs();
1846 unsigned pcounter
= 0;
1847 if (parameters
!= NULL
)
1849 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1850 p
!= parameters
->end();
1853 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1855 if (is_varargs
&& p
+ 1 == parameters
->end())
1856 param
->set_is_varargs_parameter();
1858 std::string pname
= p
->name();
1860 // We need to give each nameless parameter a non-empty name to avoid
1861 // having it clash with some other nameless param. FIXME.
1862 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
1864 block
->bindings()->add_variable(pname
, NULL
, param
);
1868 function
->create_result_variables(this);
1870 const std::string
* pname
;
1871 std::string nested_name
;
1872 bool is_init
= false;
1873 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1875 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1876 || (type
->results() != NULL
&& !type
->results()->empty()))
1877 go_error_at(location
,
1878 "func init must have no arguments and no return values");
1879 // There can be multiple "init" functions, so give them each a
1881 nested_name
= this->init_function_name();
1882 pname
= &nested_name
;
1885 else if (!name
.empty())
1889 // Invent a name for a nested function.
1890 nested_name
= this->nested_function_name(enclosing
);
1891 pname
= &nested_name
;
1895 if (Gogo::is_sink_name(*pname
))
1897 std::string
sname(this->sink_function_name());
1898 ret
= Named_object::make_function(sname
, NULL
, function
);
1899 ret
->func_value()->set_is_sink();
1901 if (!type
->is_method())
1902 ret
= this->package_
->bindings()->add_named_object(ret
);
1903 else if (add_method_to_type
)
1905 // We should report errors even for sink methods.
1906 Type
* rtype
= type
->receiver()->type();
1907 // Avoid points_to and deref to avoid getting an error if
1908 // the type is not yet defined.
1909 if (rtype
->classification() == Type::TYPE_POINTER
)
1910 rtype
= rtype
->points_to();
1911 while (rtype
->named_type() != NULL
1912 && rtype
->named_type()->is_alias())
1913 rtype
= rtype
->named_type()->real_type()->forwarded();
1914 if (rtype
->is_error_type())
1916 else if (rtype
->named_type() != NULL
)
1918 if (rtype
->named_type()->named_object()->package() != NULL
)
1919 go_error_at(type
->receiver()->location(),
1920 "may not define methods on non-local type");
1922 else if (rtype
->forward_declaration_type() != NULL
)
1924 // Go ahead and add the method in case we need to report
1925 // an error when we see the definition.
1926 rtype
->forward_declaration_type()->add_existing_method(ret
);
1929 go_error_at(type
->receiver()->location(),
1930 ("invalid receiver type "
1931 "(receiver must be a named type)"));
1934 else if (!type
->is_method())
1936 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1937 if (!ret
->is_function() || ret
->func_value() != function
)
1939 // Redefinition error. Invent a name to avoid knockon
1941 std::string
rname(this->redefined_function_name());
1942 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
1947 if (!add_method_to_type
)
1948 ret
= Named_object::make_function(name
, NULL
, function
);
1951 go_assert(at_top_level
);
1952 Type
* rtype
= type
->receiver()->type();
1954 while (rtype
->named_type() != NULL
1955 && rtype
->named_type()->is_alias())
1956 rtype
= rtype
->named_type()->real_type()->forwarded();
1958 // We want to look through the pointer created by the
1959 // parser, without getting an error if the type is not yet
1961 if (rtype
->classification() == Type::TYPE_POINTER
)
1962 rtype
= rtype
->points_to();
1964 while (rtype
->named_type() != NULL
1965 && rtype
->named_type()->is_alias())
1966 rtype
= rtype
->named_type()->real_type()->forwarded();
1968 if (rtype
->is_error_type())
1969 ret
= Named_object::make_function(name
, NULL
, function
);
1970 else if (rtype
->named_type() != NULL
)
1972 if (rtype
->named_type()->named_object()->package() != NULL
)
1974 go_error_at(type
->receiver()->location(),
1975 "may not define methods on non-local type");
1976 ret
= Named_object::make_function(name
, NULL
, function
);
1980 ret
= rtype
->named_type()->add_method(name
, function
);
1981 if (!ret
->is_function())
1983 // Redefinition error.
1984 ret
= Named_object::make_function(name
, NULL
, function
);
1988 else if (rtype
->forward_declaration_type() != NULL
)
1990 Named_object
* type_no
=
1991 rtype
->forward_declaration_type()->named_object();
1992 if (type_no
->is_unknown())
1994 // If we are seeing methods it really must be a
1995 // type. Declare it as such. An alternative would
1996 // be to support lists of methods for unknown
1997 // expressions. Either way the error messages if
1998 // this is not a type are going to get confusing.
1999 Named_object
* declared
=
2000 this->declare_package_type(type_no
->name(),
2001 type_no
->location());
2003 == type_no
->unknown_value()->real_named_object());
2005 ret
= rtype
->forward_declaration_type()->add_method(name
,
2010 go_error_at(type
->receiver()->location(),
2011 ("invalid receiver type (receiver must "
2012 "be a named type)"));
2013 ret
= Named_object::make_function(name
, NULL
, function
);
2016 this->package_
->bindings()->add_method(ret
);
2019 this->functions_
.resize(this->functions_
.size() + 1);
2020 Open_function
& of(this->functions_
.back());
2022 of
.blocks
.push_back(block
);
2026 this->init_functions_
.push_back(ret
);
2027 this->need_init_fn_
= true;
2033 // Finish compiling a function.
2036 Gogo::finish_function(Location location
)
2038 this->finish_block(location
);
2039 go_assert(this->functions_
.back().blocks
.empty());
2040 this->functions_
.pop_back();
2043 // Return the current function.
2046 Gogo::current_function() const
2048 go_assert(!this->functions_
.empty());
2049 return this->functions_
.back().function
;
2052 // Start a new block.
2055 Gogo::start_block(Location location
)
2057 go_assert(!this->functions_
.empty());
2058 Block
* block
= new Block(this->current_block(), location
);
2059 this->functions_
.back().blocks
.push_back(block
);
2065 Gogo::finish_block(Location location
)
2067 go_assert(!this->functions_
.empty());
2068 go_assert(!this->functions_
.back().blocks
.empty());
2069 Block
* block
= this->functions_
.back().blocks
.back();
2070 this->functions_
.back().blocks
.pop_back();
2071 block
->set_end_location(location
);
2075 // Add an erroneous name.
2078 Gogo::add_erroneous_name(const std::string
& name
)
2080 return this->package_
->bindings()->add_erroneous_name(name
);
2083 // Add an unknown name.
2086 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2088 return this->package_
->bindings()->add_unknown_name(name
, location
);
2091 // Declare a function.
2094 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2097 if (!type
->is_method())
2098 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2102 // We don't bother to add this to the list of global
2104 Type
* rtype
= type
->receiver()->type();
2106 while (rtype
->named_type() != NULL
2107 && rtype
->named_type()->is_alias())
2108 rtype
= rtype
->named_type()->real_type()->forwarded();
2110 // We want to look through the pointer created by the
2111 // parser, without getting an error if the type is not yet
2113 if (rtype
->classification() == Type::TYPE_POINTER
)
2114 rtype
= rtype
->points_to();
2116 while (rtype
->named_type() != NULL
2117 && rtype
->named_type()->is_alias())
2118 rtype
= rtype
->named_type()->real_type()->forwarded();
2120 if (rtype
->is_error_type())
2122 else if (rtype
->named_type() != NULL
)
2123 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2125 else if (rtype
->forward_declaration_type() != NULL
)
2127 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2128 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2132 go_error_at(type
->receiver()->location(),
2133 "invalid receiver type (receiver must be a named type)");
2134 return Named_object::make_erroneous_name(name
);
2139 // Add a label definition.
2142 Gogo::add_label_definition(const std::string
& label_name
,
2145 go_assert(!this->functions_
.empty());
2146 Function
* func
= this->functions_
.back().function
->func_value();
2147 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2148 this->add_statement(Statement::make_label_statement(label
, location
));
2152 // Add a label reference.
2155 Gogo::add_label_reference(const std::string
& label_name
,
2156 Location location
, bool issue_goto_errors
)
2158 go_assert(!this->functions_
.empty());
2159 Function
* func
= this->functions_
.back().function
->func_value();
2160 return func
->add_label_reference(this, label_name
, location
,
2164 // Return the current binding state.
2167 Gogo::bindings_snapshot(Location location
)
2169 return new Bindings_snapshot(this->current_block(), location
);
2175 Gogo::add_statement(Statement
* statement
)
2177 go_assert(!this->functions_
.empty()
2178 && !this->functions_
.back().blocks
.empty());
2179 this->functions_
.back().blocks
.back()->add_statement(statement
);
2185 Gogo::add_block(Block
* block
, Location location
)
2187 go_assert(!this->functions_
.empty()
2188 && !this->functions_
.back().blocks
.empty());
2189 Statement
* statement
= Statement::make_block_statement(block
, location
);
2190 this->functions_
.back().blocks
.back()->add_statement(statement
);
2196 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2199 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2205 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2207 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2209 if (!this->in_global_scope() && no
->is_type())
2211 Named_object
* f
= this->functions_
.back().function
;
2213 if (f
->is_function())
2214 index
= f
->func_value()->new_local_type_index();
2217 no
->type_value()->set_in_function(f
, index
);
2221 // Add a named type.
2224 Gogo::add_named_type(Named_type
* type
)
2226 go_assert(this->in_global_scope());
2227 this->current_bindings()->add_named_type(type
);
2233 Gogo::declare_type(const std::string
& name
, Location location
)
2235 Bindings
* bindings
= this->current_bindings();
2236 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2237 if (!this->in_global_scope() && no
->is_type_declaration())
2239 Named_object
* f
= this->functions_
.back().function
;
2241 if (f
->is_function())
2242 index
= f
->func_value()->new_local_type_index();
2245 no
->type_declaration_value()->set_in_function(f
, index
);
2250 // Declare a type at the package level.
2253 Gogo::declare_package_type(const std::string
& name
, Location location
)
2255 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2258 // Declare a function at the package level.
2261 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2264 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2268 // Add a function declaration to the list of functions we may want to
2272 Gogo::add_imported_inlinable_function(Named_object
* no
)
2274 go_assert(no
->is_function_declaration());
2275 Function_declaration
* fd
= no
->func_declaration_value();
2276 if (fd
->is_on_inlinable_list())
2278 this->imported_inlinable_functions_
.push_back(no
);
2279 fd
->set_is_on_inlinable_list();
2282 // Define a type which was already declared.
2285 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2287 this->current_bindings()->define_type(no
, type
);
2293 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2295 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2298 // In a function the middle-end wants to see a DECL_EXPR node.
2300 && no
->is_variable()
2301 && !no
->var_value()->is_parameter()
2302 && !this->functions_
.empty())
2303 this->add_statement(Statement::make_variable_declaration(no
));
2309 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2311 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2314 go_assert(strlen(tag
) < 10);
2315 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2322 // Add a sink--a reference to the blank identifier _.
2327 return Named_object::make_sink();
2330 // Add a named object for a dot import.
2333 Gogo::add_dot_import_object(Named_object
* no
)
2335 // If the name already exists, then it was defined in some file seen
2336 // earlier. If the earlier name is just a declaration, don't add
2337 // this name, because that will cause the previous declaration to
2338 // merge to this imported name, which should not happen. Just add
2339 // this name to the list of file block names to get appropriate
2340 // errors if we see a later definition.
2341 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2342 if (e
!= NULL
&& e
->package() == NULL
)
2344 if (e
->is_unknown())
2346 if (e
->package() == NULL
2347 && (e
->is_type_declaration()
2348 || e
->is_function_declaration()
2349 || e
->is_unknown()))
2351 this->add_file_block_name(no
->name(), no
->location());
2356 this->current_bindings()->add_named_object(no
);
2359 // Add a linkname. This implements the go:linkname compiler directive.
2360 // We only support this for functions and function declarations.
2363 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2364 const std::string
& ext_name
, Location loc
)
2367 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2370 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2371 else if (no
->is_function())
2372 no
->func_value()->set_asm_name(ext_name
);
2373 else if (no
->is_function_declaration())
2374 no
->func_declaration_value()->set_asm_name(ext_name
);
2377 ("%s is not a function; "
2378 "//go:linkname is only supported for functions"),
2382 // Mark all local variables used. This is used when some types of
2383 // parse error occur.
2386 Gogo::mark_locals_used()
2388 for (Open_functions::iterator pf
= this->functions_
.begin();
2389 pf
!= this->functions_
.end();
2392 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2393 pb
!= pf
->blocks
.end();
2395 (*pb
)->bindings()->mark_locals_used();
2399 // Record that we've seen an interface type.
2402 Gogo::record_interface_type(Interface_type
* itype
)
2404 this->interface_types_
.push_back(itype
);
2407 // Define the global names. We do this only after parsing all the
2408 // input files, because the program might define the global names
2412 Gogo::define_global_names()
2414 if (this->is_main_package())
2416 // Every Go program has to import the runtime package, so that
2417 // it is properly initialized.
2418 this->import_package("runtime", "_", false, false,
2419 Linemap::predeclared_location());
2422 for (Bindings::const_declarations_iterator p
=
2423 this->globals_
->begin_declarations();
2424 p
!= this->globals_
->end_declarations();
2427 Named_object
* global_no
= p
->second
;
2428 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2429 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2433 if (no
->is_type_declaration())
2435 if (global_no
->is_type())
2437 if (no
->type_declaration_value()->has_methods())
2439 for (std::vector
<Named_object
*>::const_iterator p
=
2440 no
->type_declaration_value()->methods()->begin();
2441 p
!= no
->type_declaration_value()->methods()->end();
2443 go_error_at((*p
)->location(),
2444 "may not define methods on non-local type");
2446 no
->set_type_value(global_no
->type_value());
2450 go_error_at(no
->location(), "expected type");
2451 Type
* errtype
= Type::make_error_type();
2453 Named_object::make_type("erroneous_type", NULL
, errtype
,
2454 Linemap::predeclared_location());
2455 no
->set_type_value(err
->type_value());
2458 else if (no
->is_unknown())
2459 no
->unknown_value()->set_real_named_object(global_no
);
2462 // Give an error if any name is defined in both the package block
2463 // and the file block. For example, this can happen if one file
2464 // imports "fmt" and another file defines a global variable fmt.
2465 for (Bindings::const_declarations_iterator p
=
2466 this->package_
->bindings()->begin_declarations();
2467 p
!= this->package_
->bindings()->end_declarations();
2470 if (p
->second
->is_unknown()
2471 && p
->second
->unknown_value()->real_named_object() == NULL
)
2473 // No point in warning about an undefined name, as we will
2474 // get other errors later anyhow.
2477 File_block_names::const_iterator pf
=
2478 this->file_block_names_
.find(p
->second
->name());
2479 if (pf
!= this->file_block_names_
.end())
2481 std::string n
= p
->second
->message_name();
2482 go_error_at(p
->second
->location(),
2483 "%qs defined as both imported name and global name",
2485 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2488 // No package scope identifier may be named "init".
2489 if (!p
->second
->is_function()
2490 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2492 go_error_at(p
->second
->location(),
2493 "cannot declare init - must be func");
2498 // Clear out names in file scope.
2501 Gogo::clear_file_scope()
2503 this->package_
->bindings()->clear_file_scope(this);
2505 // Warn about packages which were imported but not used.
2506 bool quiet
= saw_errors();
2507 for (Packages::iterator p
= this->packages_
.begin();
2508 p
!= this->packages_
.end();
2511 Package
* package
= p
->second
;
2512 if (package
!= this->package_
&& !quiet
)
2514 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2515 p1
!= package
->aliases().end();
2518 if (!p1
->second
->used())
2520 // Give a more refined error message if the alias name is known.
2521 std::string pkg_name
= package
->package_name();
2522 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2524 go_error_at(p1
->second
->location(),
2525 "imported and not used: %s as %s",
2526 Gogo::message_name(pkg_name
).c_str(),
2527 Gogo::message_name(p1
->first
).c_str());
2530 go_error_at(p1
->second
->location(),
2531 "imported and not used: %s",
2532 Gogo::message_name(pkg_name
).c_str());
2536 package
->clear_used();
2539 this->current_file_imported_unsafe_
= false;
2542 // Queue up a type specific function for later writing. These are
2543 // written out in write_specific_type_functions, called after the
2544 // parse tree is lowered.
2547 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
, int64_t size
,
2548 const std::string
& hash_name
,
2549 Function_type
* hash_fntype
,
2550 const std::string
& equal_name
,
2551 Function_type
* equal_fntype
)
2553 go_assert(!this->specific_type_functions_are_written_
);
2554 go_assert(!this->in_global_scope());
2555 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2560 this->specific_type_functions_
.push_back(tsf
);
2563 // Look for types which need specific hash or equality functions.
2565 class Specific_type_functions
: public Traverse
2568 Specific_type_functions(Gogo
* gogo
)
2569 : Traverse(traverse_types
),
2581 Specific_type_functions::type(Type
* t
)
2583 Named_object
* hash_fn
;
2584 Named_object
* equal_fn
;
2585 switch (t
->classification())
2587 case Type::TYPE_NAMED
:
2589 Named_type
* nt
= t
->named_type();
2591 return TRAVERSE_CONTINUE
;
2592 if (t
->needs_specific_type_functions(this->gogo_
))
2593 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2595 // If this is a struct type, we don't want to make functions
2596 // for the unnamed struct.
2597 Type
* rt
= nt
->real_type();
2598 if (rt
->struct_type() == NULL
)
2600 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2601 return TRAVERSE_EXIT
;
2605 // If this type is defined in another package, then we don't
2606 // need to worry about the unexported fields.
2607 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2608 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2609 for (Struct_field_list::const_iterator p
= fields
->begin();
2613 if (is_defined_elsewhere
2614 && Gogo::is_hidden_name(p
->field_name()))
2616 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2617 return TRAVERSE_EXIT
;
2621 return TRAVERSE_SKIP_COMPONENTS
;
2624 case Type::TYPE_STRUCT
:
2625 case Type::TYPE_ARRAY
:
2626 if (t
->needs_specific_type_functions(this->gogo_
))
2627 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2634 return TRAVERSE_CONTINUE
;
2637 // Write out type specific functions.
2640 Gogo::write_specific_type_functions()
2642 Specific_type_functions
stf(this);
2643 this->traverse(&stf
);
2645 while (!this->specific_type_functions_
.empty())
2647 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2648 this->specific_type_functions_
.pop_back();
2649 tsf
->type
->write_specific_type_functions(this, tsf
->name
, tsf
->size
,
2656 this->specific_type_functions_are_written_
= true;
2659 // Traverse the tree.
2662 Gogo::traverse(Traverse
* traverse
)
2664 // Traverse the current package first for consistency. The other
2665 // packages will only contain imported types, constants, and
2667 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2669 for (Packages::const_iterator p
= this->packages_
.begin();
2670 p
!= this->packages_
.end();
2673 if (p
->second
!= this->package_
)
2675 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2681 // Add a type to verify. This is used for types of sink variables, in
2682 // order to give appropriate error messages.
2685 Gogo::add_type_to_verify(Type
* type
)
2687 this->verify_types_
.push_back(type
);
2690 // Traversal class used to verify types.
2692 class Verify_types
: public Traverse
2696 : Traverse(traverse_types
)
2703 // Verify that a type is correct.
2706 Verify_types::type(Type
* t
)
2709 return TRAVERSE_SKIP_COMPONENTS
;
2710 return TRAVERSE_CONTINUE
;
2713 // Verify that all types are correct.
2716 Gogo::verify_types()
2718 Verify_types traverse
;
2719 this->traverse(&traverse
);
2721 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2722 p
!= this->verify_types_
.end();
2725 this->verify_types_
.clear();
2728 // Traversal class used to lower parse tree.
2730 class Lower_parse_tree
: public Traverse
2733 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2734 : Traverse(traverse_variables
2735 | traverse_constants
2736 | traverse_functions
2737 | traverse_statements
2738 | traverse_expressions
),
2739 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2743 set_inserter(const Statement_inserter
* inserter
)
2744 { this->inserter_
= *inserter
; }
2747 variable(Named_object
*);
2750 constant(Named_object
*, bool);
2753 function(Named_object
*);
2756 statement(Block
*, size_t* pindex
, Statement
*);
2759 expression(Expression
**);
2764 // The function we are traversing.
2765 Named_object
* function_
;
2766 // Value to use for the predeclared constant iota.
2768 // Current statement inserter for use by expressions.
2769 Statement_inserter inserter_
;
2775 Lower_parse_tree::variable(Named_object
* no
)
2777 if (!no
->is_variable())
2778 return TRAVERSE_CONTINUE
;
2780 if (no
->is_variable() && no
->var_value()->is_global())
2782 // Global variables can have loops in their initialization
2783 // expressions. This is handled in lower_init_expression.
2784 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2786 return TRAVERSE_CONTINUE
;
2789 // This is a local variable. We are going to return
2790 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2791 // initialization expression when we reach the variable declaration
2792 // statement. However, that means that we need to traverse the type
2794 if (no
->var_value()->has_type())
2796 Type
* type
= no
->var_value()->type();
2799 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2800 return TRAVERSE_EXIT
;
2803 go_assert(!no
->var_value()->has_pre_init());
2805 return TRAVERSE_SKIP_COMPONENTS
;
2808 // Lower constants. We handle constants specially so that we can set
2809 // the right value for the predeclared constant iota. This works in
2810 // conjunction with the way we lower Const_expression objects.
2813 Lower_parse_tree::constant(Named_object
* no
, bool)
2815 Named_constant
* nc
= no
->const_value();
2817 // Don't get into trouble if the constant's initializer expression
2818 // refers to the constant itself.
2820 return TRAVERSE_CONTINUE
;
2823 go_assert(this->iota_value_
== -1);
2824 this->iota_value_
= nc
->iota_value();
2825 nc
->traverse_expression(this);
2826 this->iota_value_
= -1;
2828 nc
->clear_lowering();
2830 // We will traverse the expression a second time, but that will be
2833 return TRAVERSE_CONTINUE
;
2836 // Lower the body of a function, and set the closure type. Record the
2837 // function while lowering it, so that we can pass it down when
2838 // lowering an expression.
2841 Lower_parse_tree::function(Named_object
* no
)
2843 no
->func_value()->set_closure_type();
2845 go_assert(this->function_
== NULL
);
2846 this->function_
= no
;
2847 int t
= no
->func_value()->traverse(this);
2848 this->function_
= NULL
;
2850 if (t
== TRAVERSE_EXIT
)
2852 return TRAVERSE_SKIP_COMPONENTS
;
2855 // Lower statement parse trees.
2858 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2860 // Because we explicitly traverse the statement's contents
2861 // ourselves, we want to skip block statements here. There is
2862 // nothing to lower in a block statement.
2863 if (sorig
->is_block_statement())
2864 return TRAVERSE_CONTINUE
;
2866 Statement_inserter
hold_inserter(this->inserter_
);
2867 this->inserter_
= Statement_inserter(block
, pindex
);
2869 // Lower the expressions first.
2870 int t
= sorig
->traverse_contents(this);
2871 if (t
== TRAVERSE_EXIT
)
2873 this->inserter_
= hold_inserter
;
2877 // Keep lowering until nothing changes.
2878 Statement
* s
= sorig
;
2881 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2886 t
= s
->traverse_contents(this);
2887 if (t
== TRAVERSE_EXIT
)
2889 this->inserter_
= hold_inserter
;
2895 block
->replace_statement(*pindex
, s
);
2897 this->inserter_
= hold_inserter
;
2898 return TRAVERSE_SKIP_COMPONENTS
;
2901 // Lower expression parse trees.
2904 Lower_parse_tree::expression(Expression
** pexpr
)
2906 // We have to lower all subexpressions first, so that we can get
2907 // their type if necessary. This is awkward, because we don't have
2908 // a postorder traversal pass.
2909 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2910 return TRAVERSE_EXIT
;
2911 // Keep lowering until nothing changes.
2914 Expression
* e
= *pexpr
;
2915 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2916 &this->inserter_
, this->iota_value_
);
2919 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2920 return TRAVERSE_EXIT
;
2924 // Lower the type of this expression before the parent looks at it,
2925 // in case the type contains an array that has expressions in its
2926 // length. Skip an Unknown_expression, as at this point that means
2927 // a composite literal key that does not have a type.
2928 if ((*pexpr
)->unknown_expression() == NULL
)
2929 Type::traverse((*pexpr
)->type(), this);
2931 return TRAVERSE_SKIP_COMPONENTS
;
2934 // Lower the parse tree. This is called after the parse is complete,
2935 // when all names should be resolved.
2938 Gogo::lower_parse_tree()
2940 Lower_parse_tree
lower_parse_tree(this, NULL
);
2941 this->traverse(&lower_parse_tree
);
2943 // If we found any functions defined in other packages that are
2944 // inlinables, import their bodies and turn them into functions.
2946 // Note that as we import inlinable functions we may find more
2947 // inlinable functions, so don't use an iterator.
2948 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
2950 Named_object
* no
= this->imported_inlinable_functions_
[i
];
2951 no
->func_declaration_value()->import_function_body(this, no
);
2954 // There might be type definitions that involve expressions such as the
2955 // array length. Make sure to lower these expressions as well. Otherwise,
2956 // errors hidden within a type can introduce unexpected errors into later
2958 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2959 p
!= this->verify_types_
.end();
2961 Type::traverse(*p
, &lower_parse_tree
);
2967 Gogo::lower_block(Named_object
* function
, Block
* block
)
2969 Lower_parse_tree
lower_parse_tree(this, function
);
2970 block
->traverse(&lower_parse_tree
);
2973 // Lower an expression. INSERTER may be NULL, in which case the
2974 // expression had better not need to create any temporaries.
2977 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2980 Lower_parse_tree
lower_parse_tree(this, function
);
2981 if (inserter
!= NULL
)
2982 lower_parse_tree
.set_inserter(inserter
);
2983 lower_parse_tree
.expression(pexpr
);
2986 // Lower a constant. This is called when lowering a reference to a
2987 // constant. We have to make sure that the constant has already been
2991 Gogo::lower_constant(Named_object
* no
)
2993 go_assert(no
->is_const());
2994 Lower_parse_tree
lower(this, NULL
);
2995 lower
.constant(no
, false);
2998 // Traverse the tree to create function descriptors as needed.
3000 class Create_function_descriptors
: public Traverse
3003 Create_function_descriptors(Gogo
* gogo
)
3004 : Traverse(traverse_functions
| traverse_expressions
),
3009 function(Named_object
*);
3012 expression(Expression
**);
3018 // Create a descriptor for every top-level exported function.
3021 Create_function_descriptors::function(Named_object
* no
)
3023 if (no
->is_function()
3024 && no
->func_value()->enclosing() == NULL
3025 && !no
->func_value()->is_method()
3026 && !Gogo::is_hidden_name(no
->name())
3027 && !Gogo::is_thunk(no
))
3028 no
->func_value()->descriptor(this->gogo_
, no
);
3030 return TRAVERSE_CONTINUE
;
3033 // If we see a function referenced in any way other than calling it,
3034 // create a descriptor for it.
3037 Create_function_descriptors::expression(Expression
** pexpr
)
3039 Expression
* expr
= *pexpr
;
3041 Func_expression
* fe
= expr
->func_expression();
3044 // We would not get here for a call to this function, so this is
3045 // a reference to a function other than calling it. We need a
3047 if (fe
->closure() != NULL
)
3048 return TRAVERSE_CONTINUE
;
3049 Named_object
* no
= fe
->named_object();
3050 if (no
->is_function() && !no
->func_value()->is_method())
3051 no
->func_value()->descriptor(this->gogo_
, no
);
3052 else if (no
->is_function_declaration()
3053 && !no
->func_declaration_value()->type()->is_method()
3054 && !Linemap::is_predeclared_location(no
->location()))
3055 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3056 return TRAVERSE_CONTINUE
;
3059 Bound_method_expression
* bme
= expr
->bound_method_expression();
3062 // We would not get here for a call to this method, so this is a
3063 // method value. We need to create a thunk.
3064 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3066 return TRAVERSE_CONTINUE
;
3069 Interface_field_reference_expression
* ifre
=
3070 expr
->interface_field_reference_expression();
3073 // We would not get here for a call to this interface method, so
3074 // this is a method value. We need to create a thunk.
3075 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3077 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3079 return TRAVERSE_CONTINUE
;
3082 Call_expression
* ce
= expr
->call_expression();
3085 Expression
* fn
= ce
->fn();
3086 if (fn
->func_expression() != NULL
3087 || fn
->bound_method_expression() != NULL
3088 || fn
->interface_field_reference_expression() != NULL
)
3090 // Traverse the arguments but not the function.
3091 Expression_list
* args
= ce
->args();
3094 if (args
->traverse(this) == TRAVERSE_EXIT
)
3095 return TRAVERSE_EXIT
;
3097 return TRAVERSE_SKIP_COMPONENTS
;
3101 return TRAVERSE_CONTINUE
;
3104 // Create function descriptors as needed. We need a function
3105 // descriptor for all exported functions and for all functions that
3106 // are referenced without being called.
3109 Gogo::create_function_descriptors()
3111 // Create a function descriptor for any exported function that is
3112 // declared in this package. This is so that we have a descriptor
3113 // for functions written in assembly. Gather the descriptors first
3114 // so that we don't add declarations while looping over them.
3115 std::vector
<Named_object
*> fndecls
;
3116 Bindings
* b
= this->package_
->bindings();
3117 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3118 p
!= b
->end_declarations();
3121 Named_object
* no
= p
->second
;
3122 if (no
->is_function_declaration()
3123 && !no
->func_declaration_value()->type()->is_method()
3124 && !Linemap::is_predeclared_location(no
->location())
3125 && !Gogo::is_hidden_name(no
->name()))
3126 fndecls
.push_back(no
);
3128 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3131 (*p
)->func_declaration_value()->descriptor(this, *p
);
3134 Create_function_descriptors
cfd(this);
3135 this->traverse(&cfd
);
3138 // Look for interface types to finalize methods of inherited
3141 class Finalize_methods
: public Traverse
3144 Finalize_methods(Gogo
* gogo
)
3145 : Traverse(traverse_types
),
3156 // Finalize the methods of an interface type.
3159 Finalize_methods::type(Type
* t
)
3161 // Check the classification so that we don't finalize the methods
3162 // twice for a named interface type.
3163 switch (t
->classification())
3165 case Type::TYPE_INTERFACE
:
3166 t
->interface_type()->finalize_methods();
3169 case Type::TYPE_NAMED
:
3171 Named_type
* nt
= t
->named_type();
3172 Type
* rt
= nt
->real_type();
3173 if (rt
->classification() != Type::TYPE_STRUCT
)
3175 // Finalize the methods of the real type first.
3176 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3177 return TRAVERSE_EXIT
;
3179 // Finalize the methods of this type.
3180 nt
->finalize_methods(this->gogo_
);
3184 // We don't want to finalize the methods of a named struct
3185 // type, as the methods should be attached to the named
3186 // type, not the struct type. We just want to finalize
3189 // It is possible that a field type refers indirectly to
3190 // this type, such as via a field with function type with
3191 // an argument or result whose type is this type. To
3192 // avoid the cycle, first finalize the methods of any
3193 // embedded types, which are the only types we need to
3194 // know to finalize the methods of this type.
3195 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3198 for (Struct_field_list::const_iterator pf
= fields
->begin();
3199 pf
!= fields
->end();
3202 if (pf
->is_anonymous())
3204 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3205 return TRAVERSE_EXIT
;
3210 // Finalize the methods of this type.
3211 nt
->finalize_methods(this->gogo_
);
3213 // Finalize all the struct fields.
3214 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3215 return TRAVERSE_EXIT
;
3218 // If this type is defined in a different package, then finalize the
3219 // types of all the methods, since we won't see them otherwise.
3220 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3222 const Methods
* methods
= nt
->methods();
3223 for (Methods::const_iterator p
= methods
->begin();
3224 p
!= methods
->end();
3227 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3228 return TRAVERSE_EXIT
;
3232 // Finalize the types of all methods that are declared but not
3233 // defined, since we won't see the declarations otherwise.
3234 if (nt
->named_object()->package() == NULL
3235 && nt
->local_methods() != NULL
)
3237 const Bindings
* methods
= nt
->local_methods();
3238 for (Bindings::const_declarations_iterator p
=
3239 methods
->begin_declarations();
3240 p
!= methods
->end_declarations();
3243 if (p
->second
->is_function_declaration())
3245 Type
* mt
= p
->second
->func_declaration_value()->type();
3246 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3247 return TRAVERSE_EXIT
;
3252 return TRAVERSE_SKIP_COMPONENTS
;
3255 case Type::TYPE_STRUCT
:
3256 // Traverse the field types first in case there is an embedded
3257 // field with methods that the struct should inherit.
3258 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3259 return TRAVERSE_EXIT
;
3260 t
->struct_type()->finalize_methods(this->gogo_
);
3261 return TRAVERSE_SKIP_COMPONENTS
;
3267 return TRAVERSE_CONTINUE
;
3270 // Finalize method lists and build stub methods for types.
3273 Gogo::finalize_methods()
3275 Finalize_methods
finalize(this);
3276 this->traverse(&finalize
);
3279 // Finalize the method list for a type. This is called when a type is
3280 // parsed for an inlined function body, which happens after the
3281 // finalize_methods pass.
3284 Gogo::finalize_methods_for_type(Type
* type
)
3286 Finalize_methods
finalize(this);
3287 Type::traverse(type
, &finalize
);
3290 // Set types for unspecified variables and constants.
3293 Gogo::determine_types()
3295 Bindings
* bindings
= this->current_bindings();
3296 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3297 p
!= bindings
->end_definitions();
3300 if ((*p
)->is_function())
3301 (*p
)->func_value()->determine_types();
3302 else if ((*p
)->is_variable())
3303 (*p
)->var_value()->determine_type();
3304 else if ((*p
)->is_const())
3305 (*p
)->const_value()->determine_type();
3307 // See if a variable requires us to build an initialization
3308 // function. We know that we will see all global variables
3310 if (!this->need_init_fn_
&& (*p
)->is_variable())
3312 Variable
* variable
= (*p
)->var_value();
3314 // If this is a global variable which requires runtime
3315 // initialization, we need an initialization function.
3316 if (!variable
->is_global())
3318 else if (variable
->init() == NULL
)
3320 else if (variable
->type()->interface_type() != NULL
)
3321 this->need_init_fn_
= true;
3322 else if (variable
->init()->is_constant())
3324 else if (!variable
->init()->is_composite_literal())
3325 this->need_init_fn_
= true;
3326 else if (variable
->init()->is_nonconstant_composite_literal())
3327 this->need_init_fn_
= true;
3329 // If this is a global variable which holds a pointer value,
3330 // then we need an initialization function to register it as a
3332 if (variable
->is_global() && variable
->type()->has_pointer())
3333 this->need_init_fn_
= true;
3337 // Determine the types of constants in packages.
3338 for (Packages::const_iterator p
= this->packages_
.begin();
3339 p
!= this->packages_
.end();
3341 p
->second
->determine_types();
3344 // Traversal class used for type checking.
3346 class Check_types_traverse
: public Traverse
3349 Check_types_traverse(Gogo
* gogo
)
3350 : Traverse(traverse_variables
3351 | traverse_constants
3352 | traverse_functions
3353 | traverse_statements
3354 | traverse_expressions
),
3359 variable(Named_object
*);
3362 constant(Named_object
*, bool);
3365 function(Named_object
*);
3368 statement(Block
*, size_t* pindex
, Statement
*);
3371 expression(Expression
**);
3378 // Check that a variable initializer has the right type.
3381 Check_types_traverse::variable(Named_object
* named_object
)
3383 if (named_object
->is_variable())
3385 Variable
* var
= named_object
->var_value();
3387 // Give error if variable type is not defined.
3388 var
->type()->base();
3390 Expression
* init
= var
->init();
3393 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3396 go_error_at(var
->location(), "incompatible type in initialization");
3398 go_error_at(var
->location(),
3399 "incompatible type in initialization (%s)",
3401 init
= Expression::make_error(named_object
->location());
3404 else if (init
!= NULL
3405 && init
->func_expression() != NULL
)
3407 Named_object
* no
= init
->func_expression()->named_object();
3408 Function_type
* fntype
;
3409 if (no
->is_function())
3410 fntype
= no
->func_value()->type();
3411 else if (no
->is_function_declaration())
3412 fntype
= no
->func_declaration_value()->type();
3416 // Builtin functions cannot be used as function values for variable
3418 if (fntype
->is_builtin())
3420 go_error_at(init
->location(),
3421 "invalid use of special builtin function %qs; "
3423 no
->message_name().c_str());
3427 && !var
->is_global()
3428 && !var
->is_parameter()
3429 && !var
->is_receiver()
3430 && !var
->type()->is_error()
3431 && (init
== NULL
|| !init
->is_error_expression())
3432 && !Lex::is_invalid_identifier(named_object
->name()))
3433 go_error_at(var
->location(), "%qs declared and not used",
3434 named_object
->message_name().c_str());
3436 return TRAVERSE_CONTINUE
;
3439 // Check that a constant initializer has the right type.
3442 Check_types_traverse::constant(Named_object
* named_object
, bool)
3444 Named_constant
* constant
= named_object
->const_value();
3445 Type
* ctype
= constant
->type();
3446 if (ctype
->integer_type() == NULL
3447 && ctype
->float_type() == NULL
3448 && ctype
->complex_type() == NULL
3449 && !ctype
->is_boolean_type()
3450 && !ctype
->is_string_type())
3452 if (ctype
->is_nil_type())
3453 go_error_at(constant
->location(), "const initializer cannot be nil");
3454 else if (!ctype
->is_error())
3455 go_error_at(constant
->location(), "invalid constant type");
3456 constant
->set_error();
3458 else if (!constant
->expr()->is_constant())
3460 go_error_at(constant
->expr()->location(), "expression is not constant");
3461 constant
->set_error();
3463 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3466 go_error_at(constant
->location(),
3467 "initialization expression has wrong type");
3468 constant
->set_error();
3470 return TRAVERSE_CONTINUE
;
3473 // There are no types to check in a function, but this is where we
3474 // issue warnings about labels which are defined but not referenced.
3477 Check_types_traverse::function(Named_object
* no
)
3479 no
->func_value()->check_labels();
3480 return TRAVERSE_CONTINUE
;
3483 // Check that types are valid in a statement.
3486 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3488 s
->check_types(this->gogo_
);
3489 return TRAVERSE_CONTINUE
;
3492 // Check that types are valid in an expression.
3495 Check_types_traverse::expression(Expression
** expr
)
3497 (*expr
)->check_types(this->gogo_
);
3498 return TRAVERSE_CONTINUE
;
3501 // Check that types are valid.
3506 Check_types_traverse
traverse(this);
3507 this->traverse(&traverse
);
3509 Bindings
* bindings
= this->current_bindings();
3510 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3511 p
!= bindings
->end_declarations();
3514 // Also check the types in a function declaration's signature.
3515 Named_object
* no
= p
->second
;
3516 if (no
->is_function_declaration())
3517 no
->func_declaration_value()->check_types();
3521 // Check the types in a single block.
3524 Gogo::check_types_in_block(Block
* block
)
3526 Check_types_traverse
traverse(this);
3527 block
->traverse(&traverse
);
3530 // A traversal class which finds all the expressions which must be
3531 // evaluated in order within a statement or larger expression. This
3532 // is used to implement the rules about order of evaluation.
3534 class Find_eval_ordering
: public Traverse
3537 typedef std::vector
<Expression
**> Expression_pointers
;
3540 Find_eval_ordering()
3541 : Traverse(traverse_blocks
3542 | traverse_statements
3543 | traverse_expressions
),
3549 { return this->exprs_
.size(); }
3551 typedef Expression_pointers::const_iterator const_iterator
;
3555 { return this->exprs_
.begin(); }
3559 { return this->exprs_
.end(); }
3564 { return TRAVERSE_SKIP_COMPONENTS
; }
3567 statement(Block
*, size_t*, Statement
*)
3568 { return TRAVERSE_SKIP_COMPONENTS
; }
3571 expression(Expression
**);
3574 // A list of pointers to expressions with side-effects.
3575 Expression_pointers exprs_
;
3578 // If an expression must be evaluated in order, put it on the list.
3581 Find_eval_ordering::expression(Expression
** expression_pointer
)
3583 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3585 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3587 // Shortcut expressions may potentially have side effects which need
3588 // to be ordered, so add them to the list.
3589 // We don't order its subexpressions here since they may be evaluated
3590 // conditionally. This is handled in remove_shortcuts.
3591 this->exprs_
.push_back(expression_pointer
);
3592 return TRAVERSE_SKIP_COMPONENTS
;
3595 // We have to look at subexpressions before this one.
3596 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3597 return TRAVERSE_EXIT
;
3598 if ((*expression_pointer
)->must_eval_in_order())
3599 this->exprs_
.push_back(expression_pointer
);
3600 return TRAVERSE_SKIP_COMPONENTS
;
3603 // A traversal class for ordering evaluations.
3605 class Order_eval
: public Traverse
3608 Order_eval(Gogo
* gogo
)
3609 : Traverse(traverse_variables
3610 | traverse_statements
),
3615 variable(Named_object
*);
3618 statement(Block
*, size_t*, Statement
*);
3625 // Implement the order of evaluation rules for a statement.
3628 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3630 // FIXME: This approach doesn't work for switch statements, because
3631 // we add the new statements before the whole switch when we need to
3632 // instead add them just before the switch expression. The right
3633 // fix is probably to lower switch statements with nonconstant cases
3634 // to a series of conditionals.
3635 if (stmt
->switch_statement() != NULL
)
3636 return TRAVERSE_CONTINUE
;
3638 Find_eval_ordering find_eval_ordering
;
3640 // If S is a variable declaration, then ordinary traversal won't do
3641 // anything. We want to explicitly traverse the initialization
3642 // expression if there is one.
3643 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
3644 Expression
* init
= NULL
;
3645 Expression
* orig_init
= NULL
;
3647 stmt
->traverse_contents(&find_eval_ordering
);
3650 init
= vds
->var()->var_value()->init();
3652 return TRAVERSE_CONTINUE
;
3655 // It might seem that this could be
3656 // init->traverse_subexpressions. Unfortunately that can fail
3659 // newvar, err := call(arg())
3660 // Here newvar will have an init of call result 0 of
3661 // call(arg()). If we only traverse subexpressions, we will
3662 // only find arg(), and we won't bother to move anything out.
3663 // Then we get to the assignment to err, we will traverse the
3664 // whole statement, and this time we will find both call() and
3665 // arg(), and so we will move them out. This will cause them to
3666 // be put into temporary variables before the assignment to err
3667 // but after the declaration of newvar. To avoid that problem,
3668 // we traverse the entire expression here.
3669 Expression::traverse(&init
, &find_eval_ordering
);
3672 size_t c
= find_eval_ordering
.size();
3674 return TRAVERSE_CONTINUE
;
3676 // If there is only one expression with a side-effect, we can
3677 // usually leave it in place.
3680 switch (stmt
->classification())
3682 case Statement::STATEMENT_ASSIGNMENT
:
3683 // For an assignment statement, we need to evaluate an
3684 // expression on the right hand side before we evaluate any
3685 // index expression on the left hand side, so for that case
3686 // we always move the expression. Otherwise we mishandle
3687 // m[0] = len(m) where m is a map.
3690 case Statement::STATEMENT_EXPRESSION
:
3692 // If this is a call statement that doesn't return any
3693 // values, it will not have been counted as a value to
3694 // move. We need to move any subexpressions in case they
3695 // are themselves call statements that require passing a
3697 Expression
* expr
= stmt
->expression_statement()->expr();
3698 if (expr
->call_expression() != NULL
3699 && expr
->call_expression()->result_count() == 0)
3701 return TRAVERSE_CONTINUE
;
3705 // We can leave the expression in place.
3706 return TRAVERSE_CONTINUE
;
3710 bool is_thunk
= stmt
->thunk_statement() != NULL
;
3711 Expression_statement
* es
= stmt
->expression_statement();
3712 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3713 p
!= find_eval_ordering
.end();
3716 Expression
** pexpr
= *p
;
3718 // The last expression in a thunk will be the call passed to go
3719 // or defer, which we must not evaluate early.
3720 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3723 Location loc
= (*pexpr
)->location();
3725 if ((*pexpr
)->call_expression() == NULL
3726 || (*pexpr
)->call_expression()->result_count() < 2)
3728 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3731 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3735 // A call expression which returns multiple results needs to
3736 // be handled specially. We can't create a temporary
3737 // because there is no type to give it. Any actual uses of
3738 // the values will be done via Call_result_expressions.
3740 // Since a given call expression can be shared by multiple
3741 // Call_result_expressions, avoid hoisting the call the
3742 // second time we see it here. In addition, don't try to
3743 // hoist the top-level multi-return call in the statement,
3744 // since doing this would result a tree with more than one copy
3746 if (this->remember_expression(*pexpr
))
3748 else if (es
!= NULL
&& *pexpr
== es
->expr())
3751 s
= Statement::make_statement(*pexpr
, true);
3756 block
->insert_statement_before(*pindex
, s
);
3761 if (init
!= orig_init
)
3762 vds
->var()->var_value()->set_init(init
);
3764 return TRAVERSE_CONTINUE
;
3767 // Implement the order of evaluation rules for the initializer of a
3771 Order_eval::variable(Named_object
* no
)
3773 if (no
->is_result_variable())
3774 return TRAVERSE_CONTINUE
;
3775 Variable
* var
= no
->var_value();
3776 Expression
* init
= var
->init();
3777 if (!var
->is_global() || init
== NULL
)
3778 return TRAVERSE_CONTINUE
;
3780 Find_eval_ordering find_eval_ordering
;
3781 Expression::traverse(&init
, &find_eval_ordering
);
3783 if (find_eval_ordering
.size() <= 1)
3785 // If there is only one expression with a side-effect, we can
3786 // leave it in place.
3787 return TRAVERSE_SKIP_COMPONENTS
;
3790 Expression
* orig_init
= init
;
3792 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3793 p
!= find_eval_ordering
.end();
3796 Expression
** pexpr
= *p
;
3797 Location loc
= (*pexpr
)->location();
3799 if ((*pexpr
)->call_expression() == NULL
3800 || (*pexpr
)->call_expression()->result_count() < 2)
3802 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3805 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3809 // A call expression which returns multiple results needs to
3810 // be handled specially.
3811 s
= Statement::make_statement(*pexpr
, true);
3813 var
->add_preinit_statement(this->gogo_
, s
);
3816 if (init
!= orig_init
)
3817 var
->set_init(init
);
3819 return TRAVERSE_SKIP_COMPONENTS
;
3822 // Use temporary variables to implement the order of evaluation rules.
3825 Gogo::order_evaluations()
3827 Order_eval
order_eval(this);
3828 this->traverse(&order_eval
);
3831 // A traversal class used to find a single shortcut operator within an
3834 class Find_shortcut
: public Traverse
3838 : Traverse(traverse_blocks
3839 | traverse_statements
3840 | traverse_expressions
),
3844 // A pointer to the expression which was found, or NULL if none was
3848 { return this->found_
; }
3853 { return TRAVERSE_SKIP_COMPONENTS
; }
3856 statement(Block
*, size_t*, Statement
*)
3857 { return TRAVERSE_SKIP_COMPONENTS
; }
3860 expression(Expression
**);
3863 Expression
** found_
;
3866 // Find a shortcut expression.
3869 Find_shortcut::expression(Expression
** pexpr
)
3871 Expression
* expr
= *pexpr
;
3872 Binary_expression
* be
= expr
->binary_expression();
3874 return TRAVERSE_CONTINUE
;
3875 Operator op
= be
->op();
3876 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3877 return TRAVERSE_CONTINUE
;
3878 go_assert(this->found_
== NULL
);
3879 this->found_
= pexpr
;
3880 return TRAVERSE_EXIT
;
3883 // A traversal class used to turn shortcut operators into explicit if
3886 class Shortcuts
: public Traverse
3889 Shortcuts(Gogo
* gogo
)
3890 : Traverse(traverse_variables
3891 | traverse_statements
),
3897 variable(Named_object
*);
3900 statement(Block
*, size_t*, Statement
*);
3903 // Convert a shortcut operator.
3905 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3911 // Remove shortcut operators in a single statement.
3914 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3916 // FIXME: This approach doesn't work for switch statements, because
3917 // we add the new statements before the whole switch when we need to
3918 // instead add them just before the switch expression. The right
3919 // fix is probably to lower switch statements with nonconstant cases
3920 // to a series of conditionals.
3921 if (s
->switch_statement() != NULL
)
3922 return TRAVERSE_CONTINUE
;
3926 Find_shortcut find_shortcut
;
3928 // If S is a variable declaration, then ordinary traversal won't
3929 // do anything. We want to explicitly traverse the
3930 // initialization expression if there is one.
3931 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3932 Expression
* init
= NULL
;
3934 s
->traverse_contents(&find_shortcut
);
3937 init
= vds
->var()->var_value()->init();
3939 return TRAVERSE_CONTINUE
;
3940 init
->traverse(&init
, &find_shortcut
);
3942 Expression
** pshortcut
= find_shortcut
.found();
3943 if (pshortcut
== NULL
)
3944 return TRAVERSE_CONTINUE
;
3946 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3947 block
->insert_statement_before(*pindex
, snew
);
3950 if (pshortcut
== &init
)
3951 vds
->var()->var_value()->set_init(init
);
3955 // Remove shortcut operators in the initializer of a global variable.
3958 Shortcuts::variable(Named_object
* no
)
3960 if (no
->is_result_variable())
3961 return TRAVERSE_CONTINUE
;
3962 Variable
* var
= no
->var_value();
3963 Expression
* init
= var
->init();
3964 if (!var
->is_global() || init
== NULL
)
3965 return TRAVERSE_CONTINUE
;
3969 Find_shortcut find_shortcut
;
3970 init
->traverse(&init
, &find_shortcut
);
3971 Expression
** pshortcut
= find_shortcut
.found();
3972 if (pshortcut
== NULL
)
3973 return TRAVERSE_CONTINUE
;
3975 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3976 var
->add_preinit_statement(this->gogo_
, snew
);
3977 if (pshortcut
== &init
)
3978 var
->set_init(init
);
3982 // Given an expression which uses a shortcut operator, return a
3983 // statement which implements it, and update *PSHORTCUT accordingly.
3986 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3988 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3989 Expression
* left
= shortcut
->left();
3990 Expression
* right
= shortcut
->right();
3991 Location loc
= shortcut
->location();
3993 Block
* retblock
= new Block(enclosing
, loc
);
3994 retblock
->set_end_location(loc
);
3996 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3998 retblock
->add_statement(ts
);
4000 Block
* block
= new Block(retblock
, loc
);
4001 block
->set_end_location(loc
);
4002 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4003 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4004 block
->add_statement(assign
);
4006 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4007 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4008 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4010 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4012 retblock
->add_statement(if_statement
);
4014 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4018 // Now convert any shortcut operators in LEFT and RIGHT.
4019 // LEFT and RIGHT were skipped in the top level
4020 // Gogo::order_evaluations. We need to order their
4021 // components first.
4022 Order_eval
order_eval(this->gogo_
);
4023 retblock
->traverse(&order_eval
);
4024 Shortcuts
shortcuts(this->gogo_
);
4025 retblock
->traverse(&shortcuts
);
4027 return Statement::make_block_statement(retblock
, loc
);
4030 // Turn shortcut operators into explicit if statements. Doing this
4031 // considerably simplifies the order of evaluation rules.
4034 Gogo::remove_shortcuts()
4036 Shortcuts
shortcuts(this);
4037 this->traverse(&shortcuts
);
4040 // Traversal to flatten parse tree after order of evaluation rules are applied.
4042 class Flatten
: public Traverse
4045 Flatten(Gogo
* gogo
, Named_object
* function
)
4046 : Traverse(traverse_variables
4047 | traverse_functions
4048 | traverse_statements
4049 | traverse_expressions
),
4050 gogo_(gogo
), function_(function
), inserter_()
4054 set_inserter(const Statement_inserter
* inserter
)
4055 { this->inserter_
= *inserter
; }
4058 variable(Named_object
*);
4061 function(Named_object
*);
4064 statement(Block
*, size_t* pindex
, Statement
*);
4067 expression(Expression
**);
4072 // The function we are traversing.
4073 Named_object
* function_
;
4074 // Current statement inserter for use by expressions.
4075 Statement_inserter inserter_
;
4078 // Flatten variables.
4081 Flatten::variable(Named_object
* no
)
4083 if (!no
->is_variable())
4084 return TRAVERSE_CONTINUE
;
4086 if (no
->is_variable() && no
->var_value()->is_global())
4088 // Global variables can have loops in their initialization
4089 // expressions. This is handled in flatten_init_expression.
4090 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4092 return TRAVERSE_CONTINUE
;
4095 if (!no
->var_value()->is_parameter()
4096 && !no
->var_value()->is_receiver()
4097 && !no
->var_value()->is_closure()
4098 && no
->var_value()->is_non_escaping_address_taken()
4099 && !no
->var_value()->is_in_heap()
4100 && no
->var_value()->toplevel_decl() == NULL
)
4102 // Local variable that has address taken but not escape.
4103 // It needs to be live beyond its lexical scope. So we
4104 // create a top-level declaration for it.
4105 // No need to do it if it is already in the top level.
4106 Block
* top_block
= function_
->func_value()->block();
4107 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4109 Variable
* var
= no
->var_value();
4110 Temporary_statement
* ts
=
4111 Statement::make_temporary(var
->type(), NULL
, var
->location());
4112 ts
->set_is_address_taken();
4113 top_block
->add_statement_at_front(ts
);
4114 var
->set_toplevel_decl(ts
);
4118 go_assert(!no
->var_value()->has_pre_init());
4120 return TRAVERSE_SKIP_COMPONENTS
;
4123 // Flatten the body of a function. Record the function while flattening it,
4124 // so that we can pass it down when flattening an expression.
4127 Flatten::function(Named_object
* no
)
4129 go_assert(this->function_
== NULL
);
4130 this->function_
= no
;
4131 int t
= no
->func_value()->traverse(this);
4132 this->function_
= NULL
;
4134 if (t
== TRAVERSE_EXIT
)
4136 return TRAVERSE_SKIP_COMPONENTS
;
4139 // Flatten statement parse trees.
4142 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4144 // Because we explicitly traverse the statement's contents
4145 // ourselves, we want to skip block statements here. There is
4146 // nothing to flatten in a block statement.
4147 if (sorig
->is_block_statement())
4148 return TRAVERSE_CONTINUE
;
4150 Statement_inserter
hold_inserter(this->inserter_
);
4151 this->inserter_
= Statement_inserter(block
, pindex
);
4153 // Flatten the expressions first.
4154 int t
= sorig
->traverse_contents(this);
4155 if (t
== TRAVERSE_EXIT
)
4157 this->inserter_
= hold_inserter
;
4161 // Keep flattening until nothing changes.
4162 Statement
* s
= sorig
;
4165 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4170 t
= s
->traverse_contents(this);
4171 if (t
== TRAVERSE_EXIT
)
4173 this->inserter_
= hold_inserter
;
4179 block
->replace_statement(*pindex
, s
);
4181 this->inserter_
= hold_inserter
;
4182 return TRAVERSE_SKIP_COMPONENTS
;
4185 // Flatten expression parse trees.
4188 Flatten::expression(Expression
** pexpr
)
4190 // Keep flattening until nothing changes.
4193 Expression
* e
= *pexpr
;
4194 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4195 return TRAVERSE_EXIT
;
4197 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4203 return TRAVERSE_SKIP_COMPONENTS
;
4209 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4211 Flatten
flatten(this, function
);
4212 block
->traverse(&flatten
);
4215 // Flatten an expression. INSERTER may be NULL, in which case the
4216 // expression had better not need to create any temporaries.
4219 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4222 Flatten
flatten(this, function
);
4223 if (inserter
!= NULL
)
4224 flatten
.set_inserter(inserter
);
4225 flatten
.expression(pexpr
);
4231 Flatten
flatten(this, NULL
);
4232 this->traverse(&flatten
);
4235 // Traversal to convert calls to the predeclared recover function to
4236 // pass in an argument indicating whether it can recover from a panic
4239 class Convert_recover
: public Traverse
4242 Convert_recover(Named_object
* arg
)
4243 : Traverse(traverse_expressions
),
4249 expression(Expression
**);
4252 // The argument to pass to the function.
4256 // Convert calls to recover.
4259 Convert_recover::expression(Expression
** pp
)
4261 Call_expression
* ce
= (*pp
)->call_expression();
4262 if (ce
!= NULL
&& ce
->is_recover_call())
4263 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4265 return TRAVERSE_CONTINUE
;
4268 // Traversal for build_recover_thunks.
4270 class Build_recover_thunks
: public Traverse
4273 Build_recover_thunks(Gogo
* gogo
)
4274 : Traverse(traverse_functions
),
4279 function(Named_object
*);
4283 can_recover_arg(Location
);
4289 // If this function calls recover, turn it into a thunk.
4292 Build_recover_thunks::function(Named_object
* orig_no
)
4294 Function
* orig_func
= orig_no
->func_value();
4295 if (!orig_func
->calls_recover()
4296 || orig_func
->is_recover_thunk()
4297 || orig_func
->has_recover_thunk())
4298 return TRAVERSE_CONTINUE
;
4300 Gogo
* gogo
= this->gogo_
;
4301 Location location
= orig_func
->location();
4306 Function_type
* orig_fntype
= orig_func
->type();
4307 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4308 std::string receiver_name
;
4309 if (orig_fntype
->is_method())
4311 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4312 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4314 receiver_name
= buf
;
4315 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4316 receiver
->location()));
4318 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4319 if (orig_params
!= NULL
&& !orig_params
->empty())
4321 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4322 p
!= orig_params
->end();
4325 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4327 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4331 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4333 std::string can_recover_name
= buf
;
4334 new_params
->push_back(Typed_identifier(can_recover_name
,
4335 Type::lookup_bool_type(),
4336 orig_fntype
->location()));
4338 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4339 Typed_identifier_list
* new_results
;
4340 if (orig_results
== NULL
|| orig_results
->empty())
4344 new_results
= new Typed_identifier_list();
4345 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4346 p
!= orig_results
->end();
4348 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4351 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4353 orig_fntype
->location());
4354 if (orig_fntype
->is_varargs())
4355 new_fntype
->set_is_varargs();
4358 if (orig_fntype
->is_method())
4359 rtype
= orig_fntype
->receiver()->type();
4360 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4361 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4363 Function
*new_func
= new_no
->func_value();
4364 if (orig_func
->enclosing() != NULL
)
4365 new_func
->set_enclosing(orig_func
->enclosing());
4367 // We build the code for the original function attached to the new
4368 // function, and then swap the original and new function bodies.
4369 // This means that existing references to the original function will
4370 // then refer to the new function. That makes this code a little
4371 // confusing, in that the reference to NEW_NO really refers to the
4372 // other function, not the one we are building.
4374 Expression
* closure
= NULL
;
4375 if (orig_func
->needs_closure())
4377 // For the new function we are creating, declare a new parameter
4378 // variable NEW_CLOSURE_NO and set it to be the closure variable
4379 // of the function. This will be set to the closure value
4380 // passed in by the caller. Then pass a reference to this
4381 // variable as the closure value when calling the original
4382 // function. In other words, simply pass the closure value
4383 // through the thunk we are creating.
4384 Named_object
* orig_closure_no
= orig_func
->closure_var();
4385 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4386 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4387 false, false, location
);
4388 new_var
->set_is_closure();
4389 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4391 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4393 new_func
->set_closure_var(new_closure_no
);
4394 closure
= Expression::make_var_reference(new_closure_no
, location
);
4397 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4399 Expression_list
* args
= new Expression_list();
4400 if (new_params
!= NULL
)
4402 // Note that we skip the last parameter, which is the boolean
4403 // indicating whether recover can succed.
4404 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4405 p
+ 1 != new_params
->end();
4408 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4409 go_assert(p_no
!= NULL
4410 && p_no
->is_variable()
4411 && p_no
->var_value()->is_parameter());
4412 args
->push_back(Expression::make_var_reference(p_no
, location
));
4415 args
->push_back(this->can_recover_arg(location
));
4417 gogo
->start_block(location
);
4419 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4421 // Any varargs call has already been lowered.
4422 call
->set_varargs_are_lowered();
4424 Statement
* s
= Statement::make_return_from_call(call
, location
);
4425 s
->determine_types();
4426 gogo
->add_statement(s
);
4428 Block
* b
= gogo
->finish_block(location
);
4430 gogo
->add_block(b
, location
);
4432 // Lower the call in case it returns multiple results.
4433 gogo
->lower_block(new_no
, b
);
4435 gogo
->finish_function(location
);
4437 // Swap the function bodies and types.
4438 new_func
->swap_for_recover(orig_func
);
4439 orig_func
->set_is_recover_thunk();
4440 new_func
->set_calls_recover();
4441 new_func
->set_has_recover_thunk();
4443 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4444 Bindings
* new_bindings
= new_func
->block()->bindings();
4445 if (orig_fntype
->is_method())
4447 // We changed the receiver to be a regular parameter. We have
4448 // to update the binding accordingly in both functions.
4449 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4450 go_assert(orig_rec_no
!= NULL
4451 && orig_rec_no
->is_variable()
4452 && !orig_rec_no
->var_value()->is_receiver());
4453 orig_rec_no
->var_value()->set_is_receiver();
4455 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4456 if (new_receiver_name
.empty())
4458 // Find the receiver. It was named "r.NNN" in
4459 // Gogo::start_function.
4460 for (Bindings::const_definitions_iterator p
=
4461 new_bindings
->begin_definitions();
4462 p
!= new_bindings
->end_definitions();
4465 const std::string
& pname((*p
)->name());
4466 if (pname
[0] == 'r' && pname
[1] == '.')
4468 new_receiver_name
= pname
;
4472 go_assert(!new_receiver_name
.empty());
4474 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4475 if (new_rec_no
== NULL
)
4476 go_assert(saw_errors());
4479 go_assert(new_rec_no
->is_variable()
4480 && new_rec_no
->var_value()->is_receiver());
4481 new_rec_no
->var_value()->set_is_not_receiver();
4485 // Because we flipped blocks but not types, the can_recover
4486 // parameter appears in the (now) old bindings as a parameter.
4487 // Change it to a local variable, whereupon it will be discarded.
4488 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4489 go_assert(can_recover_no
!= NULL
4490 && can_recover_no
->is_variable()
4491 && can_recover_no
->var_value()->is_parameter());
4492 orig_bindings
->remove_binding(can_recover_no
);
4494 // Add the can_recover argument to the (now) new bindings, and
4495 // attach it to any recover statements.
4496 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4497 false, true, false, location
);
4498 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4500 Convert_recover
convert_recover(can_recover_no
);
4501 new_func
->traverse(&convert_recover
);
4503 // Update the function pointers in any named results.
4504 new_func
->update_result_variables();
4505 orig_func
->update_result_variables();
4507 return TRAVERSE_CONTINUE
;
4510 // Return the expression to pass for the .can_recover parameter to the
4511 // new function. This indicates whether a call to recover may return
4512 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4515 Build_recover_thunks::can_recover_arg(Location location
)
4517 static Named_object
* builtin_return_address
;
4518 if (builtin_return_address
== NULL
)
4519 builtin_return_address
=
4520 Gogo::declare_builtin_rf_address("__builtin_return_address", true);
4522 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4523 static Named_object
* can_recover
;
4524 if (can_recover
== NULL
)
4526 const Location bloc
= Linemap::predeclared_location();
4527 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4528 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4529 Type
* boolean_type
= Type::lookup_bool_type();
4530 Typed_identifier_list
* results
= new Typed_identifier_list();
4531 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4532 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4535 Named_object::make_function_declaration("runtime_canrecover",
4536 NULL
, fntype
, bloc
);
4537 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4540 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4543 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4544 Expression_list
*args
= new Expression_list();
4545 args
->push_back(zexpr
);
4547 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4548 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4550 args
= new Expression_list();
4551 args
->push_back(call
);
4553 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4554 return Expression::make_call(fn
, args
, false, location
);
4557 // Build thunks for functions which call recover. We build a new
4558 // function with an extra parameter, which is whether a call to
4559 // recover can succeed. We then move the body of this function to
4560 // that one. We then turn this function into a thunk which calls the
4561 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4562 // The function will be marked as not splitting the stack. This will
4563 // cooperate with the implementation of defer to make recover do the
4567 Gogo::build_recover_thunks()
4569 Build_recover_thunks
build_recover_thunks(this);
4570 this->traverse(&build_recover_thunks
);
4573 // Return a declaration for __builtin_return_address or
4574 // __builtin_dwarf_cfa.
4577 Gogo::declare_builtin_rf_address(const char* name
, bool hasarg
)
4579 const Location bloc
= Linemap::predeclared_location();
4581 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4584 Type
* uint32_type
= Type::lookup_integer_type("uint32");
4585 param_types
->push_back(Typed_identifier("l", uint32_type
, bloc
));
4588 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4589 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4590 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4592 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4593 return_types
, bloc
);
4594 Named_object
* ret
= Named_object::make_function_declaration(name
, NULL
,
4596 ret
->func_declaration_value()->set_asm_name(name
);
4600 // Build a call to the runtime error function.
4603 Gogo::runtime_error(int code
, Location location
)
4605 Type
* int32_type
= Type::lookup_integer_type("int32");
4606 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4608 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4611 // Look for named types to see whether we need to create an interface
4614 class Build_method_tables
: public Traverse
4617 Build_method_tables(Gogo
* gogo
,
4618 const std::vector
<Interface_type
*>& interfaces
)
4619 : Traverse(traverse_types
),
4620 gogo_(gogo
), interfaces_(interfaces
)
4629 // A list of locally defined interfaces which have hidden methods.
4630 const std::vector
<Interface_type
*>& interfaces_
;
4633 // Build all required interface method tables for types. We need to
4634 // ensure that we have an interface method table for every interface
4635 // which has a hidden method, for every named type which implements
4636 // that interface. Normally we can just build interface method tables
4637 // as we need them. However, in some cases we can require an
4638 // interface method table for an interface defined in a different
4639 // package for a type defined in that package. If that interface and
4640 // type both use a hidden method, that is OK. However, we will not be
4641 // able to build that interface method table when we need it, because
4642 // the type's hidden method will be static. So we have to build it
4643 // here, and just refer it from other packages as needed.
4646 Gogo::build_interface_method_tables()
4651 std::vector
<Interface_type
*> hidden_interfaces
;
4652 hidden_interfaces
.reserve(this->interface_types_
.size());
4653 for (std::vector
<Interface_type
*>::const_iterator pi
=
4654 this->interface_types_
.begin();
4655 pi
!= this->interface_types_
.end();
4658 const Typed_identifier_list
* methods
= (*pi
)->methods();
4659 if (methods
== NULL
)
4661 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4662 pm
!= methods
->end();
4665 if (Gogo::is_hidden_name(pm
->name()))
4667 hidden_interfaces
.push_back(*pi
);
4673 if (!hidden_interfaces
.empty())
4675 // Now traverse the tree looking for all named types.
4676 Build_method_tables
bmt(this, hidden_interfaces
);
4677 this->traverse(&bmt
);
4680 // We no longer need the list of interfaces.
4682 this->interface_types_
.clear();
4685 // This is called for each type. For a named type, for each of the
4686 // interfaces with hidden methods that it implements, create the
4690 Build_method_tables::type(Type
* type
)
4692 Named_type
* nt
= type
->named_type();
4693 Struct_type
* st
= type
->struct_type();
4694 if (nt
!= NULL
|| st
!= NULL
)
4696 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4697 for (std::vector
<Interface_type
*>::const_iterator p
=
4698 this->interfaces_
.begin();
4699 p
!= this->interfaces_
.end();
4702 // We ask whether a pointer to the named type implements the
4703 // interface, because a pointer can implement more methods
4707 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4710 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4711 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4716 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4719 st
->interface_method_table(*p
, false)->get_backend(&context
);
4720 st
->interface_method_table(*p
, true)->get_backend(&context
);
4725 return TRAVERSE_CONTINUE
;
4728 // Return an expression which allocates memory to hold values of type TYPE.
4731 Gogo::allocate_memory(Type
* type
, Location location
)
4733 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4734 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
4737 // Traversal class used to check for return statements.
4739 class Check_return_statements_traverse
: public Traverse
4742 Check_return_statements_traverse()
4743 : Traverse(traverse_functions
)
4747 function(Named_object
*);
4750 // Check that a function has a return statement if it needs one.
4753 Check_return_statements_traverse::function(Named_object
* no
)
4755 Function
* func
= no
->func_value();
4756 const Function_type
* fntype
= func
->type();
4757 const Typed_identifier_list
* results
= fntype
->results();
4759 // We only need a return statement if there is a return value.
4760 if (results
== NULL
|| results
->empty())
4761 return TRAVERSE_CONTINUE
;
4763 if (func
->block()->may_fall_through())
4764 go_error_at(func
->block()->end_location(),
4765 "missing return at end of function");
4767 return TRAVERSE_CONTINUE
;
4770 // Check return statements.
4773 Gogo::check_return_statements()
4775 Check_return_statements_traverse traverse
;
4776 this->traverse(&traverse
);
4779 // Traversal class to decide whether a function body is less than the
4780 // inlining budget. This adjusts *available as it goes, and stops the
4781 // traversal if it goes negative.
4783 class Inline_within_budget
: public Traverse
4786 Inline_within_budget(int* available
)
4787 : Traverse(traverse_statements
4788 | traverse_expressions
),
4789 available_(available
)
4793 statement(Block
*, size_t*, Statement
*);
4796 expression(Expression
**);
4799 // Pointer to remaining budget.
4803 // Adjust the budget for the inlining cost of a statement.
4806 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
4808 if (*this->available_
< 0)
4809 return TRAVERSE_EXIT
;
4810 *this->available_
-= s
->inlining_cost();
4811 return TRAVERSE_CONTINUE
;
4814 // Adjust the budget for the inlining cost of an expression.
4817 Inline_within_budget::expression(Expression
** pexpr
)
4819 if (*this->available_
< 0)
4820 return TRAVERSE_EXIT
;
4821 *this->available_
-= (*pexpr
)->inlining_cost();
4822 return TRAVERSE_CONTINUE
;
4825 // Traversal class to find functions whose body should be exported for
4826 // inlining by other packages.
4828 class Mark_inline_candidates
: public Traverse
4831 Mark_inline_candidates()
4832 : Traverse(traverse_functions
4837 function(Named_object
*);
4843 // We traverse the function body trying to determine how expensive
4844 // it is for inlining. We start with a budget, and decrease that
4845 // budget for each statement and expression. If the budget goes
4846 // negative, we do not export the function body. The value of this
4847 // budget is a heuristic. In the usual GCC spirit, we could
4848 // consider setting this via a command line option.
4849 const int budget_heuristic
= 80;
4852 // Mark a function if it is an inline candidate.
4855 Mark_inline_candidates::function(Named_object
* no
)
4857 Function
* func
= no
->func_value();
4858 int budget
= budget_heuristic
;
4859 Inline_within_budget
iwb(&budget
);
4860 func
->block()->traverse(&iwb
);
4862 func
->set_export_for_inlining();
4863 return TRAVERSE_CONTINUE
;
4866 // Mark methods if they are inline candidates.
4869 Mark_inline_candidates::type(Type
* t
)
4871 Named_type
* nt
= t
->named_type();
4872 if (nt
== NULL
|| nt
->is_alias())
4873 return TRAVERSE_CONTINUE
;
4874 const Bindings
* methods
= nt
->local_methods();
4875 if (methods
== NULL
)
4876 return TRAVERSE_CONTINUE
;
4877 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
4878 p
!= methods
->end_definitions();
4881 Named_object
* no
= *p
;
4882 go_assert(no
->is_function());
4883 Function
*func
= no
->func_value();
4884 int budget
= budget_heuristic
;
4885 Inline_within_budget
iwb(&budget
);
4886 func
->block()->traverse(&iwb
);
4888 func
->set_export_for_inlining();
4890 return TRAVERSE_CONTINUE
;
4893 // Export identifiers as requested.
4898 // Mark any functions whose body should be exported for inlining by
4900 Mark_inline_candidates mic
;
4901 this->traverse(&mic
);
4903 // For now we always stream to a section. Later we may want to
4904 // support streaming to a separate file.
4905 Stream_to_section
stream(this->backend());
4907 // Write out either the prefix or pkgpath depending on how we were
4910 std::string pkgpath
;
4911 if (this->pkgpath_from_option_
)
4912 pkgpath
= this->pkgpath_
;
4913 else if (this->prefix_from_option_
)
4914 prefix
= this->prefix_
;
4915 else if (this->is_main_package())
4920 Export
exp(&stream
);
4921 exp
.register_builtin_types(this);
4922 exp
.export_globals(this->package_name(),
4927 (this->need_init_fn_
&& !this->is_main_package()
4928 ? this->get_init_fn_name()
4930 this->imported_init_fns_
,
4931 this->package_
->bindings());
4933 if (!this->c_header_
.empty() && !saw_errors())
4934 this->write_c_header();
4937 // Write the top level named struct types in C format to a C header
4938 // file. This is used when building the runtime package, to share
4939 // struct definitions between C and Go.
4942 Gogo::write_c_header()
4945 out
.open(this->c_header_
.c_str());
4948 go_error_at(Linemap::unknown_location(),
4949 "cannot open %s: %m", this->c_header_
.c_str());
4953 std::list
<Named_object
*> types
;
4954 Bindings
* top
= this->package_
->bindings();
4955 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
4956 p
!= top
->end_definitions();
4959 Named_object
* no
= *p
;
4961 // Skip names that start with underscore followed by something
4962 // other than an uppercase letter, as when compiling the runtime
4963 // package they are mostly types defined by mkrsysinfo.sh based
4964 // on the C system header files. We don't need to translate
4965 // types to C and back to Go. But do accept the special cases
4966 // _defer and _panic.
4967 std::string name
= Gogo::unpack_hidden_name(no
->name());
4969 && (name
[1] < 'A' || name
[1] > 'Z')
4970 && (name
!= "_defer" && name
!= "_panic"))
4973 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
4974 types
.push_back(no
);
4976 && no
->const_value()->type()->integer_type() != NULL
4977 && !no
->const_value()->is_sink())
4979 Numeric_constant nc
;
4981 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
4982 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
4984 out
<< "#define " << no
->message_name() << ' ' << val
4990 std::vector
<const Named_object
*> written
;
4992 while (!types
.empty())
4994 Named_object
* no
= types
.front();
4997 std::vector
<const Named_object
*> requires
;
4998 std::vector
<const Named_object
*> declare
;
4999 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
5004 for (std::vector
<const Named_object
*>::const_iterator pr
5006 pr
!= requires
.end() && ok
;
5009 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5010 pt
!= types
.end() && ok
;
5020 // This should be impossible since the code parsed and
5025 types
.push_back(no
);
5029 for (std::vector
<const Named_object
*>::const_iterator pd
5031 pd
!= declare
.end();
5037 std::vector
<const Named_object
*> drequires
;
5038 std::vector
<const Named_object
*> ddeclare
;
5039 if (!(*pd
)->type_value()->struct_type()->
5040 can_write_to_c_header(&drequires
, &ddeclare
))
5044 for (std::vector
<const Named_object
*>::const_iterator pw
5046 pw
!= written
.end();
5058 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5059 written
.push_back(*pd
);
5064 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5065 no
->type_value()->struct_type()->write_to_c_header(out
);
5066 out
<< "};" << std::endl
;
5067 written
.push_back(no
);
5072 go_error_at(Linemap::unknown_location(),
5073 "error writing to %s: %m", this->c_header_
.c_str());
5076 // Find the blocks in order to convert named types defined in blocks.
5078 class Convert_named_types
: public Traverse
5081 Convert_named_types(Gogo
* gogo
)
5082 : Traverse(traverse_blocks
),
5088 block(Block
* block
);
5095 Convert_named_types::block(Block
* block
)
5097 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5098 return TRAVERSE_CONTINUE
;
5101 // Convert all named types to the backend representation. Since named
5102 // types can refer to other types, this needs to be done in the right
5103 // sequence, which is handled by Named_type::convert. Here we arrange
5104 // to call that for each named type.
5107 Gogo::convert_named_types()
5109 this->convert_named_types_in_bindings(this->globals_
);
5110 for (Packages::iterator p
= this->packages_
.begin();
5111 p
!= this->packages_
.end();
5114 Package
* package
= p
->second
;
5115 this->convert_named_types_in_bindings(package
->bindings());
5118 Convert_named_types
cnt(this);
5119 this->traverse(&cnt
);
5121 // Make all the builtin named types used for type descriptors, and
5122 // then convert them. They will only be written out if they are
5124 Type::make_type_descriptor_type();
5125 Type::make_type_descriptor_ptr_type();
5126 Function_type::make_function_type_descriptor_type();
5127 Pointer_type::make_pointer_type_descriptor_type();
5128 Struct_type::make_struct_type_descriptor_type();
5129 Array_type::make_array_type_descriptor_type();
5130 Array_type::make_slice_type_descriptor_type();
5131 Map_type::make_map_type_descriptor_type();
5132 Channel_type::make_chan_type_descriptor_type();
5133 Interface_type::make_interface_type_descriptor_type();
5134 Expression::make_func_descriptor_type();
5135 Type::convert_builtin_named_types(this);
5137 Runtime::convert_types(this);
5139 this->named_types_are_converted_
= true;
5141 Type::finish_pointer_types(this);
5144 // Convert all names types in a set of bindings.
5147 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5149 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5150 p
!= bindings
->end_definitions();
5153 if ((*p
)->is_type())
5154 (*p
)->type_value()->convert(this);
5160 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5162 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5163 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5164 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5165 pragmas_(0), nested_functions_(0), is_sink_(false),
5166 results_are_named_(false), is_unnamed_type_stub_method_(false),
5167 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5168 calls_defer_retaddr_(false), is_type_specific_function_(false),
5169 in_unique_section_(false), export_for_inlining_(false),
5170 is_inline_only_(false)
5174 // Create the named result variables.
5177 Function::create_result_variables(Gogo
* gogo
)
5179 const Typed_identifier_list
* results
= this->type_
->results();
5180 if (results
== NULL
|| results
->empty())
5183 if (!results
->front().name().empty())
5184 this->results_are_named_
= true;
5186 this->results_
= new Results();
5187 this->results_
->reserve(results
->size());
5189 Block
* block
= this->block_
;
5191 for (Typed_identifier_list::const_iterator p
= results
->begin();
5192 p
!= results
->end();
5195 std::string name
= p
->name();
5196 if (name
.empty() || Gogo::is_sink_name(name
))
5198 static int result_counter
;
5200 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5202 name
= gogo
->pack_hidden_name(buf
, false);
5204 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5206 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5207 if (no
->is_result_variable())
5208 this->results_
->push_back(no
);
5211 static int dummy_result_count
;
5213 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5214 ++dummy_result_count
;
5215 name
= gogo
->pack_hidden_name(buf
, false);
5216 no
= block
->bindings()->add_result_variable(name
, result
);
5217 go_assert(no
->is_result_variable());
5218 this->results_
->push_back(no
);
5223 // Update the named result variables when cloning a function which
5227 Function::update_result_variables()
5229 if (this->results_
== NULL
)
5232 for (Results::iterator p
= this->results_
->begin();
5233 p
!= this->results_
->end();
5235 (*p
)->result_var_value()->set_function(this);
5238 // Whether this method should not be included in the type descriptor.
5241 Function::nointerface() const
5243 go_assert(this->is_method());
5244 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5247 // Record that this method should not be included in the type
5251 Function::set_nointerface()
5253 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5256 // Return the closure variable, creating it if necessary.
5259 Function::closure_var()
5261 if (this->closure_var_
== NULL
)
5263 go_assert(this->descriptor_
== NULL
);
5264 // We don't know the type of the variable yet. We add fields as
5266 Location loc
= this->type_
->location();
5267 Struct_field_list
* sfl
= new Struct_field_list
;
5268 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5269 struct_type
->set_is_struct_incomparable();
5270 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5271 NULL
, false, false, false, loc
);
5273 var
->set_is_closure();
5274 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5275 // Note that the new variable is not in any binding contour.
5277 return this->closure_var_
;
5280 // Set the type of the closure variable.
5283 Function::set_closure_type()
5285 if (this->closure_var_
== NULL
)
5287 Named_object
* closure
= this->closure_var_
;
5288 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5290 // The first field of a closure is always a pointer to the function
5292 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5293 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5296 unsigned int index
= 1;
5297 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5298 p
!= this->closure_fields_
.end();
5301 Named_object
* no
= p
->first
;
5303 snprintf(buf
, sizeof buf
, "%u", index
);
5304 std::string n
= no
->name() + buf
;
5306 if (no
->is_variable())
5307 var_type
= no
->var_value()->type();
5309 var_type
= no
->result_var_value()->type();
5310 Type
* field_type
= Type::make_pointer_type(var_type
);
5311 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5315 // Return whether this function is a method.
5318 Function::is_method() const
5320 return this->type_
->is_method();
5323 // Add a label definition.
5326 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5329 Label
* lnull
= NULL
;
5330 std::pair
<Labels::iterator
, bool> ins
=
5331 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5333 if (label_name
== "_")
5335 label
= Label::create_dummy_label();
5337 ins
.first
->second
= label
;
5339 else if (ins
.second
)
5341 // This is a new label.
5342 label
= new Label(label_name
);
5343 ins
.first
->second
= label
;
5347 // The label was already in the hash table.
5348 label
= ins
.first
->second
;
5349 if (label
->is_defined())
5351 go_error_at(location
, "label %qs already defined",
5352 Gogo::message_name(label_name
).c_str());
5353 go_inform(label
->location(), "previous definition of %qs was here",
5354 Gogo::message_name(label_name
).c_str());
5355 return new Label(label_name
);
5359 label
->define(location
, gogo
->bindings_snapshot(location
));
5361 // Issue any errors appropriate for any previous goto's to this
5363 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5364 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5367 (*p
)->check_goto_to(gogo
->current_block());
5368 label
->clear_refs();
5373 // Add a reference to a label.
5376 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5377 Location location
, bool issue_goto_errors
)
5379 Label
* lnull
= NULL
;
5380 std::pair
<Labels::iterator
, bool> ins
=
5381 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5385 // The label was already in the hash table.
5386 label
= ins
.first
->second
;
5390 go_assert(ins
.first
->second
== NULL
);
5391 label
= new Label(label_name
);
5392 ins
.first
->second
= label
;
5395 label
->set_is_used();
5397 if (issue_goto_errors
)
5399 Bindings_snapshot
* snapshot
= label
->snapshot();
5400 if (snapshot
!= NULL
)
5401 snapshot
->check_goto_from(gogo
->current_block(), location
);
5403 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5409 // Warn about labels that are defined but not used.
5412 Function::check_labels() const
5414 for (Labels::const_iterator p
= this->labels_
.begin();
5415 p
!= this->labels_
.end();
5418 Label
* label
= p
->second
;
5419 if (!label
->is_used())
5420 go_error_at(label
->location(), "label %qs defined and not used",
5421 Gogo::message_name(label
->name()).c_str());
5425 // Swap one function with another. This is used when building the
5426 // thunk we use to call a function which calls recover. It may not
5427 // work for any other case.
5430 Function::swap_for_recover(Function
*x
)
5432 go_assert(this->enclosing_
== x
->enclosing_
);
5433 std::swap(this->results_
, x
->results_
);
5434 std::swap(this->closure_var_
, x
->closure_var_
);
5435 std::swap(this->block_
, x
->block_
);
5436 go_assert(this->location_
== x
->location_
);
5437 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5438 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5441 // Traverse the tree.
5444 Function::traverse(Traverse
* traverse
)
5446 unsigned int traverse_mask
= traverse
->traverse_mask();
5449 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5452 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5453 return TRAVERSE_EXIT
;
5456 // FIXME: We should check traverse_functions here if nested
5457 // functions are stored in block bindings.
5458 if (this->block_
!= NULL
5460 & (Traverse::traverse_variables
5461 | Traverse::traverse_constants
5462 | Traverse::traverse_blocks
5463 | Traverse::traverse_statements
5464 | Traverse::traverse_expressions
5465 | Traverse::traverse_types
)) != 0)
5467 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5468 return TRAVERSE_EXIT
;
5471 return TRAVERSE_CONTINUE
;
5474 // Work out types for unspecified variables and constants.
5477 Function::determine_types()
5479 if (this->block_
!= NULL
)
5480 this->block_
->determine_types();
5483 // Return the function descriptor, the value you get when you refer to
5484 // the function in Go code without calling it.
5487 Function::descriptor(Gogo
*, Named_object
* no
)
5489 go_assert(!this->is_method());
5490 go_assert(this->closure_var_
== NULL
);
5491 if (this->descriptor_
== NULL
)
5492 this->descriptor_
= Expression::make_func_descriptor(no
);
5493 return this->descriptor_
;
5496 // Get a pointer to the variable representing the defer stack for this
5497 // function, making it if necessary. The value of the variable is set
5498 // by the runtime routines to true if the function is returning,
5499 // rather than panicing through. A pointer to this variable is used
5500 // as a marker for the functions on the defer stack associated with
5501 // this function. A function-specific variable permits inlining a
5502 // function which uses defer.
5505 Function::defer_stack(Location location
)
5507 if (this->defer_stack_
== NULL
)
5509 Type
* t
= Type::lookup_bool_type();
5510 Expression
* n
= Expression::make_boolean(false, location
);
5511 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5512 this->defer_stack_
->set_is_address_taken();
5514 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5516 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5519 // Export the function.
5522 Function::export_func(Export
* exp
, const std::string
& name
) const
5524 Block
* block
= NULL
;
5525 if (this->export_for_inlining())
5526 block
= this->block_
;
5527 Function::export_func_with_type(exp
, name
, this->type_
, this->results_
,
5528 this->is_method() && this->nointerface(),
5529 block
, this->location_
);
5532 // Export a function with a type.
5535 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
5536 const Function_type
* fntype
,
5537 Function::Results
* result_vars
,
5538 bool nointerface
, Block
* block
, Location loc
)
5540 exp
->write_c_string("func ");
5544 go_assert(fntype
->is_method());
5545 exp
->write_c_string("/*nointerface*/ ");
5548 if (fntype
->is_method())
5550 exp
->write_c_string("(");
5551 const Typed_identifier
* receiver
= fntype
->receiver();
5552 exp
->write_name(receiver
->name());
5553 exp
->write_escape(receiver
->note());
5554 exp
->write_c_string(" ");
5555 exp
->write_type(receiver
->type());
5556 exp
->write_c_string(") ");
5559 exp
->write_string(name
);
5561 exp
->write_c_string(" (");
5562 const Typed_identifier_list
* parameters
= fntype
->parameters();
5563 if (parameters
!= NULL
)
5566 bool is_varargs
= fntype
->is_varargs();
5568 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5569 p
!= parameters
->end();
5575 exp
->write_c_string(", ");
5576 exp
->write_name(p
->name());
5577 exp
->write_escape(p
->note());
5578 exp
->write_c_string(" ");
5579 if (!is_varargs
|| p
+ 1 != parameters
->end())
5580 exp
->write_type(p
->type());
5583 exp
->write_c_string("...");
5584 exp
->write_type(p
->type()->array_type()->element_type());
5588 exp
->write_c_string(")");
5590 const Typed_identifier_list
* result_decls
= fntype
->results();
5591 if (result_decls
!= NULL
)
5593 if (result_decls
->size() == 1
5594 && result_decls
->begin()->name().empty()
5597 exp
->write_c_string(" ");
5598 exp
->write_type(result_decls
->begin()->type());
5602 exp
->write_c_string(" (");
5604 Results::const_iterator pr
;
5605 if (result_vars
!= NULL
)
5606 pr
= result_vars
->begin();
5607 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
5608 pd
!= result_decls
->end();
5614 exp
->write_c_string(", ");
5615 // We only use pr->name, which may be artificial, if
5616 // need it for inlining.
5617 if (block
== NULL
|| result_vars
== NULL
)
5618 exp
->write_name(pd
->name());
5620 exp
->write_name((*pr
)->name());
5621 exp
->write_escape(pd
->note());
5622 exp
->write_c_string(" ");
5623 exp
->write_type(pd
->type());
5624 if (result_vars
!= NULL
)
5627 if (result_vars
!= NULL
)
5628 go_assert(pr
== result_vars
->end());
5629 exp
->write_c_string(")");
5634 exp
->write_c_string("\n");
5638 if (fntype
->is_method())
5641 Export_function_body
efb(exp
, indent
);
5644 efb
.write_c_string("// ");
5645 efb
.write_string(Linemap::location_to_file(block
->start_location()));
5646 efb
.write_char(':');
5648 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
5649 efb
.write_c_string(buf
);
5650 efb
.write_char('\n');
5651 block
->export_block(&efb
);
5653 const std::string
& body(efb
.body());
5655 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
5656 static_cast<unsigned long>(body
.length()));
5657 exp
->write_c_string(buf
);
5659 exp
->write_string(body
);
5663 // Import a function.
5666 Function::import_func(Import
* imp
, std::string
* pname
,
5667 Typed_identifier
** preceiver
,
5668 Typed_identifier_list
** pparameters
,
5669 Typed_identifier_list
** presults
,
5674 imp
->require_c_string("func ");
5676 *nointerface
= false;
5677 if (imp
->match_c_string("/*"))
5679 imp
->require_c_string("/*nointerface*/ ");
5680 *nointerface
= true;
5682 // Only a method can be nointerface.
5683 go_assert(imp
->peek_char() == '(');
5687 if (imp
->peek_char() == '(')
5689 imp
->require_c_string("(");
5690 std::string name
= imp
->read_name();
5691 std::string escape_note
= imp
->read_escape();
5692 imp
->require_c_string(" ");
5693 Type
* rtype
= imp
->read_type();
5694 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5695 (*preceiver
)->set_note(escape_note
);
5696 imp
->require_c_string(") ");
5699 *pname
= imp
->read_identifier();
5701 Typed_identifier_list
* parameters
;
5702 *is_varargs
= false;
5703 imp
->require_c_string(" (");
5704 if (imp
->peek_char() == ')')
5708 parameters
= new Typed_identifier_list();
5711 std::string name
= imp
->read_name();
5712 std::string escape_note
= imp
->read_escape();
5713 imp
->require_c_string(" ");
5715 if (imp
->match_c_string("..."))
5721 Type
* ptype
= imp
->read_type();
5723 ptype
= Type::make_array_type(ptype
, NULL
);
5724 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
5725 t
.set_note(escape_note
);
5726 parameters
->push_back(t
);
5727 if (imp
->peek_char() != ',')
5729 go_assert(!*is_varargs
);
5730 imp
->require_c_string(", ");
5733 imp
->require_c_string(")");
5734 *pparameters
= parameters
;
5736 Typed_identifier_list
* results
;
5737 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
5741 results
= new Typed_identifier_list();
5742 imp
->require_c_string(" ");
5743 if (imp
->peek_char() != '(')
5745 Type
* rtype
= imp
->read_type();
5746 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5750 imp
->require_c_string("(");
5753 std::string name
= imp
->read_name();
5754 std::string note
= imp
->read_escape();
5755 imp
->require_c_string(" ");
5756 Type
* rtype
= imp
->read_type();
5757 Typed_identifier t
= Typed_identifier(name
, rtype
,
5760 results
->push_back(t
);
5761 if (imp
->peek_char() != ',')
5763 imp
->require_c_string(", ");
5765 imp
->require_c_string(")");
5768 *presults
= results
;
5770 if (!imp
->match_c_string(" <inl:"))
5772 imp
->require_semicolon_if_old_version();
5773 imp
->require_c_string("\n");
5778 imp
->require_c_string(" <inl:");
5783 c
= imp
->peek_char();
5784 if (c
< '0' || c
> '9')
5789 imp
->require_c_string(">\n");
5793 long llen
= strtol(lenstr
.c_str(), &end
, 10);
5796 || (llen
== LONG_MAX
&& errno
== ERANGE
))
5798 go_error_at(imp
->location(), "invalid inline function length %s",
5803 *body
= imp
->read(static_cast<size_t>(llen
));
5807 // Get the backend representation.
5810 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5812 if (this->fndecl_
== NULL
)
5814 unsigned int flags
= 0;
5815 bool is_init_fn
= false;
5816 if (no
->package() != NULL
)
5818 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5820 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5821 && !this->type_
->is_method())
5823 else if (no
->name() == gogo
->get_init_fn_name())
5825 flags
|= Backend::function_is_visible
;
5828 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5829 && gogo
->is_main_package())
5830 flags
|= Backend::function_is_visible
;
5831 // Methods have to be public even if they are hidden because
5832 // they can be pulled into type descriptors when using
5833 // anonymous fields.
5834 else if (!Gogo::is_hidden_name(no
->name())
5835 || this->type_
->is_method())
5837 if (!this->is_unnamed_type_stub_method_
)
5838 flags
|= Backend::function_is_visible
;
5842 if (this->type_
->is_method())
5843 rtype
= this->type_
->receiver()->type();
5845 std::string asm_name
;
5846 if (!this->asm_name_
.empty())
5848 asm_name
= this->asm_name_
;
5850 // If an assembler name is explicitly specified, there must
5851 // be some reason to refer to the symbol from a different
5853 flags
|= Backend::function_is_visible
;
5855 else if (is_init_fn
)
5857 // These names appear in the export data and are used
5858 // directly in the assembler code. If we change this here
5859 // we need to change Gogo::init_imports.
5860 asm_name
= no
->name();
5863 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
5865 // If a function calls the predeclared recover function, we
5866 // can't inline it, because recover behaves differently in a
5867 // function passed directly to defer. If this is a recover
5868 // thunk that we built to test whether a function can be
5869 // recovered, we can't inline it, because that will mess up
5870 // our return address comparison.
5871 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5873 // If a function calls __go_set_defer_retaddr, then mark it as
5874 // uninlinable. This prevents the GCC backend from splitting
5875 // the function; splitting the function is a bad idea because we
5876 // want the return address label to be in the same function as
5878 if (this->calls_defer_retaddr_
)
5879 is_inlinable
= false;
5881 // Check the //go:noinline compiler directive.
5882 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
5883 is_inlinable
= false;
5886 flags
|= Backend::function_is_inlinable
;
5888 // If this is a thunk created to call a function which calls
5889 // the predeclared recover function, we need to disable
5890 // stack splitting for the thunk.
5891 bool disable_split_stack
= this->is_recover_thunk_
;
5893 // Check the //go:nosplit compiler directive.
5894 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
5895 disable_split_stack
= true;
5897 if (disable_split_stack
)
5898 flags
|= Backend::function_no_split_stack
;
5900 // This should go into a unique section if that has been
5901 // requested elsewhere, or if this is a nointerface function.
5902 // We want to put a nointerface function into a unique section
5903 // because there is a good chance that the linker garbage
5904 // collection can discard it.
5905 if (this->in_unique_section_
5906 || (this->is_method() && this->nointerface()))
5907 flags
|= Backend::function_in_unique_section
;
5909 if (this->is_inline_only_
)
5910 flags
|= Backend::function_only_inline
;
5912 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5914 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5915 flags
, this->location());
5917 return this->fndecl_
;
5920 // Get the backend representation.
5923 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5925 if (this->fndecl_
== NULL
)
5927 unsigned int flags
=
5928 (Backend::function_is_visible
5929 | Backend::function_is_declaration
5930 | Backend::function_is_inlinable
);
5932 // Let Go code use an asm declaration to pick up a builtin
5934 if (!this->asm_name_
.empty())
5936 Bfunction
* builtin_decl
=
5937 gogo
->backend()->lookup_builtin(this->asm_name_
);
5938 if (builtin_decl
!= NULL
)
5940 this->fndecl_
= builtin_decl
;
5941 return this->fndecl_
;
5944 if (this->asm_name_
== "runtime.gopanic"
5945 || this->asm_name_
== "__go_runtime_error")
5946 flags
|= Backend::function_does_not_return
;
5949 std::string asm_name
;
5950 if (this->asm_name_
.empty())
5953 if (this->fntype_
->is_method())
5954 rtype
= this->fntype_
->receiver()->type();
5955 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
5957 else if (go_id_needs_encoding(no
->get_id(gogo
)))
5958 asm_name
= go_encode_id(no
->get_id(gogo
));
5960 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5962 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5963 flags
, this->location());
5966 return this->fndecl_
;
5969 // Build the descriptor for a function declaration. This won't
5970 // necessarily happen if the package has just a declaration for the
5971 // function and no other reference to it, but we may still need the
5972 // descriptor for references from other packages.
5974 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5976 if (this->descriptor_
!= NULL
)
5978 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5979 this->descriptor_
->get_backend(&context
);
5983 // Check that the types used in this declaration's signature are defined.
5984 // Reports errors for any undefined type.
5987 Function_declaration::check_types() const
5989 // Calling Type::base will give errors for any undefined types.
5990 Function_type
* fntype
= this->type();
5991 if (fntype
->receiver() != NULL
)
5992 fntype
->receiver()->type()->base();
5993 if (fntype
->parameters() != NULL
)
5995 const Typed_identifier_list
* params
= fntype
->parameters();
5996 for (Typed_identifier_list::const_iterator p
= params
->begin();
6003 // Return the function's decl after it has been built.
6006 Function::get_decl() const
6008 go_assert(this->fndecl_
!= NULL
);
6009 return this->fndecl_
;
6012 // Build the backend representation for the function code.
6015 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6017 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6019 // A list of parameter variables for this function.
6020 std::vector
<Bvariable
*> param_vars
;
6022 // Variables that need to be declared for this function and their
6024 std::vector
<Bvariable
*> vars
;
6025 std::vector
<Bexpression
*> var_inits
;
6026 std::vector
<Statement
*> var_decls_stmts
;
6027 for (Bindings::const_definitions_iterator p
=
6028 this->block_
->bindings()->begin_definitions();
6029 p
!= this->block_
->bindings()->end_definitions();
6032 Location loc
= (*p
)->location();
6033 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6035 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6036 Bvariable
* parm_bvar
= bvar
;
6038 // We always pass the receiver to a method as a pointer. If
6039 // the receiver is declared as a non-pointer type, then we
6040 // copy the value into a local variable.
6041 if ((*p
)->var_value()->is_receiver()
6042 && !(*p
)->var_value()->type()->is_direct_iface_type())
6044 std::string name
= (*p
)->name() + ".pointer";
6045 Type
* var_type
= (*p
)->var_value()->type();
6046 Variable
* parm_var
=
6047 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6049 Named_object
* parm_no
=
6050 Named_object::make_variable(name
, NULL
, parm_var
);
6051 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6053 vars
.push_back(bvar
);
6054 Expression
* parm_ref
=
6055 Expression::make_var_reference(parm_no
, loc
);
6057 Expression::make_dereference(parm_ref
,
6058 Expression::NIL_CHECK_NEEDED
,
6060 if ((*p
)->var_value()->is_in_heap())
6061 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6062 var_inits
.push_back(parm_ref
->get_backend(&context
));
6064 else if ((*p
)->var_value()->is_in_heap())
6066 // If we take the address of a parameter, then we need
6067 // to copy it into the heap.
6068 std::string parm_name
= (*p
)->name() + ".param";
6069 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6070 false, true, false, loc
);
6071 Named_object
* parm_no
=
6072 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6073 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6075 vars
.push_back(bvar
);
6076 Expression
* var_ref
=
6077 Expression::make_var_reference(parm_no
, loc
);
6078 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6079 var_inits
.push_back(var_ref
->get_backend(&context
));
6081 param_vars
.push_back(parm_bvar
);
6083 else if ((*p
)->is_result_variable())
6085 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6087 Type
* type
= (*p
)->result_var_value()->type();
6089 if (!(*p
)->result_var_value()->is_in_heap())
6091 Btype
* btype
= type
->get_backend(gogo
);
6092 init
= gogo
->backend()->zero_expression(btype
);
6095 init
= Expression::make_allocation(type
,
6096 loc
)->get_backend(&context
);
6098 vars
.push_back(bvar
);
6099 var_inits
.push_back(init
);
6101 else if (this->defer_stack_
!= NULL
6102 && (*p
)->is_variable()
6103 && (*p
)->var_value()->is_non_escaping_address_taken()
6104 && !(*p
)->var_value()->is_in_heap())
6106 // Local variable captured by deferred closure needs to be live
6107 // until the end of the function. We create a top-level
6108 // declaration for it.
6109 // TODO: we don't need to do this if the variable is not captured
6110 // by the defer closure. There is no easy way to check it here,
6111 // so we do this for all address-taken variables for now.
6112 Variable
* var
= (*p
)->var_value();
6113 Temporary_statement
* ts
=
6114 Statement::make_temporary(var
->type(), NULL
, var
->location());
6115 ts
->set_is_address_taken();
6116 var
->set_toplevel_decl(ts
);
6117 var_decls_stmts
.push_back(ts
);
6120 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6122 go_assert(saw_errors());
6126 // If we need a closure variable, make sure to create it.
6127 // It gets installed in the function as a side effect of creation.
6128 if (this->closure_var_
!= NULL
)
6130 go_assert(this->closure_var_
->var_value()->is_closure());
6131 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6134 if (this->block_
!= NULL
)
6136 // Declare variables if necessary.
6137 Bblock
* var_decls
= NULL
;
6138 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6139 Bstatement
* defer_init
= NULL
;
6140 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6143 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6144 this->block_
->start_location(),
6145 this->block_
->end_location());
6147 if (this->defer_stack_
!= NULL
)
6149 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6151 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6152 var_decls_bstmt_list
.push_back(defer_init
);
6153 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6154 p
!= var_decls_stmts
.end();
6157 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6158 var_decls_bstmt_list
.push_back(bstmt
);
6163 // Build the backend representation for all the statements in the
6165 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6166 Bblock
* code_block
= this->block_
->get_backend(&context
);
6168 // Initialize variables if necessary.
6169 std::vector
<Bstatement
*> init
;
6170 go_assert(vars
.size() == var_inits
.size());
6171 for (size_t i
= 0; i
< vars
.size(); ++i
)
6173 Bstatement
* init_stmt
=
6174 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6176 init
.push_back(init_stmt
);
6178 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6180 // Initialize all variables before executing this code block.
6181 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6182 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6184 // If we have a defer stack, initialize it at the start of a
6186 Bstatement
* except
= NULL
;
6187 Bstatement
* fini
= NULL
;
6188 if (defer_init
!= NULL
)
6190 // Clean up the defer stack when we leave the function.
6191 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6193 // Wrap the code for this function in an exception handler to handle
6196 gogo
->backend()->exception_handler_statement(code_stmt
,
6201 // Stick the code into the block we built for the receiver, if
6203 if (var_decls
!= NULL
)
6205 var_decls_bstmt_list
.push_back(code_stmt
);
6206 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6207 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6210 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6212 go_assert(saw_errors());
6217 // If we created a descriptor for the function, make sure we emit it.
6218 if (this->descriptor_
!= NULL
)
6220 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6221 this->descriptor_
->get_backend(&context
);
6225 // Build the wrappers around function code needed if the function has
6226 // any defer statements. This sets *EXCEPT to an exception handler
6227 // and *FINI to a finally handler.
6230 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6231 Bstatement
** except
, Bstatement
** fini
)
6233 Location end_loc
= this->block_
->end_location();
6235 // Add an exception handler. This is used if a panic occurs. Its
6236 // purpose is to stop the stack unwinding if a deferred function
6237 // calls recover. There are more details in
6238 // libgo/runtime/go-unwind.c.
6240 std::vector
<Bstatement
*> stmts
;
6241 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6242 this->defer_stack(end_loc
));
6243 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6244 Bexpression
* defer
= call
->get_backend(&context
);
6245 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6247 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6248 if (ret_bstmt
!= NULL
)
6249 stmts
.push_back(ret_bstmt
);
6251 go_assert(*except
== NULL
);
6252 *except
= gogo
->backend()->statement_list(stmts
);
6254 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6255 this->defer_stack(end_loc
));
6256 defer
= call
->get_backend(&context
);
6258 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
6259 this->defer_stack(end_loc
));
6260 Bexpression
* undefer
= call
->get_backend(&context
);
6261 Bstatement
* function_defer
=
6262 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6264 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6265 if (this->type_
->results() != NULL
6266 && !this->type_
->results()->empty()
6267 && !this->type_
->results()->front().name().empty())
6269 // If the result variables are named, and we are returning from
6270 // this function rather than panicing through it, we need to
6271 // return them again, because they might have been changed by a
6272 // defer function. The runtime routines set the defer_stack
6273 // variable to true if we are returning from this function.
6275 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6276 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6278 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6280 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6281 Bexpression
* bref
= ref
->get_backend(&context
);
6282 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6283 NULL
, bref
, ret
, NULL
,
6285 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6288 go_assert(*fini
== NULL
);
6289 *fini
= gogo
->backend()->statement_list(stmts
);
6292 // Return the statement that assigns values to this function's result struct.
6295 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6296 Location location
) const
6298 const Typed_identifier_list
* results
= this->type_
->results();
6299 if (results
== NULL
|| results
->empty())
6302 go_assert(this->results_
!= NULL
);
6303 if (this->results_
->size() != results
->size())
6305 go_assert(saw_errors());
6306 return gogo
->backend()->error_statement();
6309 std::vector
<Bexpression
*> vals(results
->size());
6310 for (size_t i
= 0; i
< vals
.size(); ++i
)
6312 Named_object
* no
= (*this->results_
)[i
];
6313 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6314 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6315 if (no
->result_var_value()->is_in_heap())
6317 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6318 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6322 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6327 Block::Block(Block
* enclosing
, Location location
)
6328 : enclosing_(enclosing
), statements_(),
6329 bindings_(new Bindings(enclosing
== NULL
6331 : enclosing
->bindings())),
6332 start_location_(location
),
6333 end_location_(Linemap::unknown_location())
6337 // Add a statement to a block.
6340 Block::add_statement(Statement
* statement
)
6342 this->statements_
.push_back(statement
);
6345 // Add a statement to the front of a block. This is slow but is only
6346 // used for reference counts of parameters.
6349 Block::add_statement_at_front(Statement
* statement
)
6351 this->statements_
.insert(this->statements_
.begin(), statement
);
6354 // Replace a statement in a block.
6357 Block::replace_statement(size_t index
, Statement
* s
)
6359 go_assert(index
< this->statements_
.size());
6360 this->statements_
[index
] = s
;
6363 // Add a statement before another statement.
6366 Block::insert_statement_before(size_t index
, Statement
* s
)
6368 go_assert(index
< this->statements_
.size());
6369 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6372 // Add a statement after another statement.
6375 Block::insert_statement_after(size_t index
, Statement
* s
)
6377 go_assert(index
< this->statements_
.size());
6378 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6381 // Traverse the tree.
6384 Block::traverse(Traverse
* traverse
)
6386 unsigned int traverse_mask
= traverse
->traverse_mask();
6388 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6390 int t
= traverse
->block(this);
6391 if (t
== TRAVERSE_EXIT
)
6392 return TRAVERSE_EXIT
;
6393 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6394 return TRAVERSE_CONTINUE
;
6398 & (Traverse::traverse_variables
6399 | Traverse::traverse_constants
6400 | Traverse::traverse_expressions
6401 | Traverse::traverse_types
)) != 0)
6403 const unsigned int e_or_t
= (Traverse::traverse_expressions
6404 | Traverse::traverse_types
);
6405 const unsigned int e_or_t_or_s
= (e_or_t
6406 | Traverse::traverse_statements
);
6407 for (Bindings::const_definitions_iterator pb
=
6408 this->bindings_
->begin_definitions();
6409 pb
!= this->bindings_
->end_definitions();
6412 int t
= TRAVERSE_CONTINUE
;
6413 switch ((*pb
)->classification())
6415 case Named_object::NAMED_OBJECT_CONST
:
6416 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
6417 t
= traverse
->constant(*pb
, false);
6418 if (t
== TRAVERSE_CONTINUE
6419 && (traverse_mask
& e_or_t
) != 0)
6421 Type
* tc
= (*pb
)->const_value()->type();
6423 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
6424 return TRAVERSE_EXIT
;
6425 t
= (*pb
)->const_value()->traverse_expression(traverse
);
6429 case Named_object::NAMED_OBJECT_VAR
:
6430 case Named_object::NAMED_OBJECT_RESULT_VAR
:
6431 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
6432 t
= traverse
->variable(*pb
);
6433 if (t
== TRAVERSE_CONTINUE
6434 && (traverse_mask
& e_or_t
) != 0)
6436 if ((*pb
)->is_result_variable()
6437 || (*pb
)->var_value()->has_type())
6439 Type
* tv
= ((*pb
)->is_variable()
6440 ? (*pb
)->var_value()->type()
6441 : (*pb
)->result_var_value()->type());
6443 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
6444 return TRAVERSE_EXIT
;
6447 if (t
== TRAVERSE_CONTINUE
6448 && (traverse_mask
& e_or_t_or_s
) != 0
6449 && (*pb
)->is_variable())
6450 t
= (*pb
)->var_value()->traverse_expression(traverse
,
6454 case Named_object::NAMED_OBJECT_FUNC
:
6455 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
6458 case Named_object::NAMED_OBJECT_TYPE
:
6459 if ((traverse_mask
& e_or_t
) != 0)
6460 t
= Type::traverse((*pb
)->type_value(), traverse
);
6463 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
6464 case Named_object::NAMED_OBJECT_UNKNOWN
:
6465 case Named_object::NAMED_OBJECT_ERRONEOUS
:
6468 case Named_object::NAMED_OBJECT_PACKAGE
:
6469 case Named_object::NAMED_OBJECT_SINK
:
6476 if (t
== TRAVERSE_EXIT
)
6477 return TRAVERSE_EXIT
;
6481 // No point in checking traverse_mask here--if we got here we always
6482 // want to walk the statements. The traversal can insert new
6483 // statements before or after the current statement. Inserting
6484 // statements before the current statement requires updating I via
6485 // the pointer; those statements will not be traversed. Any new
6486 // statements inserted after the current statement will be traversed
6488 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6490 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6491 return TRAVERSE_EXIT
;
6494 return TRAVERSE_CONTINUE
;
6497 // Work out types for unspecified variables and constants.
6500 Block::determine_types()
6502 for (Bindings::const_definitions_iterator pb
=
6503 this->bindings_
->begin_definitions();
6504 pb
!= this->bindings_
->end_definitions();
6507 if ((*pb
)->is_variable())
6508 (*pb
)->var_value()->determine_type();
6509 else if ((*pb
)->is_const())
6510 (*pb
)->const_value()->determine_type();
6513 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6514 ps
!= this->statements_
.end();
6516 (*ps
)->determine_types();
6519 // Return true if the statements in this block may fall through.
6522 Block::may_fall_through() const
6524 if (this->statements_
.empty())
6526 return this->statements_
.back()->may_fall_through();
6529 // Write export data for a block.
6532 Block::export_block(Export_function_body
* efb
)
6534 for (Block::iterator p
= this->begin();
6540 efb
->increment_indent();
6541 (*p
)->export_statement(efb
);
6542 efb
->decrement_indent();
6544 Location loc
= (*p
)->location();
6545 if ((*p
)->is_block_statement())
6547 // For a block we put the start location on the first brace
6548 // in Block_statement::do_export_statement. Here we put the
6549 // end location on the final brace.
6550 loc
= (*p
)->block_statement()->block()->end_location();
6553 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
6554 efb
->write_c_string(buf
);
6558 // Add exported block data to SET, reading from BODY starting at OFF.
6559 // Returns whether the import succeeded.
6562 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
6564 Location eloc
= ifb
->location();
6565 Location sloc
= loc
;
6566 const std::string
& body(ifb
->body());
6567 size_t off
= ifb
->off();
6568 while (off
< body
.length())
6570 int indent
= ifb
->indent();
6571 if (off
+ indent
>= body
.length())
6574 "invalid export data for %qs: insufficient indentation",
6575 ifb
->name().c_str());
6578 for (int i
= 0; i
< indent
- 1; i
++)
6580 if (body
[off
+ i
] != ' ')
6583 "invalid export data for %qs: bad indentation",
6584 ifb
->name().c_str());
6589 bool at_end
= false;
6590 if (body
[off
+ indent
- 1] == '}')
6592 else if (body
[off
+ indent
- 1] != ' ')
6595 "invalid export data for %qs: bad indentation",
6596 ifb
->name().c_str());
6602 size_t nl
= body
.find('\n', off
);
6603 if (nl
== std::string::npos
)
6605 go_error_at(eloc
, "invalid export data for %qs: missing newline",
6606 ifb
->name().c_str());
6610 size_t lineno_pos
= body
.find(" //", off
);
6611 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
6613 go_error_at(eloc
, "invalid export data for %qs: missing line number",
6614 ifb
->name().c_str());
6618 unsigned int lineno
= 0;
6619 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
6622 if (c
< '0' || c
> '9')
6625 "invalid export data for %qs: invalid line number",
6626 ifb
->name().c_str());
6629 lineno
= lineno
* 10 + c
- '0';
6632 ifb
->gogo()->linemap()->start_line(lineno
, 1);
6633 sloc
= ifb
->gogo()->linemap()->get_location(0);
6642 Statement
* s
= Statement::import_statement(ifb
, sloc
);
6646 set
->add_statement(s
);
6648 size_t at
= ifb
->off();
6656 set
->set_end_location(sloc
);
6660 // Convert a block to the backend representation.
6663 Block::get_backend(Translate_context
* context
)
6665 Gogo
* gogo
= context
->gogo();
6666 Named_object
* function
= context
->function();
6667 std::vector
<Bvariable
*> vars
;
6668 vars
.reserve(this->bindings_
->size_definitions());
6669 for (Bindings::const_definitions_iterator pv
=
6670 this->bindings_
->begin_definitions();
6671 pv
!= this->bindings_
->end_definitions();
6674 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
6675 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
6678 go_assert(function
!= NULL
);
6679 Bfunction
* bfunction
=
6680 function
->func_value()->get_or_make_decl(gogo
, function
);
6681 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
6682 vars
, this->start_location_
,
6683 this->end_location_
);
6685 Translate_context
subcontext(gogo
, function
, this, ret
);
6686 std::vector
<Bstatement
*> bstatements
;
6687 bstatements
.reserve(this->statements_
.size());
6688 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
6689 p
!= this->statements_
.end();
6691 bstatements
.push_back((*p
)->get_backend(&subcontext
));
6693 context
->backend()->block_add_statements(ret
, bstatements
);
6698 // Class Bindings_snapshot.
6700 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
6701 : block_(b
), counts_(), location_(location
)
6705 this->counts_
.push_back(b
->bindings()->size_definitions());
6710 // Report errors appropriate for a goto from B to this.
6713 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
6716 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
6718 this->check_goto_defs(loc
, this->block_
,
6719 this->block_
->bindings()->size_definitions(),
6723 // Report errors appropriate for a goto from this to B.
6726 Bindings_snapshot::check_goto_to(const Block
* b
)
6729 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
6731 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
6732 b
->bindings()->size_definitions());
6735 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6736 // Return true if all is well, false if we reported an error. If this
6737 // returns true, it sets *PINDEX to the number of blocks BTO is above
6741 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
6742 const Block
* bto
, size_t* pindex
)
6744 // It is an error if BTO is not either BFROM or above BFROM.
6746 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
6750 go_error_at(loc
, "goto jumps into block");
6751 go_inform(bto
->start_location(), "goto target block starts here");
6759 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6760 // CFROM is the number of names defined at the point of the goto and
6761 // CTO is the number of names defined at the point of the label.
6764 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
6765 size_t cfrom
, size_t cto
)
6769 Bindings::const_definitions_iterator p
=
6770 block
->bindings()->begin_definitions();
6771 for (size_t i
= 0; i
< cfrom
; ++i
)
6773 go_assert(p
!= block
->bindings()->end_definitions());
6776 go_assert(p
!= block
->bindings()->end_definitions());
6778 for (; p
!= block
->bindings()->end_definitions(); ++p
)
6780 if ((*p
)->is_variable())
6782 std::string n
= (*p
)->message_name();
6783 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
6784 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
6790 // Class Function_declaration.
6792 // Whether this declares a method.
6795 Function_declaration::is_method() const
6797 return this->fntype_
->is_method();
6800 // Whether this method should not be included in the type descriptor.
6803 Function_declaration::nointerface() const
6805 go_assert(this->is_method());
6806 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
6809 // Record that this method should not be included in the type
6813 Function_declaration::set_nointerface()
6815 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
6818 // Import an inlinable function. This is used for an inlinable
6819 // function whose body is recorded in the export data. Parse the
6820 // export data into a Block and create a regular function using that
6821 // Block as its body. Redeclare this function declaration as the
6825 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
6827 go_assert(no
->func_declaration_value() == this);
6828 go_assert(no
->package() != NULL
);
6829 const std::string
& body(this->imported_body_
);
6830 go_assert(!body
.empty());
6832 // Read the "//FILE:LINE" comment starts the export data.
6835 if (this->is_method())
6838 for (; i
< indent
; i
++)
6840 if (body
.at(i
) != ' ')
6842 go_error_at(this->location_
,
6843 "invalid export body for %qs: bad initial indentation",
6844 no
->message_name().c_str());
6849 if (body
.substr(i
, 2) != "//")
6851 go_error_at(this->location_
,
6852 "invalid export body for %qs: missing file comment",
6853 no
->message_name().c_str());
6857 size_t colon
= body
.find(':', i
+ 2);
6858 size_t nl
= body
.find('\n', i
+ 2);
6859 if (nl
== std::string::npos
)
6861 go_error_at(this->location_
,
6862 "invalid export body for %qs: missing file name",
6863 no
->message_name().c_str());
6866 if (colon
== std::string::npos
|| nl
< colon
)
6868 go_error_at(this->location_
,
6869 "invalid export body for %qs: missing initial line number",
6870 no
->message_name().c_str());
6874 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
6875 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
6877 long linenol
= strtol(linestr
.c_str(), &end
, 10);
6880 go_error_at(this->location_
,
6881 "invalid export body for %qs: invalid initial line number",
6882 no
->message_name().c_str());
6885 unsigned int lineno
= static_cast<unsigned int>(linenol
);
6887 // Turn the file/line into a location.
6889 char* alc
= new char[file
.length() + 1];
6890 memcpy(alc
, file
.data(), file
.length());
6891 alc
[file
.length()] = '\0';
6892 gogo
->linemap()->start_file(alc
, lineno
);
6893 gogo
->linemap()->start_line(lineno
, 1);
6894 Location start_loc
= gogo
->linemap()->get_location(0);
6896 // Define the function with an outer block that declares the
6899 Function_type
* fntype
= this->fntype_
;
6901 Block
* outer
= new Block(NULL
, start_loc
);
6903 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
6904 fn
->set_is_inline_only();
6906 if (fntype
->is_method())
6908 if (this->nointerface())
6909 fn
->set_nointerface();
6910 const Typed_identifier
* receiver
= fntype
->receiver();
6911 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
6912 true, true, start_loc
);
6914 std::string rname
= receiver
->name();
6915 unsigned rcounter
= 0;
6917 // We need to give a nameless receiver a name to avoid having it
6918 // clash with some other nameless param. FIXME.
6919 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
6921 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
6924 const Typed_identifier_list
* params
= fntype
->parameters();
6925 bool is_varargs
= fntype
->is_varargs();
6926 unsigned pcounter
= 0;
6929 for (Typed_identifier_list::const_iterator p
= params
->begin();
6933 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
6935 if (is_varargs
&& p
+ 1 == params
->end())
6936 param
->set_is_varargs_parameter();
6938 std::string pname
= p
->name();
6940 // We need to give each nameless parameter a non-empty name to avoid
6941 // having it clash with some other nameless param. FIXME.
6942 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
6944 outer
->bindings()->add_variable(pname
, NULL
, param
);
6948 fn
->create_result_variables(gogo
);
6950 if (!fntype
->is_method())
6952 const Package
* package
= no
->package();
6953 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
6957 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
6958 go_assert(rtype
!= NULL
);
6959 no
= rtype
->add_method(no
->name(), fn
);
6962 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
6964 if (!Block::import_block(outer
, &ifb
, start_loc
))
6967 gogo
->lower_block(no
, outer
);
6969 gogo
->add_imported_inline_function(no
);
6972 // Return the function descriptor.
6975 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
6977 go_assert(!this->fntype_
->is_method());
6978 if (this->descriptor_
== NULL
)
6979 this->descriptor_
= Expression::make_func_descriptor(no
);
6980 return this->descriptor_
;
6985 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
6986 bool is_parameter
, bool is_receiver
,
6988 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
6989 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
6990 is_closure_(false), is_receiver_(is_receiver
),
6991 is_varargs_parameter_(false), is_used_(false),
6992 is_address_taken_(false), is_non_escaping_address_taken_(false),
6993 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6994 type_from_init_tuple_(false), type_from_range_index_(false),
6995 type_from_range_value_(false), type_from_chan_element_(false),
6996 is_type_switch_var_(false), determined_type_(false),
6997 in_unique_section_(false), toplevel_decl_(NULL
)
6999 go_assert(type
!= NULL
|| init
!= NULL
);
7000 go_assert(!is_parameter
|| init
== NULL
);
7003 // Traverse the initializer expression.
7006 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7008 if (this->preinit_
!= NULL
)
7010 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7011 return TRAVERSE_EXIT
;
7013 if (this->init_
!= NULL
7015 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7018 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7019 return TRAVERSE_EXIT
;
7021 return TRAVERSE_CONTINUE
;
7024 // Lower the initialization expression after parsing is complete.
7027 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7028 Statement_inserter
* inserter
)
7030 Named_object
* dep
= gogo
->var_depends_on(this);
7031 if (dep
!= NULL
&& dep
->is_variable())
7032 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7034 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7038 // We will give an error elsewhere, this is just to prevent
7039 // an infinite loop.
7044 Statement_inserter global_inserter
;
7045 if (this->is_global_
)
7047 global_inserter
= Statement_inserter(gogo
, this);
7048 inserter
= &global_inserter
;
7051 gogo
->lower_expression(function
, inserter
, &this->init_
);
7053 this->seen_
= false;
7055 this->init_is_lowered_
= true;
7059 // Flatten the initialization expression after ordering evaluations.
7062 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7063 Statement_inserter
* inserter
)
7065 Named_object
* dep
= gogo
->var_depends_on(this);
7066 if (dep
!= NULL
&& dep
->is_variable())
7067 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7069 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7073 // We will give an error elsewhere, this is just to prevent
7074 // an infinite loop.
7079 Statement_inserter global_inserter
;
7080 if (this->is_global_
)
7082 global_inserter
= Statement_inserter(gogo
, this);
7083 inserter
= &global_inserter
;
7086 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7088 // If an interface conversion is needed, we need a temporary
7090 if (this->type_
!= NULL
7091 && !Type::are_identical(this->type_
, this->init_
->type(),
7092 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7094 && this->init_
->type()->interface_type() != NULL
7095 && !this->init_
->is_variable())
7097 Temporary_statement
* temp
=
7098 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7099 inserter
->insert(temp
);
7100 this->init_
= Expression::make_temporary_reference(temp
,
7104 this->seen_
= false;
7105 this->init_is_flattened_
= true;
7109 // Get the preinit block.
7112 Variable::preinit_block(Gogo
* gogo
)
7114 go_assert(this->is_global_
);
7115 if (this->preinit_
== NULL
)
7116 this->preinit_
= new Block(NULL
, this->location());
7118 // If a global variable has a preinitialization statement, then we
7119 // need to have an initialization function.
7120 gogo
->set_need_init_fn();
7122 return this->preinit_
;
7125 // Add a statement to be run before the initialization expression.
7128 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7130 Block
* b
= this->preinit_block(gogo
);
7131 b
->add_statement(s
);
7132 b
->set_end_location(s
->location());
7135 // Whether this variable has a type.
7138 Variable::has_type() const
7140 if (this->type_
== NULL
)
7143 // A variable created in a type switch case nil does not actually
7144 // have a type yet. It will be changed to use the initializer's
7145 // type in determine_type.
7146 if (this->is_type_switch_var_
7147 && this->type_
->is_nil_constant_as_type())
7153 // In an assignment which sets a variable to a tuple of EXPR, return
7154 // the type of the first element of the tuple.
7157 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7159 if (expr
->map_index_expression() != NULL
)
7161 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
7163 return Type::make_error_type();
7164 return mt
->val_type();
7166 else if (expr
->receive_expression() != NULL
)
7168 Expression
* channel
= expr
->receive_expression()->channel();
7169 Type
* channel_type
= channel
->type();
7170 if (channel_type
->channel_type() == NULL
)
7171 return Type::make_error_type();
7172 return channel_type
->channel_type()->element_type();
7177 go_error_at(this->location(), "invalid tuple definition");
7178 return Type::make_error_type();
7182 // Given EXPR used in a range clause, return either the index type or
7183 // the value type of the range, depending upon GET_INDEX_TYPE.
7186 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7187 bool report_error
) const
7189 Type
* t
= expr
->type();
7190 if (t
->array_type() != NULL
7191 || (t
->points_to() != NULL
7192 && t
->points_to()->array_type() != NULL
7193 && !t
->points_to()->is_slice_type()))
7196 return Type::lookup_integer_type("int");
7198 return t
->deref()->array_type()->element_type();
7200 else if (t
->is_string_type())
7203 return Type::lookup_integer_type("int");
7205 return Type::lookup_integer_type("int32");
7207 else if (t
->map_type() != NULL
)
7210 return t
->map_type()->key_type();
7212 return t
->map_type()->val_type();
7214 else if (t
->channel_type() != NULL
)
7217 return t
->channel_type()->element_type();
7221 go_error_at(this->location(),
7222 ("invalid definition of value variable "
7223 "for channel range"));
7224 return Type::make_error_type();
7230 go_error_at(this->location(), "invalid type for range clause");
7231 return Type::make_error_type();
7235 // EXPR should be a channel. Return the channel's element type.
7238 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7240 Type
* t
= expr
->type();
7241 if (t
->channel_type() != NULL
)
7242 return t
->channel_type()->element_type();
7246 go_error_at(this->location(), "expected channel");
7247 return Type::make_error_type();
7251 // Return the type of the Variable. This may be called before
7252 // Variable::determine_type is called, which means that we may need to
7253 // get the type from the initializer. FIXME: If we combine lowering
7254 // with type determination, then this should be unnecessary.
7259 // A variable in a type switch with a nil case will have the wrong
7260 // type here. This gets fixed up in determine_type, below.
7261 Type
* type
= this->type_
;
7262 Expression
* init
= this->init_
;
7263 if (this->is_type_switch_var_
7265 && this->type_
->is_nil_constant_as_type())
7267 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7268 go_assert(tge
!= NULL
);
7275 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7277 go_error_at(this->location_
, "variable initializer refers to itself");
7278 this->type_
= Type::make_error_type();
7287 else if (this->type_from_init_tuple_
)
7288 type
= this->type_from_tuple(init
, false);
7289 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7290 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7291 else if (this->type_from_chan_element_
)
7292 type
= this->type_from_chan_element(init
, false);
7295 go_assert(init
!= NULL
);
7296 type
= init
->type();
7297 go_assert(type
!= NULL
);
7299 // Variables should not have abstract types.
7300 if (type
->is_abstract())
7301 type
= type
->make_non_abstract_type();
7303 if (type
->is_void_type())
7304 type
= Type::make_error_type();
7307 this->seen_
= false;
7312 // Fetch the type from a const pointer, in which case it should have
7313 // been set already.
7316 Variable::type() const
7318 go_assert(this->type_
!= NULL
);
7322 // Set the type if necessary.
7325 Variable::determine_type()
7327 if (this->determined_type_
)
7329 this->determined_type_
= true;
7331 if (this->preinit_
!= NULL
)
7332 this->preinit_
->determine_types();
7334 // A variable in a type switch with a nil case will have the wrong
7335 // type here. It will have an initializer which is a type guard.
7336 // We want to initialize it to the value without the type guard, and
7337 // use the type of that value as well.
7338 if (this->is_type_switch_var_
7339 && this->type_
!= NULL
7340 && this->type_
->is_nil_constant_as_type())
7342 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7343 go_assert(tge
!= NULL
);
7345 this->init_
= tge
->expr();
7348 if (this->init_
== NULL
)
7349 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7350 else if (this->type_from_init_tuple_
)
7352 Expression
*init
= this->init_
;
7353 init
->determine_type_no_context();
7354 this->type_
= this->type_from_tuple(init
, true);
7357 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7359 Expression
* init
= this->init_
;
7360 init
->determine_type_no_context();
7361 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7365 else if (this->type_from_chan_element_
)
7367 Expression
* init
= this->init_
;
7368 init
->determine_type_no_context();
7369 this->type_
= this->type_from_chan_element(init
, true);
7374 Type_context
context(this->type_
, false);
7375 this->init_
->determine_type(&context
);
7376 if (this->type_
== NULL
)
7378 Type
* type
= this->init_
->type();
7379 go_assert(type
!= NULL
);
7380 if (type
->is_abstract())
7381 type
= type
->make_non_abstract_type();
7383 if (type
->is_void_type())
7385 go_error_at(this->location_
, "variable has no type");
7386 type
= Type::make_error_type();
7388 else if (type
->is_nil_type())
7390 go_error_at(this->location_
, "variable defined to nil type");
7391 type
= Type::make_error_type();
7393 else if (type
->is_call_multiple_result_type())
7395 go_error_at(this->location_
,
7396 "single variable set to multiple-value function call");
7397 type
= Type::make_error_type();
7405 // Get the initial value of a variable. This does not
7406 // consider whether the variable is in the heap--it returns the
7407 // initial value as though it were always stored in the stack.
7410 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7412 go_assert(this->preinit_
== NULL
);
7413 Location loc
= this->location();
7414 if (this->init_
== NULL
)
7416 go_assert(!this->is_parameter_
);
7417 if (this->is_global_
|| this->is_in_heap())
7419 Btype
* btype
= this->type()->get_backend(gogo
);
7420 return gogo
->backend()->zero_expression(btype
);
7424 Translate_context
context(gogo
, function
, NULL
, NULL
);
7425 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7426 return init
->get_backend(&context
);
7430 // Get the initial value of a variable when a block is required.
7431 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7434 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7435 Bvariable
* var_decl
)
7437 go_assert(this->preinit_
!= NULL
);
7439 // We want to add the variable assignment to the end of the preinit
7442 Translate_context
context(gogo
, function
, NULL
, NULL
);
7443 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7444 Bfunction
* bfunction
=
7445 function
->func_value()->get_or_make_decl(gogo
, function
);
7447 // It's possible to have pre-init statements without an initializer
7448 // if the pre-init statements set the variable.
7449 Bstatement
* decl_init
= NULL
;
7450 if (this->init_
!= NULL
)
7452 if (var_decl
== NULL
)
7454 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7455 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7460 Location loc
= this->location();
7461 Expression
* val_expr
=
7462 Expression::make_cast(this->type(), this->init_
, loc
);
7463 Bexpression
* val
= val_expr
->get_backend(&context
);
7464 Bexpression
* var_ref
=
7465 gogo
->backend()->var_expression(var_decl
, loc
);
7466 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7470 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7471 if (decl_init
!= NULL
)
7472 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
7476 // Export the variable
7479 Variable::export_var(Export
* exp
, const std::string
& name
) const
7481 go_assert(this->is_global_
);
7482 exp
->write_c_string("var ");
7483 exp
->write_string(name
);
7484 exp
->write_c_string(" ");
7485 exp
->write_type(this->type());
7486 exp
->write_c_string("\n");
7489 // Import a variable.
7492 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
7494 imp
->require_c_string("var ");
7495 *pname
= imp
->read_identifier();
7496 imp
->require_c_string(" ");
7497 *ptype
= imp
->read_type();
7498 imp
->require_semicolon_if_old_version();
7499 imp
->require_c_string("\n");
7502 // Convert a variable to the backend representation.
7505 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7506 const Package
* package
, const std::string
& name
)
7508 if (this->backend_
== NULL
)
7510 Backend
* backend
= gogo
->backend();
7511 Type
* type
= this->type_
;
7512 if (type
->is_error_type()
7513 || (type
->is_undefined()
7514 && (!this->is_global_
|| package
== NULL
)))
7515 this->backend_
= backend
->error_variable();
7518 bool is_parameter
= this->is_parameter_
;
7519 if (this->is_receiver_
&& !type
->is_direct_iface_type())
7520 is_parameter
= false;
7521 if (this->is_in_heap())
7523 is_parameter
= false;
7524 type
= Type::make_pointer_type(type
);
7527 const std::string n
= Gogo::unpack_hidden_name(name
);
7528 Btype
* btype
= type
->get_backend(gogo
);
7531 if (Map_type::is_zero_value(this))
7532 bvar
= Map_type::backend_zero_value(gogo
);
7533 else if (this->is_global_
)
7535 std::string
var_name(package
!= NULL
7536 ? package
->package_name()
7537 : gogo
->package_name());
7538 var_name
.push_back('.');
7541 std::string
asm_name(gogo
->global_var_asm_name(name
, package
));
7543 bool is_hidden
= Gogo::is_hidden_name(name
);
7544 // Hack to export runtime.writeBarrier. FIXME.
7545 // This is because go:linkname doesn't work on variables.
7546 if (gogo
->compiling_runtime()
7547 && var_name
== "runtime.writeBarrier")
7550 bvar
= backend
->global_variable(var_name
,
7555 this->in_unique_section_
,
7558 else if (function
== NULL
)
7560 go_assert(saw_errors());
7561 bvar
= backend
->error_variable();
7565 Bfunction
* bfunction
= function
->func_value()->get_decl();
7566 bool is_address_taken
= (this->is_non_escaping_address_taken_
7567 && !this->is_in_heap());
7568 if (this->is_closure())
7569 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
7571 else if (is_parameter
)
7572 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
7577 Bvariable
* bvar_decl
= NULL
;
7578 if (this->toplevel_decl_
!= NULL
)
7580 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
7581 bvar_decl
= this->toplevel_decl_
->temporary_statement()
7582 ->get_backend_variable(&context
);
7584 bvar
= backend
->local_variable(bfunction
, n
, btype
,
7590 this->backend_
= bvar
;
7593 return this->backend_
;
7596 // Class Result_variable.
7598 // Convert a result variable to the backend representation.
7601 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7602 const std::string
& name
)
7604 if (this->backend_
== NULL
)
7606 Backend
* backend
= gogo
->backend();
7607 Type
* type
= this->type_
;
7608 if (type
->is_error())
7609 this->backend_
= backend
->error_variable();
7612 if (this->is_in_heap())
7613 type
= Type::make_pointer_type(type
);
7614 Btype
* btype
= type
->get_backend(gogo
);
7615 Bfunction
* bfunction
= function
->func_value()->get_decl();
7616 std::string n
= Gogo::unpack_hidden_name(name
);
7617 bool is_address_taken
= (this->is_non_escaping_address_taken_
7618 && !this->is_in_heap());
7619 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
7620 NULL
, is_address_taken
,
7624 return this->backend_
;
7627 // Class Named_constant.
7629 // Set the type of a named constant. This is only used to set the
7630 // type to an error type.
7633 Named_constant::set_type(Type
* t
)
7635 go_assert(this->type_
== NULL
|| t
->is_error_type());
7639 // Traverse the initializer expression.
7642 Named_constant::traverse_expression(Traverse
* traverse
)
7644 return Expression::traverse(&this->expr_
, traverse
);
7647 // Determine the type of the constant.
7650 Named_constant::determine_type()
7652 if (this->type_
!= NULL
)
7654 Type_context
context(this->type_
, false);
7655 this->expr_
->determine_type(&context
);
7659 // A constant may have an abstract type.
7660 Type_context
context(NULL
, true);
7661 this->expr_
->determine_type(&context
);
7662 this->type_
= this->expr_
->type();
7663 go_assert(this->type_
!= NULL
);
7667 // Indicate that we found and reported an error for this constant.
7670 Named_constant::set_error()
7672 this->type_
= Type::make_error_type();
7673 this->expr_
= Expression::make_error(this->location_
);
7676 // Export a constant.
7679 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
7681 exp
->write_c_string("const ");
7682 exp
->write_string(name
);
7683 exp
->write_c_string(" ");
7684 if (!this->type_
->is_abstract())
7686 exp
->write_type(this->type_
);
7687 exp
->write_c_string(" ");
7689 exp
->write_c_string("= ");
7691 Export_function_body
efb(exp
, 0);
7692 if (!this->type_
->is_abstract())
7693 efb
.set_type_context(this->type_
);
7694 this->expr()->export_expression(&efb
);
7695 exp
->write_string(efb
.body());
7697 exp
->write_c_string("\n");
7700 // Import a constant.
7703 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
7706 imp
->require_c_string("const ");
7707 *pname
= imp
->read_identifier();
7708 imp
->require_c_string(" ");
7709 if (imp
->peek_char() == '=')
7713 *ptype
= imp
->read_type();
7714 imp
->require_c_string(" ");
7716 imp
->require_c_string("= ");
7717 *pexpr
= Expression::import_expression(imp
, imp
->location());
7718 imp
->require_semicolon_if_old_version();
7719 imp
->require_c_string("\n");
7722 // Get the backend representation.
7725 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
7727 if (this->bconst_
== NULL
)
7729 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
7730 Type
* type
= this->type();
7731 Location loc
= this->location();
7733 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
7734 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
7735 if (type
!= NULL
&& type
->is_numeric_type())
7737 Btype
* btype
= type
->get_backend(gogo
);
7738 std::string name
= const_no
->get_id(gogo
);
7740 gogo
->backend()->named_constant_expression(btype
, name
,
7743 this->bconst_
= const_decl
;
7745 return this->bconst_
;
7751 Type_declaration::add_method(const std::string
& name
, Function
* function
)
7753 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
7754 this->methods_
.push_back(ret
);
7758 // Add a method declaration.
7761 Type_declaration::add_method_declaration(const std::string
& name
,
7763 Function_type
* type
,
7766 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
7768 this->methods_
.push_back(ret
);
7772 // Return whether any methods are defined.
7775 Type_declaration::has_methods() const
7777 return !this->methods_
.empty();
7780 // Define methods for the real type.
7783 Type_declaration::define_methods(Named_type
* nt
)
7785 if (this->methods_
.empty())
7788 while (nt
->is_alias())
7790 Type
*t
= nt
->real_type()->forwarded();
7791 if (t
->named_type() != NULL
)
7792 nt
= t
->named_type();
7793 else if (t
->forward_declaration_type() != NULL
)
7795 Named_object
* no
= t
->forward_declaration_type()->named_object();
7796 Type_declaration
* td
= no
->type_declaration_value();
7797 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
7798 this->methods_
.end());
7799 this->methods_
.clear();
7804 for (std::vector
<Named_object
*>::const_iterator p
=
7805 this->methods_
.begin();
7806 p
!= this->methods_
.end();
7808 go_error_at((*p
)->location(),
7809 ("invalid receiver type "
7810 "(receiver must be a named type"));
7815 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
7816 p
!= this->methods_
.end();
7819 if ((*p
)->is_function_declaration()
7820 || !(*p
)->func_value()->is_sink())
7821 nt
->add_existing_method(*p
);
7825 // We are using the type. Return true if we should issue a warning.
7828 Type_declaration::using_type()
7830 bool ret
= !this->issued_warning_
;
7831 this->issued_warning_
= true;
7835 // Class Unknown_name.
7837 // Set the real named object.
7840 Unknown_name::set_real_named_object(Named_object
* no
)
7842 go_assert(this->real_named_object_
== NULL
);
7843 go_assert(!no
->is_unknown());
7844 this->real_named_object_
= no
;
7847 // Class Named_object.
7849 Named_object::Named_object(const std::string
& name
,
7850 const Package
* package
,
7851 Classification classification
)
7852 : name_(name
), package_(package
), classification_(classification
),
7853 is_redefinition_(false)
7855 if (Gogo::is_sink_name(name
))
7856 go_assert(classification
== NAMED_OBJECT_SINK
);
7859 // Make an unknown name. This is used by the parser. The name must
7860 // be resolved later. Unknown names are only added in the current
7864 Named_object::make_unknown_name(const std::string
& name
,
7867 Named_object
* named_object
= new Named_object(name
, NULL
,
7868 NAMED_OBJECT_UNKNOWN
);
7869 Unknown_name
* value
= new Unknown_name(location
);
7870 named_object
->u_
.unknown_value
= value
;
7871 return named_object
;
7877 Named_object::make_constant(const Typed_identifier
& tid
,
7878 const Package
* package
, Expression
* expr
,
7881 Named_object
* named_object
= new Named_object(tid
.name(), package
,
7882 NAMED_OBJECT_CONST
);
7883 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
7886 named_object
->u_
.const_value
= named_constant
;
7887 return named_object
;
7890 // Make a named type.
7893 Named_object::make_type(const std::string
& name
, const Package
* package
,
7894 Type
* type
, Location location
)
7896 Named_object
* named_object
= new Named_object(name
, package
,
7898 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
7899 named_object
->u_
.type_value
= named_type
;
7900 return named_object
;
7903 // Make a type declaration.
7906 Named_object::make_type_declaration(const std::string
& name
,
7907 const Package
* package
,
7910 Named_object
* named_object
= new Named_object(name
, package
,
7911 NAMED_OBJECT_TYPE_DECLARATION
);
7912 Type_declaration
* type_declaration
= new Type_declaration(location
);
7913 named_object
->u_
.type_declaration
= type_declaration
;
7914 return named_object
;
7920 Named_object::make_variable(const std::string
& name
, const Package
* package
,
7923 Named_object
* named_object
= new Named_object(name
, package
,
7925 named_object
->u_
.var_value
= variable
;
7926 return named_object
;
7929 // Make a result variable.
7932 Named_object::make_result_variable(const std::string
& name
,
7933 Result_variable
* result
)
7935 Named_object
* named_object
= new Named_object(name
, NULL
,
7936 NAMED_OBJECT_RESULT_VAR
);
7937 named_object
->u_
.result_var_value
= result
;
7938 return named_object
;
7941 // Make a sink. This is used for the special blank identifier _.
7944 Named_object::make_sink()
7946 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
7949 // Make a named function.
7952 Named_object::make_function(const std::string
& name
, const Package
* package
,
7955 Named_object
* named_object
= new Named_object(name
, package
,
7957 named_object
->u_
.func_value
= function
;
7958 return named_object
;
7961 // Make a function declaration.
7964 Named_object::make_function_declaration(const std::string
& name
,
7965 const Package
* package
,
7966 Function_type
* fntype
,
7969 Named_object
* named_object
= new Named_object(name
, package
,
7970 NAMED_OBJECT_FUNC_DECLARATION
);
7971 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
7972 named_object
->u_
.func_declaration_value
= func_decl
;
7973 return named_object
;
7979 Named_object::make_package(const std::string
& alias
, Package
* package
)
7981 Named_object
* named_object
= new Named_object(alias
, NULL
,
7982 NAMED_OBJECT_PACKAGE
);
7983 named_object
->u_
.package_value
= package
;
7984 return named_object
;
7987 // Return the name to use in an error message.
7990 Named_object::message_name() const
7992 if (this->package_
== NULL
)
7993 return Gogo::message_name(this->name_
);
7995 if (this->package_
->has_package_name())
7996 ret
= this->package_
->package_name();
7998 ret
= this->package_
->pkgpath();
7999 ret
= Gogo::message_name(ret
);
8001 ret
+= Gogo::message_name(this->name_
);
8005 // Set the type when a declaration is defined.
8008 Named_object::set_type_value(Named_type
* named_type
)
8010 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8011 Type_declaration
* td
= this->u_
.type_declaration
;
8012 td
->define_methods(named_type
);
8014 Named_object
* in_function
= td
->in_function(&index
);
8015 if (in_function
!= NULL
)
8016 named_type
->set_in_function(in_function
, index
);
8018 this->classification_
= NAMED_OBJECT_TYPE
;
8019 this->u_
.type_value
= named_type
;
8022 // Define a function which was previously declared.
8025 Named_object::set_function_value(Function
* function
)
8027 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8028 if (this->func_declaration_value()->has_descriptor())
8030 Expression
* descriptor
=
8031 this->func_declaration_value()->descriptor(NULL
, NULL
);
8032 function
->set_descriptor(descriptor
);
8034 this->classification_
= NAMED_OBJECT_FUNC
;
8035 // FIXME: We should free the old value.
8036 this->u_
.func_value
= function
;
8039 // Declare an unknown object as a type declaration.
8042 Named_object::declare_as_type()
8044 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8045 Unknown_name
* unk
= this->u_
.unknown_value
;
8046 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8047 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8051 // Return the location of a named object.
8054 Named_object::location() const
8056 switch (this->classification_
)
8059 case NAMED_OBJECT_UNINITIALIZED
:
8062 case NAMED_OBJECT_ERRONEOUS
:
8063 return Linemap::unknown_location();
8065 case NAMED_OBJECT_UNKNOWN
:
8066 return this->unknown_value()->location();
8068 case NAMED_OBJECT_CONST
:
8069 return this->const_value()->location();
8071 case NAMED_OBJECT_TYPE
:
8072 return this->type_value()->location();
8074 case NAMED_OBJECT_TYPE_DECLARATION
:
8075 return this->type_declaration_value()->location();
8077 case NAMED_OBJECT_VAR
:
8078 return this->var_value()->location();
8080 case NAMED_OBJECT_RESULT_VAR
:
8081 return this->result_var_value()->location();
8083 case NAMED_OBJECT_SINK
:
8086 case NAMED_OBJECT_FUNC
:
8087 return this->func_value()->location();
8089 case NAMED_OBJECT_FUNC_DECLARATION
:
8090 return this->func_declaration_value()->location();
8092 case NAMED_OBJECT_PACKAGE
:
8093 return this->package_value()->location();
8097 // Export a named object.
8100 Named_object::export_named_object(Export
* exp
) const
8102 switch (this->classification_
)
8105 case NAMED_OBJECT_UNINITIALIZED
:
8106 case NAMED_OBJECT_UNKNOWN
:
8109 case NAMED_OBJECT_ERRONEOUS
:
8112 case NAMED_OBJECT_CONST
:
8113 this->const_value()->export_const(exp
, this->name_
);
8116 case NAMED_OBJECT_TYPE
:
8117 // Types are handled by export::write_types.
8120 case NAMED_OBJECT_TYPE_DECLARATION
:
8121 go_error_at(this->type_declaration_value()->location(),
8122 "attempt to export %<%s%> which was declared but not defined",
8123 this->message_name().c_str());
8126 case NAMED_OBJECT_FUNC_DECLARATION
:
8127 this->func_declaration_value()->export_func(exp
, this->name_
);
8130 case NAMED_OBJECT_VAR
:
8131 this->var_value()->export_var(exp
, this->name_
);
8134 case NAMED_OBJECT_RESULT_VAR
:
8135 case NAMED_OBJECT_SINK
:
8138 case NAMED_OBJECT_FUNC
:
8139 this->func_value()->export_func(exp
, this->name_
);
8144 // Convert a variable to the backend representation.
8147 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8149 if (this->classification_
== NAMED_OBJECT_VAR
)
8150 return this->var_value()->get_backend_variable(gogo
, function
,
8151 this->package_
, this->name_
);
8152 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8153 return this->result_var_value()->get_backend_variable(gogo
, function
,
8159 // Return the external identifier for this object.
8162 Named_object::get_id(Gogo
* gogo
)
8164 go_assert(!this->is_variable()
8165 && !this->is_result_variable()
8166 && !this->is_type());
8167 std::string decl_name
;
8168 if (this->is_function_declaration()
8169 && !this->func_declaration_value()->asm_name().empty())
8170 decl_name
= this->func_declaration_value()->asm_name();
8173 std::string package_name
;
8174 if (this->package_
== NULL
)
8175 package_name
= gogo
->package_name();
8177 package_name
= this->package_
->package_name();
8179 // Note that this will be misleading if this is an unexported
8180 // method generated for an embedded imported type. In that case
8181 // the unexported method should have the package name of the
8182 // package from which it is imported, but we are going to give
8183 // it our package name. Fixing this would require knowing the
8184 // package name, but we only know the package path. It might be
8185 // better to use package paths here anyhow. This doesn't affect
8186 // the assembler code, because we always set that name in
8187 // Function::get_or_make_decl anyhow. FIXME.
8189 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
8191 Function_type
* fntype
;
8192 if (this->is_function())
8193 fntype
= this->func_value()->type();
8194 else if (this->is_function_declaration())
8195 fntype
= this->func_declaration_value()->type();
8198 if (fntype
!= NULL
&& fntype
->is_method())
8200 decl_name
.push_back('.');
8201 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
8207 // Get the backend representation for this named object.
8210 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8211 std::vector
<Btype
*>& type_decls
,
8212 std::vector
<Bfunction
*>& func_decls
)
8214 // If this is a definition, avoid trying to get the backend
8215 // representation, as that can crash.
8216 if (this->is_redefinition_
)
8218 go_assert(saw_errors());
8222 switch (this->classification_
)
8224 case NAMED_OBJECT_CONST
:
8225 if (!Gogo::is_erroneous_name(this->name_
))
8226 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8229 case NAMED_OBJECT_TYPE
:
8231 Named_type
* named_type
= this->u_
.type_value
;
8232 if (!Gogo::is_erroneous_name(this->name_
) && !named_type
->is_alias())
8233 type_decls
.push_back(named_type
->get_backend(gogo
));
8235 // We need to produce a type descriptor for every named
8236 // type, and for a pointer to every named type, since
8237 // other files or packages might refer to them. We need
8238 // to do this even for hidden types, because they might
8239 // still be returned by some function. Simply calling the
8240 // type_descriptor method is enough to create the type
8241 // descriptor, even though we don't do anything with it.
8242 if (this->package_
== NULL
&& !saw_errors())
8245 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8246 named_type
->gc_symbol_pointer(gogo
);
8247 Type
* pn
= Type::make_pointer_type(named_type
);
8248 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8249 pn
->gc_symbol_pointer(gogo
);
8254 case NAMED_OBJECT_TYPE_DECLARATION
:
8255 go_error_at(Linemap::unknown_location(),
8256 "reference to undefined type %qs",
8257 this->message_name().c_str());
8260 case NAMED_OBJECT_VAR
:
8261 case NAMED_OBJECT_RESULT_VAR
:
8262 case NAMED_OBJECT_SINK
:
8265 case NAMED_OBJECT_FUNC
:
8267 Function
* func
= this->u_
.func_value
;
8268 if (!Gogo::is_erroneous_name(this->name_
))
8269 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
8271 if (func
->block() != NULL
)
8272 func
->build(gogo
, this);
8276 case NAMED_OBJECT_ERRONEOUS
:
8286 Bindings::Bindings(Bindings
* enclosing
)
8287 : enclosing_(enclosing
), named_objects_(), bindings_()
8294 Bindings::clear_file_scope(Gogo
* gogo
)
8296 Contour::iterator p
= this->bindings_
.begin();
8297 while (p
!= this->bindings_
.end())
8300 if (p
->second
->package() != NULL
)
8302 else if (p
->second
->is_package())
8304 else if (p
->second
->is_function()
8305 && !p
->second
->func_value()->type()->is_method()
8306 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
8315 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
8316 p
= this->bindings_
.erase(p
);
8321 // Look up a symbol.
8324 Bindings::lookup(const std::string
& name
) const
8326 Contour::const_iterator p
= this->bindings_
.find(name
);
8327 if (p
!= this->bindings_
.end())
8328 return p
->second
->resolve();
8329 else if (this->enclosing_
!= NULL
)
8330 return this->enclosing_
->lookup(name
);
8335 // Look up a symbol locally.
8338 Bindings::lookup_local(const std::string
& name
) const
8340 Contour::const_iterator p
= this->bindings_
.find(name
);
8341 if (p
== this->bindings_
.end())
8346 // Remove an object from a set of bindings. This is used for a
8347 // special case in thunks for functions which call recover.
8350 Bindings::remove_binding(Named_object
* no
)
8352 Contour::iterator pb
= this->bindings_
.find(no
->name());
8353 go_assert(pb
!= this->bindings_
.end());
8354 this->bindings_
.erase(pb
);
8355 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
8356 pn
!= this->named_objects_
.end();
8361 this->named_objects_
.erase(pn
);
8368 // Add a method to the list of objects. This is not added to the
8369 // lookup table. This is so that we have a single list of objects
8370 // declared at the top level, which we walk through when it's time to
8371 // convert to trees.
8374 Bindings::add_method(Named_object
* method
)
8376 this->named_objects_
.push_back(method
);
8379 // Add a generic Named_object to a Contour.
8382 Bindings::add_named_object_to_contour(Contour
* contour
,
8383 Named_object
* named_object
)
8385 go_assert(named_object
== named_object
->resolve());
8386 const std::string
& name(named_object
->name());
8387 go_assert(!Gogo::is_sink_name(name
));
8389 std::pair
<Contour::iterator
, bool> ins
=
8390 contour
->insert(std::make_pair(name
, named_object
));
8393 // The name was already there.
8394 if (named_object
->package() != NULL
8395 && ins
.first
->second
->package() == named_object
->package()
8396 && (ins
.first
->second
->classification()
8397 == named_object
->classification()))
8399 // This is a second import of the same object.
8400 return ins
.first
->second
;
8402 ins
.first
->second
= this->new_definition(ins
.first
->second
,
8404 return ins
.first
->second
;
8408 // Don't push declarations on the list. We push them on when
8409 // and if we find the definitions. That way we genericize the
8410 // functions in order.
8411 if (!named_object
->is_type_declaration()
8412 && !named_object
->is_function_declaration()
8413 && !named_object
->is_unknown())
8414 this->named_objects_
.push_back(named_object
);
8415 return named_object
;
8419 // We had an existing named object OLD_OBJECT, and we've seen a new
8420 // one NEW_OBJECT with the same name. FIXME: This does not free the
8421 // new object when we don't need it.
8424 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
8426 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
8430 switch (old_object
->classification())
8433 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8436 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8439 case Named_object::NAMED_OBJECT_UNKNOWN
:
8441 Named_object
* real
= old_object
->unknown_value()->real_named_object();
8443 return this->new_definition(real
, new_object
);
8444 go_assert(!new_object
->is_unknown());
8445 old_object
->unknown_value()->set_real_named_object(new_object
);
8446 if (!new_object
->is_type_declaration()
8447 && !new_object
->is_function_declaration())
8448 this->named_objects_
.push_back(new_object
);
8452 case Named_object::NAMED_OBJECT_CONST
:
8455 case Named_object::NAMED_OBJECT_TYPE
:
8456 if (new_object
->is_type_declaration())
8460 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8461 if (new_object
->is_type_declaration())
8463 if (new_object
->is_type())
8465 old_object
->set_type_value(new_object
->type_value());
8466 new_object
->type_value()->set_named_object(old_object
);
8467 this->named_objects_
.push_back(old_object
);
8472 case Named_object::NAMED_OBJECT_VAR
:
8473 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8474 // We have already given an error in the parser for cases where
8475 // one parameter or result variable redeclares another one.
8476 if ((new_object
->is_variable()
8477 && new_object
->var_value()->is_parameter())
8478 || new_object
->is_result_variable())
8482 case Named_object::NAMED_OBJECT_SINK
:
8485 case Named_object::NAMED_OBJECT_FUNC
:
8488 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8490 // We declare the hash and equality functions before defining
8491 // them, because we sometimes see that we need the declaration
8492 // while we are in the middle of a different function.
8494 // We declare the main function before the user defines it, to
8495 // give better error messages.
8497 // We declare inline functions before we define them, as we
8498 // only define them if we need them.
8499 if (new_object
->is_function()
8500 && ((Linemap::is_predeclared_location(old_object
->location())
8501 && Linemap::is_predeclared_location(new_object
->location()))
8502 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
8503 && Linemap::is_unknown_location(old_object
->location()))
8504 || (new_object
->package() != NULL
8505 && old_object
->func_declaration_value()->has_imported_body()
8506 && new_object
->func_value()->is_inline_only())))
8508 Function_type
* old_type
=
8509 old_object
->func_declaration_value()->type();
8510 Function_type
* new_type
= new_object
->func_value()->type();
8511 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
8513 Function_declaration
* fd
=
8514 old_object
->func_declaration_value();
8515 go_assert(fd
->asm_name().empty());
8516 old_object
->set_function_value(new_object
->func_value());
8517 this->named_objects_
.push_back(old_object
);
8524 case Named_object::NAMED_OBJECT_PACKAGE
:
8528 std::string n
= old_object
->message_name();
8530 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
8532 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
8534 old_object
->set_is_redefinition();
8535 new_object
->set_is_redefinition();
8537 if (!Linemap::is_unknown_location(old_object
->location())
8538 && !Linemap::is_predeclared_location(old_object
->location()))
8539 go_inform(old_object
->location(), "previous definition of %qs was here",
8545 // Add a named type.
8548 Bindings::add_named_type(Named_type
* named_type
)
8550 return this->add_named_object(named_type
->named_object());
8556 Bindings::add_function(const std::string
& name
, const Package
* package
,
8559 return this->add_named_object(Named_object::make_function(name
, package
,
8563 // Add a function declaration.
8566 Bindings::add_function_declaration(const std::string
& name
,
8567 const Package
* package
,
8568 Function_type
* type
,
8571 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
8573 return this->add_named_object(no
);
8576 // Define a type which was previously declared.
8579 Bindings::define_type(Named_object
* no
, Named_type
* type
)
8581 no
->set_type_value(type
);
8582 this->named_objects_
.push_back(no
);
8585 // Mark all local variables as used. This is used for some types of
8589 Bindings::mark_locals_used()
8591 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
8592 p
!= this->named_objects_
.end();
8594 if ((*p
)->is_variable())
8595 (*p
)->var_value()->set_is_used();
8598 // Traverse bindings.
8601 Bindings::traverse(Traverse
* traverse
, bool is_global
)
8603 unsigned int traverse_mask
= traverse
->traverse_mask();
8605 // We don't use an iterator because we permit the traversal to add
8606 // new global objects.
8607 const unsigned int e_or_t
= (Traverse::traverse_expressions
8608 | Traverse::traverse_types
);
8609 const unsigned int e_or_t_or_s
= (e_or_t
8610 | Traverse::traverse_statements
);
8611 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
8613 Named_object
* p
= this->named_objects_
[i
];
8614 int t
= TRAVERSE_CONTINUE
;
8615 switch (p
->classification())
8617 case Named_object::NAMED_OBJECT_CONST
:
8618 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
8619 t
= traverse
->constant(p
, is_global
);
8620 if (t
== TRAVERSE_CONTINUE
8621 && (traverse_mask
& e_or_t
) != 0)
8623 Type
* tc
= p
->const_value()->type();
8625 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
8626 return TRAVERSE_EXIT
;
8627 t
= p
->const_value()->traverse_expression(traverse
);
8631 case Named_object::NAMED_OBJECT_VAR
:
8632 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8633 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
8634 t
= traverse
->variable(p
);
8635 if (t
== TRAVERSE_CONTINUE
8636 && (traverse_mask
& e_or_t
) != 0)
8638 if (p
->is_result_variable()
8639 || p
->var_value()->has_type())
8641 Type
* tv
= (p
->is_variable()
8642 ? p
->var_value()->type()
8643 : p
->result_var_value()->type());
8645 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
8646 return TRAVERSE_EXIT
;
8649 if (t
== TRAVERSE_CONTINUE
8650 && (traverse_mask
& e_or_t_or_s
) != 0
8651 && p
->is_variable())
8652 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
8655 case Named_object::NAMED_OBJECT_FUNC
:
8656 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
8657 t
= traverse
->function(p
);
8659 if (t
== TRAVERSE_CONTINUE
8661 & (Traverse::traverse_variables
8662 | Traverse::traverse_constants
8663 | Traverse::traverse_functions
8664 | Traverse::traverse_blocks
8665 | Traverse::traverse_statements
8666 | Traverse::traverse_expressions
8667 | Traverse::traverse_types
)) != 0)
8668 t
= p
->func_value()->traverse(traverse
);
8671 case Named_object::NAMED_OBJECT_PACKAGE
:
8672 // These are traversed in Gogo::traverse.
8673 go_assert(is_global
);
8676 case Named_object::NAMED_OBJECT_TYPE
:
8677 if ((traverse_mask
& e_or_t
) != 0)
8678 t
= Type::traverse(p
->type_value(), traverse
);
8681 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8682 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8683 case Named_object::NAMED_OBJECT_UNKNOWN
:
8684 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8687 case Named_object::NAMED_OBJECT_SINK
:
8692 if (t
== TRAVERSE_EXIT
)
8693 return TRAVERSE_EXIT
;
8696 // If we need to traverse types, check the function declarations,
8697 // which have types. Also check any methods of a type declaration.
8698 if ((traverse_mask
& e_or_t
) != 0)
8700 for (Bindings::const_declarations_iterator p
=
8701 this->begin_declarations();
8702 p
!= this->end_declarations();
8705 if (p
->second
->is_function_declaration())
8707 if (Type::traverse(p
->second
->func_declaration_value()->type(),
8710 return TRAVERSE_EXIT
;
8712 else if (p
->second
->is_type_declaration())
8714 const std::vector
<Named_object
*>* methods
=
8715 p
->second
->type_declaration_value()->methods();
8716 for (std::vector
<Named_object
*>::const_iterator pm
=
8718 pm
!= methods
->end();
8721 Named_object
* no
= *pm
;
8723 if (no
->is_function())
8724 t
= no
->func_value()->type();
8725 else if (no
->is_function_declaration())
8726 t
= no
->func_declaration_value()->type();
8729 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
8730 return TRAVERSE_EXIT
;
8736 // Traverse function declarations when needed.
8737 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
8739 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
8740 p
!= this->end_declarations();
8743 if (p
->second
->is_function_declaration())
8745 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
8746 return TRAVERSE_EXIT
;
8751 return TRAVERSE_CONTINUE
;
8756 // Clear any references to this label.
8761 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
8762 p
!= this->refs_
.end();
8765 this->refs_
.clear();
8768 // Get the backend representation for a label.
8771 Label::get_backend_label(Translate_context
* context
)
8773 if (this->blabel_
== NULL
)
8775 Function
* function
= context
->function()->func_value();
8776 Bfunction
* bfunction
= function
->get_decl();
8777 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
8780 return this->blabel_
;
8783 // Return an expression for the address of this label.
8786 Label::get_addr(Translate_context
* context
, Location location
)
8788 Blabel
* label
= this->get_backend_label(context
);
8789 return context
->backend()->label_address(label
, location
);
8792 // Return the dummy label that represents any instance of the blank label.
8795 Label::create_dummy_label()
8797 static Label
* dummy_label
;
8798 if (dummy_label
== NULL
)
8800 dummy_label
= new Label("_");
8801 dummy_label
->set_is_used();
8806 // Class Unnamed_label.
8808 // Get the backend representation for an unnamed label.
8811 Unnamed_label::get_blabel(Translate_context
* context
)
8813 if (this->blabel_
== NULL
)
8815 Function
* function
= context
->function()->func_value();
8816 Bfunction
* bfunction
= function
->get_decl();
8817 this->blabel_
= context
->backend()->label(bfunction
, "",
8820 return this->blabel_
;
8823 // Return a statement which defines this unnamed label.
8826 Unnamed_label::get_definition(Translate_context
* context
)
8828 Blabel
* blabel
= this->get_blabel(context
);
8829 return context
->backend()->label_definition_statement(blabel
);
8832 // Return a goto statement to this unnamed label.
8835 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
8837 Blabel
* blabel
= this->get_blabel(context
);
8838 return context
->backend()->goto_statement(blabel
, location
);
8843 Package::Package(const std::string
& pkgpath
,
8844 const std::string
& pkgpath_symbol
, Location location
)
8845 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
8846 package_name_(), bindings_(new Bindings(NULL
)),
8849 go_assert(!pkgpath
.empty());
8852 // Set the package name.
8855 Package::set_package_name(const std::string
& package_name
, Location location
)
8857 go_assert(!package_name
.empty());
8858 if (this->package_name_
.empty())
8859 this->package_name_
= package_name
;
8860 else if (this->package_name_
!= package_name
)
8861 go_error_at(location
,
8862 ("saw two different packages with "
8863 "the same package path %s: %s, %s"),
8864 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
8865 package_name
.c_str());
8868 // Return the pkgpath symbol, which is a prefix for symbols defined in
8872 Package::pkgpath_symbol() const
8874 if (this->pkgpath_symbol_
.empty())
8875 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
8876 return this->pkgpath_symbol_
;
8879 // Set the package path symbol.
8882 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
8884 go_assert(!pkgpath_symbol
.empty());
8885 if (this->pkgpath_symbol_
.empty())
8886 this->pkgpath_symbol_
= pkgpath_symbol
;
8888 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
8891 // Note that symbol from this package was and qualified by ALIAS.
8894 Package::note_usage(const std::string
& alias
) const
8896 Aliases::const_iterator p
= this->aliases_
.find(alias
);
8897 go_assert(p
!= this->aliases_
.end());
8898 p
->second
->note_usage();
8901 // Forget a given usage. If forgetting this usage means this package becomes
8902 // unused, report that error.
8905 Package::forget_usage(Expression
* usage
) const
8907 if (this->fake_uses_
.empty())
8910 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
8911 go_assert(p
!= this->fake_uses_
.end());
8912 this->fake_uses_
.erase(p
);
8914 if (this->fake_uses_
.empty())
8915 go_error_at(this->location(), "imported and not used: %s",
8916 Gogo::message_name(this->package_name()).c_str());
8919 // Clear the used field for the next file. If the only usages of this package
8920 // are possibly fake, keep the fake usages for lowering.
8923 Package::clear_used()
8925 std::string dot_alias
= "." + this->package_name();
8926 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
8927 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
8928 this->fake_uses_
.clear();
8930 this->aliases_
.clear();
8934 Package::add_alias(const std::string
& alias
, Location location
)
8936 Aliases::const_iterator p
= this->aliases_
.find(alias
);
8937 if (p
== this->aliases_
.end())
8939 std::pair
<Aliases::iterator
, bool> ret
;
8940 ret
= this->aliases_
.insert(std::make_pair(alias
,
8941 new Package_alias(location
)));
8947 // Determine types of constants. Everything else in a package
8948 // (variables, function declarations) should already have a fixed
8949 // type. Constants may have abstract types.
8952 Package::determine_types()
8954 Bindings
* bindings
= this->bindings_
;
8955 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
8956 p
!= bindings
->end_definitions();
8959 if ((*p
)->is_const())
8960 (*p
)->const_value()->determine_type();
8968 Traverse::~Traverse()
8970 if (this->types_seen_
!= NULL
)
8971 delete this->types_seen_
;
8972 if (this->expressions_seen_
!= NULL
)
8973 delete this->expressions_seen_
;
8976 // Record that we are looking at a type, and return true if we have
8980 Traverse::remember_type(const Type
* type
)
8982 if (type
->is_error_type())
8984 go_assert((this->traverse_mask() & traverse_types
) != 0
8985 || (this->traverse_mask() & traverse_expressions
) != 0);
8986 // We mostly only have to remember named types. But it turns out
8987 // that an interface type can refer to itself without using a name
8988 // by relying on interface inheritance, as in
8990 // type I interface { F() interface{I} }
8992 // Similarly it is possible for array types to refer to themselves
8993 // without a name, e.g.
8995 // var x [uintptr(unsafe.Sizeof(&x))]byte
8997 if (type
->classification() != Type::TYPE_NAMED
8998 && type
->classification() != Type::TYPE_ARRAY
8999 && type
->classification() != Type::TYPE_INTERFACE
)
9001 if (this->types_seen_
== NULL
)
9002 this->types_seen_
= new Types_seen();
9003 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9007 // Record that we are looking at an expression, and return true if we
9008 // have already seen it. NB: this routine used to assert if the traverse
9009 // mask did not include expressions/types -- this is no longer the case,
9010 // since it can be useful to remember specific expressions during
9011 // walks that only cover statements.
9014 Traverse::remember_expression(const Expression
* expression
)
9016 if (this->expressions_seen_
== NULL
)
9017 this->expressions_seen_
= new Expressions_seen();
9018 std::pair
<Expressions_seen::iterator
, bool> ins
=
9019 this->expressions_seen_
->insert(expression
);
9023 // The default versions of these functions should never be called: the
9024 // traversal mask indicates which functions may be called.
9027 Traverse::variable(Named_object
*)
9033 Traverse::constant(Named_object
*, bool)
9039 Traverse::function(Named_object
*)
9045 Traverse::block(Block
*)
9051 Traverse::statement(Block
*, size_t*, Statement
*)
9057 Traverse::expression(Expression
**)
9063 Traverse::type(Type
*)
9069 Traverse::function_declaration(Named_object
*)
9074 // Class Statement_inserter.
9077 Statement_inserter::insert(Statement
* s
)
9079 if (this->statements_added_
!= NULL
)
9080 this->statements_added_
->insert(s
);
9082 if (this->block_
!= NULL
)
9084 go_assert(this->pindex_
!= NULL
);
9085 this->block_
->insert_statement_before(*this->pindex_
, s
);
9088 else if (this->var_
!= NULL
)
9089 this->var_
->add_preinit_statement(this->gogo_
, s
);
9091 go_assert(saw_errors());