1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #include "filenames.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
17 #include "go-optimize.h"
20 #include "statements.h"
21 #include "expressions.h"
30 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
35 globals_(new Bindings(NULL
)),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
58 debug_optimization_(false),
59 nil_check_size_threshold_(4096),
62 specific_type_functions_(),
63 specific_type_functions_are_written_(false),
64 named_types_are_converted_(false),
67 imported_inlinable_functions_(),
68 imported_inline_functions_()
70 const Location loc
= Linemap::predeclared_location();
72 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
73 RUNTIME_TYPE_KIND_UINT8
);
74 this->add_named_type(uint8_type
);
75 this->add_named_type(Type::make_integer_type("uint16", true, 16,
76 RUNTIME_TYPE_KIND_UINT16
));
77 this->add_named_type(Type::make_integer_type("uint32", true, 32,
78 RUNTIME_TYPE_KIND_UINT32
));
79 this->add_named_type(Type::make_integer_type("uint64", true, 64,
80 RUNTIME_TYPE_KIND_UINT64
));
82 this->add_named_type(Type::make_integer_type("int8", false, 8,
83 RUNTIME_TYPE_KIND_INT8
));
84 this->add_named_type(Type::make_integer_type("int16", false, 16,
85 RUNTIME_TYPE_KIND_INT16
));
86 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
87 RUNTIME_TYPE_KIND_INT32
);
88 this->add_named_type(int32_type
);
89 this->add_named_type(Type::make_integer_type("int64", false, 64,
90 RUNTIME_TYPE_KIND_INT64
));
92 this->add_named_type(Type::make_float_type("float32", 32,
93 RUNTIME_TYPE_KIND_FLOAT32
));
94 this->add_named_type(Type::make_float_type("float64", 64,
95 RUNTIME_TYPE_KIND_FLOAT64
));
97 this->add_named_type(Type::make_complex_type("complex64", 64,
98 RUNTIME_TYPE_KIND_COMPLEX64
));
99 this->add_named_type(Type::make_complex_type("complex128", 128,
100 RUNTIME_TYPE_KIND_COMPLEX128
));
102 int int_type_size
= pointer_size
;
103 if (int_type_size
< 32)
105 this->add_named_type(Type::make_integer_type("uint", true,
107 RUNTIME_TYPE_KIND_UINT
));
108 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
109 RUNTIME_TYPE_KIND_INT
);
110 this->add_named_type(int_type
);
112 this->add_named_type(Type::make_integer_type("uintptr", true,
114 RUNTIME_TYPE_KIND_UINTPTR
));
116 // "byte" is an alias for "uint8".
117 uint8_type
->integer_type()->set_is_byte();
118 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
120 byte_type
->type_value()->set_is_alias();
121 this->add_named_type(byte_type
->type_value());
123 // "rune" is an alias for "int32".
124 int32_type
->integer_type()->set_is_rune();
125 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
127 rune_type
->type_value()->set_is_alias();
128 this->add_named_type(rune_type
->type_value());
130 this->add_named_type(Type::make_named_bool_type());
132 this->add_named_type(Type::make_named_string_type());
134 // "error" is interface { Error() string }.
136 Typed_identifier_list
*methods
= new Typed_identifier_list
;
137 Typed_identifier_list
*results
= new Typed_identifier_list
;
138 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
139 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
140 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
141 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
142 error_iface
->finalize_methods();
143 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
144 this->add_named_type(error_type
);
147 this->globals_
->add_constant(Typed_identifier("true",
148 Type::make_boolean_type(),
151 Expression::make_boolean(true, loc
),
153 this->globals_
->add_constant(Typed_identifier("false",
154 Type::make_boolean_type(),
157 Expression::make_boolean(false, loc
),
160 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
163 Expression::make_nil(loc
),
166 Type
* abstract_int_type
= Type::make_abstract_integer_type();
167 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
170 Expression::make_iota(),
173 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
174 new_type
->set_is_varargs();
175 new_type
->set_is_builtin();
176 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
178 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
179 make_type
->set_is_varargs();
180 make_type
->set_is_builtin();
181 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
183 Typed_identifier_list
* len_result
= new Typed_identifier_list();
184 len_result
->push_back(Typed_identifier("", int_type
, loc
));
185 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
187 len_type
->set_is_builtin();
188 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
190 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
191 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
192 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
194 cap_type
->set_is_builtin();
195 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
197 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
198 print_type
->set_is_varargs();
199 print_type
->set_is_builtin();
200 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
202 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
203 print_type
->set_is_varargs();
204 print_type
->set_is_builtin();
205 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
207 Type
*empty
= Type::make_empty_interface_type(loc
);
208 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
209 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
210 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
212 panic_type
->set_is_builtin();
213 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
215 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
216 recover_result
->push_back(Typed_identifier("", empty
, loc
));
217 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
220 recover_type
->set_is_builtin();
221 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
223 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
224 close_type
->set_is_varargs();
225 close_type
->set_is_builtin();
226 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
228 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
229 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
230 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
232 copy_type
->set_is_varargs();
233 copy_type
->set_is_builtin();
234 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
236 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
237 append_type
->set_is_varargs();
238 append_type
->set_is_builtin();
239 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
241 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
242 complex_type
->set_is_varargs();
243 complex_type
->set_is_builtin();
244 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
246 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
247 real_type
->set_is_varargs();
248 real_type
->set_is_builtin();
249 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
251 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
252 imag_type
->set_is_varargs();
253 imag_type
->set_is_builtin();
254 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
256 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
257 delete_type
->set_is_varargs();
258 delete_type
->set_is_builtin();
259 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
263 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
265 go_assert(!pkgpath
.empty());
266 return go_encode_id(pkgpath
);
269 // Return a hash code for a string, given a starting hash.
272 Gogo::hash_string(const std::string
& s
, unsigned int h
)
274 const char* p
= s
.data();
275 size_t len
= s
.length();
276 for (; len
> 0; --len
)
284 // Get the package path to use for type reflection data. This should
285 // ideally be unique across the entire link.
288 Gogo::pkgpath() const
290 go_assert(this->pkgpath_set_
);
291 return this->pkgpath_
;
294 // Set the package path from the -fgo-pkgpath command line option.
297 Gogo::set_pkgpath(const std::string
& arg
)
299 go_assert(!this->pkgpath_set_
);
300 this->pkgpath_
= arg
;
301 this->pkgpath_set_
= true;
302 this->pkgpath_from_option_
= true;
305 // Get the package path to use for symbol names.
308 Gogo::pkgpath_symbol() const
310 go_assert(this->pkgpath_set_
);
311 return this->pkgpath_symbol_
;
314 // Set the unique prefix to use to determine the package path, from
315 // the -fgo-prefix command line option.
318 Gogo::set_prefix(const std::string
& arg
)
320 go_assert(!this->prefix_from_option_
);
322 this->prefix_from_option_
= true;
325 // Given a name which may or may not have been hidden, append the
326 // appropriate version of the name to the result string. Take care
327 // to avoid creating a sequence that will be rejected by go_encode_id
328 // (avoid ..u, ..U, ..z).
330 Gogo::append_possibly_hidden_name(std::string
*result
, const std::string
& name
)
332 // FIXME: This adds in pkgpath twice for hidden symbols, which is
334 if (!Gogo::is_hidden_name(name
))
339 std::string pkgpath
= Gogo::hidden_name_pkgpath(name
);
340 char lastR
= result
->at(result
->length() - 1);
341 char firstP
= pkgpath
.at(0);
342 if (lastR
== '.' && (firstP
== 'u' || firstP
== 'U' || firstP
== 'z'))
346 n
.append(Gogo::unpack_hidden_name(name
));
351 // Munge name for use in an error message.
354 Gogo::message_name(const std::string
& name
)
356 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
359 // Get the package name.
362 Gogo::package_name() const
364 go_assert(this->package_
!= NULL
);
365 return this->package_
->package_name();
368 // Set the package name.
371 Gogo::set_package_name(const std::string
& package_name
,
374 if (this->package_
!= NULL
)
376 if (this->package_
->package_name() != package_name
)
377 go_error_at(location
, "expected package %<%s%>",
378 Gogo::message_name(this->package_
->package_name()).c_str());
382 // Now that we know the name of the package we are compiling, set
383 // the package path to use for reflect.Type.PkgPath and global
385 if (this->pkgpath_set_
)
386 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
389 if (!this->prefix_from_option_
&& package_name
== "main")
391 this->pkgpath_
= package_name
;
392 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
396 if (!this->prefix_from_option_
)
397 this->prefix_
= "go";
398 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
399 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
400 + Gogo::pkgpath_for_symbol(package_name
));
402 this->pkgpath_set_
= true;
405 this->package_
= this->register_package(this->pkgpath_
,
406 this->pkgpath_symbol_
, location
);
407 this->package_
->set_package_name(package_name
, location
);
409 if (this->is_main_package())
411 // Declare "main" as a function which takes no parameters and
413 Location uloc
= Linemap::unknown_location();
414 this->declare_function(Gogo::pack_hidden_name("main", false),
415 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
420 // Return whether this is the "main" package. This is not true if
421 // -fgo-pkgpath or -fgo-prefix was used.
424 Gogo::is_main_package() const
426 return (this->package_name() == "main"
427 && !this->pkgpath_from_option_
428 && !this->prefix_from_option_
);
434 Gogo::import_package(const std::string
& filename
,
435 const std::string
& local_name
,
436 bool is_local_name_exported
,
440 if (filename
.empty())
442 go_error_at(location
, "import path is empty");
446 const char *pf
= filename
.data();
447 const char *pend
= pf
+ filename
.length();
451 int adv
= Lex::fetch_char(pf
, &c
);
454 go_error_at(location
, "import path contains invalid UTF-8 sequence");
459 go_error_at(location
, "import path contains NUL");
462 if (c
< 0x20 || c
== 0x7f)
464 go_error_at(location
, "import path contains control character");
469 go_error_at(location
, "import path contains backslash; use slash");
472 if (Lex::is_unicode_space(c
))
474 go_error_at(location
, "import path contains space character");
477 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
479 go_error_at(location
,
480 "import path contains invalid character '%c'", c
);
486 if (IS_ABSOLUTE_PATH(filename
.c_str()))
488 go_error_at(location
, "import path cannot be absolute path");
492 if (local_name
== "init")
493 go_error_at(location
, "cannot import package as init");
495 if (filename
== "unsafe")
497 this->import_unsafe(local_name
, is_local_name_exported
, location
);
498 this->current_file_imported_unsafe_
= true;
502 Imports::const_iterator p
= this->imports_
.find(filename
);
503 if (p
!= this->imports_
.end())
505 Package
* package
= p
->second
;
506 package
->set_location(location
);
507 std::string ln
= local_name
;
508 bool is_ln_exported
= is_local_name_exported
;
511 ln
= package
->package_name();
512 go_assert(!ln
.empty());
513 is_ln_exported
= Lex::is_exported_name(ln
);
519 Bindings
* bindings
= package
->bindings();
520 for (Bindings::const_declarations_iterator p
=
521 bindings
->begin_declarations();
522 p
!= bindings
->end_declarations();
524 this->add_dot_import_object(p
->second
);
525 std::string dot_alias
= "." + package
->package_name();
526 package
->add_alias(dot_alias
, location
);
530 package
->add_alias(ln
, location
);
531 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
532 this->package_
->bindings()->add_package(ln
, package
);
537 Import::Stream
* stream
= Import::open_package(filename
, location
,
538 this->relative_import_path_
);
542 go_error_at(location
, "import file %qs not found", filename
.c_str());
546 Import
* imp
= new Import(stream
, location
);
547 imp
->register_builtin_types(this);
548 Package
* package
= imp
->import(this, local_name
, is_local_name_exported
);
551 if (package
->pkgpath() == this->pkgpath())
552 go_error_at(location
,
553 ("imported package uses same package path as package "
554 "being compiled (see -fgo-pkgpath option)"));
556 this->imports_
.insert(std::make_pair(filename
, package
));
562 // FIXME: we never delete imp; we may need it for inlinable functions.
566 Gogo::lookup_init(const std::string
& init_name
)
568 Import_init
tmp("", init_name
, -1);
569 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
570 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
573 // Add an import control function for an imported package to the list.
576 Gogo::add_import_init_fn(const std::string
& package_name
,
577 const std::string
& init_name
, int prio
)
579 for (Import_init_set::iterator p
=
580 this->imported_init_fns_
.begin();
581 p
!= this->imported_init_fns_
.end();
584 Import_init
*ii
= (*p
);
585 if (ii
->init_name() == init_name
)
587 // If a test of package P1, built as part of package P1,
588 // imports package P2, and P2 imports P1 (perhaps
589 // indirectly), then we will see the same import name with
590 // different import priorities. That is OK, so don't give
591 // an error about it.
592 if (ii
->package_name() != package_name
)
594 go_error_at(Linemap::unknown_location(),
595 "duplicate package initialization name %qs",
596 Gogo::message_name(init_name
).c_str());
597 go_inform(Linemap::unknown_location(), "used by package %qs",
598 Gogo::message_name(ii
->package_name()).c_str());
599 go_inform(Linemap::unknown_location(), " and by package %qs",
600 Gogo::message_name(package_name
).c_str());
602 ii
->set_priority(prio
);
607 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
608 this->imported_init_fns_
.insert(nii
);
611 // Return whether we are at the global binding level.
614 Gogo::in_global_scope() const
616 return this->functions_
.empty();
619 // Return the current binding contour.
622 Gogo::current_bindings()
624 if (!this->functions_
.empty())
625 return this->functions_
.back().blocks
.back()->bindings();
626 else if (this->package_
!= NULL
)
627 return this->package_
->bindings();
629 return this->globals_
;
633 Gogo::current_bindings() const
635 if (!this->functions_
.empty())
636 return this->functions_
.back().blocks
.back()->bindings();
637 else if (this->package_
!= NULL
)
638 return this->package_
->bindings();
640 return this->globals_
;
644 Gogo::update_init_priority(Import_init
* ii
,
645 std::set
<const Import_init
*>* visited
)
650 for (std::set
<std::string
>::const_iterator pci
=
651 ii
->precursors().begin();
652 pci
!= ii
->precursors().end();
655 Import_init
* succ
= this->lookup_init(*pci
);
656 if (visited
->find(succ
) == visited
->end())
657 update_init_priority(succ
, visited
);
658 succ_prior
= std::max(succ_prior
, succ
->priority());
660 if (ii
->priority() <= succ_prior
)
661 ii
->set_priority(succ_prior
+ 1);
665 Gogo::recompute_init_priorities()
667 std::set
<Import_init
*> nonroots
;
669 for (Import_init_set::const_iterator p
=
670 this->imported_init_fns_
.begin();
671 p
!= this->imported_init_fns_
.end();
674 const Import_init
*ii
= *p
;
675 for (std::set
<std::string
>::const_iterator pci
=
676 ii
->precursors().begin();
677 pci
!= ii
->precursors().end();
680 Import_init
* ii
= this->lookup_init(*pci
);
685 // Recursively update priorities starting at roots.
686 std::set
<const Import_init
*> visited
;
687 for (Import_init_set::iterator p
=
688 this->imported_init_fns_
.begin();
689 p
!= this->imported_init_fns_
.end();
692 Import_init
* ii
= *p
;
693 if (nonroots
.find(ii
) != nonroots
.end())
695 update_init_priority(ii
, &visited
);
699 // Add statements to INIT_STMTS which run the initialization
700 // functions for imported packages. This is only used for the "main"
704 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
706 go_assert(this->is_main_package());
708 if (this->imported_init_fns_
.empty())
711 Location unknown_loc
= Linemap::unknown_location();
712 Function_type
* func_type
=
713 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
714 Btype
* fntype
= func_type
->get_backend_fntype(this);
716 // Recompute init priorities based on a walk of the init graph.
717 recompute_init_priorities();
719 // We must call them in increasing priority order.
720 std::vector
<const Import_init
*> v
;
721 for (Import_init_set::const_iterator p
=
722 this->imported_init_fns_
.begin();
723 p
!= this->imported_init_fns_
.end();
726 if ((*p
)->priority() < 0)
727 go_error_at(Linemap::unknown_location(),
728 "internal error: failed to set init priority for %s",
729 (*p
)->package_name().c_str());
732 std::sort(v
.begin(), v
.end(), priority_compare
);
734 // We build calls to the init functions, which take no arguments.
735 std::vector
<Bexpression
*> empty_args
;
736 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
740 const Import_init
* ii
= *p
;
741 std::string user_name
= ii
->package_name() + ".init";
742 const std::string
& init_name(ii
->init_name());
743 const unsigned int flags
=
744 (Backend::function_is_visible
745 | Backend::function_is_declaration
746 | Backend::function_is_inlinable
);
747 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
749 Bexpression
* pfunc_code
=
750 this->backend()->function_code_expression(pfunc
, unknown_loc
);
751 Bexpression
* pfunc_call
=
752 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
754 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
759 // Register global variables with the garbage collector. We need to
760 // register all variables which can hold a pointer value. They become
761 // roots during the mark phase. We build a struct that is easy to
762 // hook into a list of roots.
764 // type gcRoot struct {
765 // decl unsafe.Pointer // Pointer to variable.
766 // size uintptr // Total size of variable.
767 // ptrdata uintptr // Length of variable's gcdata.
768 // gcdata *byte // Pointer mask.
771 // type gcRootList struct {
777 // The last entry in the roots array has a NULL decl field.
780 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
781 std::vector
<Bstatement
*>& init_stmts
,
784 if (var_gc
.empty() && this->gc_roots_
.empty())
787 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
788 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
789 Type
* byte_type
= this->lookup_global("byte")->type_value();
790 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
791 Struct_type
* root_type
=
792 Type::make_builtin_struct_type(4,
794 "size", uintptr_type
,
795 "ptrdata", uintptr_type
,
796 "gcdata", pointer_byte_type
);
798 Location builtin_loc
= Linemap::predeclared_location();
799 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
800 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
802 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
803 root_array_type
->set_is_array_incomparable();
805 Type
* int_type
= Type::lookup_integer_type("int");
806 Struct_type
* root_list_type
=
807 Type::make_builtin_struct_type(3,
810 "roots", root_array_type
);
812 // Build an initializer for the roots array.
814 Expression_list
* roots_init
= new Expression_list();
816 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
820 Expression_list
* init
= new Expression_list();
822 Location no_loc
= (*p
)->location();
823 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
824 Expression
* decl_addr
=
825 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
826 decl_addr
->unary_expression()->set_does_not_escape();
827 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
828 init
->push_back(decl_addr
);
831 Expression::make_type_info(decl
->type(),
832 Expression::TYPE_INFO_SIZE
);
833 init
->push_back(size
);
835 Expression
* ptrdata
=
836 Expression::make_type_info(decl
->type(),
837 Expression::TYPE_INFO_BACKEND_PTRDATA
);
838 init
->push_back(ptrdata
);
840 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
841 init
->push_back(gcdata
);
843 Expression
* root_ctor
=
844 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
845 roots_init
->push_back(root_ctor
);
848 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
849 p
!= this->gc_roots_
.end();
852 Expression_list
*init
= new Expression_list();
854 Expression
* expr
= *p
;
855 Location eloc
= expr
->location();
856 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
858 Type
* type
= expr
->type()->points_to();
859 go_assert(type
!= NULL
);
862 Expression::make_type_info(type
,
863 Expression::TYPE_INFO_SIZE
);
864 init
->push_back(size
);
866 Expression
* ptrdata
=
867 Expression::make_type_info(type
,
868 Expression::TYPE_INFO_BACKEND_PTRDATA
);
869 init
->push_back(ptrdata
);
871 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
872 init
->push_back(gcdata
);
874 Expression
* root_ctor
=
875 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
876 roots_init
->push_back(root_ctor
);
879 // Build a constructor for the struct.
881 Expression_list
* root_list_init
= new Expression_list();
882 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
883 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
886 Expression
* roots_ctor
=
887 Expression::make_array_composite_literal(root_array_type
, roots_init
,
889 root_list_init
->push_back(roots_ctor
);
891 Expression
* root_list_ctor
=
892 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
895 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
897 root_addr
->unary_expression()->set_is_gc_root();
898 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
899 builtin_loc
, 1, root_addr
);
901 Translate_context
context(this, NULL
, NULL
, NULL
);
902 Bexpression
* bcall
= register_roots
->get_backend(&context
);
903 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
906 // Build the decl for the initialization function.
909 Gogo::initialization_function_decl()
911 std::string name
= this->get_init_fn_name();
912 Location loc
= this->package_
->location();
914 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
915 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
916 return Named_object::make_function(name
, NULL
, initfn
);
919 // Create the magic initialization function. CODE_STMT is the
920 // code that it needs to run.
923 Gogo::create_initialization_function(Named_object
* initfn
,
924 Bstatement
* code_stmt
)
926 // Make sure that we thought we needed an initialization function,
927 // as otherwise we will not have reported it in the export data.
928 go_assert(this->is_main_package() || this->need_init_fn_
);
931 initfn
= this->initialization_function_decl();
933 // Bind the initialization function code to a block.
934 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
935 Location pkg_loc
= this->package_
->location();
936 std::vector
<Bvariable
*> vars
;
937 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
939 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
941 go_assert(saw_errors());
947 // Given an expression, collect all the global variables defined in
948 // this package that it references.
950 class Find_vars
: public Traverse
953 // The list of variables we accumulate.
954 typedef Unordered_set(Named_object
*) Vars
;
956 // A hash table we use to avoid looping. The index is a
957 // Named_object* or a Temporary_statement*. We only look through
958 // objects defined in this package.
959 typedef Unordered_set(const void*) Seen_objects
;
963 : Traverse(traverse_expressions
),
964 vars_(), seen_objects_()
967 // An iterator through the variables found, after the traversal.
968 typedef Vars::const_iterator const_iterator
;
972 { return this->vars_
.begin(); }
976 { return this->vars_
.end(); }
979 expression(Expression
**);
982 // Accumulated variables.
984 // Objects we have already seen.
985 Seen_objects seen_objects_
;
988 // Collect global variables referenced by EXPR. Look through function
989 // calls and variable initializations.
992 Find_vars::expression(Expression
** pexpr
)
994 Expression
* e
= *pexpr
;
996 Var_expression
* ve
= e
->var_expression();
999 Named_object
* v
= ve
->named_object();
1000 if (!v
->is_variable() || v
->package() != NULL
)
1002 // This is a result parameter or a variable defined in a
1003 // different package. Either way we don't care about it.
1004 return TRAVERSE_CONTINUE
;
1007 std::pair
<Seen_objects::iterator
, bool> ins
=
1008 this->seen_objects_
.insert(v
);
1011 // We've seen this variable before.
1012 return TRAVERSE_CONTINUE
;
1015 if (v
->var_value()->is_global())
1016 this->vars_
.insert(v
);
1018 Expression
* init
= v
->var_value()->init();
1021 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1022 return TRAVERSE_EXIT
;
1026 // We traverse the code of any function or bound method we see. Note that
1027 // this means that we will traverse the code of a function or bound method
1028 // whose address is taken even if it is not called.
1029 Func_expression
* fe
= e
->func_expression();
1030 Bound_method_expression
* bme
= e
->bound_method_expression();
1031 if (fe
!= NULL
|| bme
!= NULL
)
1033 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1034 if (f
->is_function() && f
->package() == NULL
)
1036 std::pair
<Seen_objects::iterator
, bool> ins
=
1037 this->seen_objects_
.insert(f
);
1040 // This is the first time we have seen this name.
1041 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1042 return TRAVERSE_EXIT
;
1047 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1050 Temporary_statement
* ts
= tre
->statement();
1051 Expression
* init
= ts
->init();
1054 std::pair
<Seen_objects::iterator
, bool> ins
=
1055 this->seen_objects_
.insert(ts
);
1058 // This is the first time we have seen this temporary
1060 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1061 return TRAVERSE_EXIT
;
1066 return TRAVERSE_CONTINUE
;
1069 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1072 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1075 Find_vars find_vars
;
1077 Expression::traverse(&expr
, &find_vars
);
1078 if (preinit
!= NULL
)
1079 preinit
->traverse(&find_vars
);
1082 Expression
* init
= dep
->var_value()->init();
1084 Expression::traverse(&init
, &find_vars
);
1085 if (dep
->var_value()->has_pre_init())
1086 dep
->var_value()->preinit()->traverse(&find_vars
);
1089 for (Find_vars::const_iterator p
= find_vars
.begin();
1090 p
!= find_vars
.end();
1099 // Sort variable initializations. If the initialization expression
1100 // for variable A refers directly or indirectly to the initialization
1101 // expression for variable B, then we must initialize B before A.
1107 : var_(NULL
), init_(NULL
), refs_(NULL
), dep_count_(0)
1110 Var_init(Named_object
* var
, Bstatement
* init
)
1111 : var_(var
), init_(init
), refs_(NULL
), dep_count_(0)
1114 // Return the variable.
1117 { return this->var_
; }
1119 // Return the initialization expression.
1122 { return this->init_
; }
1126 add_ref(Named_object
* var
);
1128 // The variables which this variable's initializers refer to.
1129 const std::vector
<Named_object
*>*
1131 { return this->refs_
; }
1133 // Clear the references, if any.
1137 // Return the number of remaining dependencies.
1140 { return this->dep_count_
; }
1142 // Increment the number of dependencies.
1145 { ++this->dep_count_
; }
1147 // Decrement the number of dependencies.
1150 { --this->dep_count_
; }
1153 // The variable being initialized.
1155 // The backend initialization statement.
1157 // Variables this refers to.
1158 std::vector
<Named_object
*>* refs_
;
1159 // The number of initializations this is dependent on. A variable
1160 // initialization should not be emitted if any of its dependencies
1161 // have not yet been resolved.
1168 Var_init::add_ref(Named_object
* var
)
1170 if (this->refs_
== NULL
)
1171 this->refs_
= new std::vector
<Named_object
*>;
1172 this->refs_
->push_back(var
);
1175 // Clear the references, if any.
1178 Var_init::clear_refs()
1180 if (this->refs_
!= NULL
)
1187 // For comparing Var_init keys in a map.
1190 operator<(const Var_init
& v1
, const Var_init
& v2
)
1191 { return v1
.var()->name() < v2
.var()->name(); }
1193 typedef std::list
<Var_init
> Var_inits
;
1195 // Sort the variable initializations. The rule we follow is that we
1196 // emit them in the order they appear in the array, except that if the
1197 // initialization expression for a variable V1 depends upon another
1198 // variable V2 then we initialize V1 after V2.
1201 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1203 if (var_inits
->empty())
1206 std::map
<Named_object
*, Var_init
*> var_to_init
;
1208 // A mapping from a variable initialization to a set of
1209 // variable initializations that depend on it.
1210 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1211 Init_deps init_deps
;
1212 bool init_loop
= false;
1214 // Compute all variable references.
1215 for (Var_inits::iterator pvar
= var_inits
->begin();
1216 pvar
!= var_inits
->end();
1219 Named_object
* var
= pvar
->var();
1220 var_to_init
[var
] = &*pvar
;
1222 Find_vars find_vars
;
1223 Expression
* init
= var
->var_value()->init();
1225 Expression::traverse(&init
, &find_vars
);
1226 if (var
->var_value()->has_pre_init())
1227 var
->var_value()->preinit()->traverse(&find_vars
);
1228 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1231 Expression
* dinit
= dep
->var_value()->init();
1233 Expression::traverse(&dinit
, &find_vars
);
1234 if (dep
->var_value()->has_pre_init())
1235 dep
->var_value()->preinit()->traverse(&find_vars
);
1237 for (Find_vars::const_iterator p
= find_vars
.begin();
1238 p
!= find_vars
.end();
1243 // Add dependencies to init_deps, and check for cycles.
1244 for (Var_inits::iterator pvar
= var_inits
->begin();
1245 pvar
!= var_inits
->end();
1248 Named_object
* var
= pvar
->var();
1250 const std::vector
<Named_object
*>* refs
= pvar
->refs();
1253 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1254 pdep
!= refs
->end();
1257 Named_object
* dep
= *pdep
;
1260 // This is a reference from a variable to itself, which
1261 // may indicate a loop. We only report an error if
1262 // there is an initializer and there is no dependency.
1263 // When there is no initializer, it means that the
1264 // preinitializer sets the variable, which will appear
1265 // to be a loop here.
1266 if (var
->var_value()->init() != NULL
1267 && gogo
->var_depends_on(var
->var_value()) == NULL
)
1268 go_error_at(var
->location(),
1269 ("initialization expression for %qs "
1270 "depends upon itself"),
1271 var
->message_name().c_str());
1276 Var_init
* dep_init
= var_to_init
[dep
];
1277 if (dep_init
== NULL
)
1279 // This is a dependency on some variable that doesn't
1280 // have an initializer, so for purposes of
1281 // initialization ordering this is irrelevant.
1285 init_deps
[*dep_init
].insert(&(*pvar
));
1286 pvar
->add_dependency();
1288 // Check for cycles.
1289 const std::vector
<Named_object
*>* deprefs
= dep_init
->refs();
1290 if (deprefs
== NULL
)
1292 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1294 pdepdep
!= deprefs
->end();
1297 if (*pdepdep
== var
)
1299 go_error_at(var
->location(),
1300 ("initialization expressions for %qs and "
1301 "%qs depend upon each other"),
1302 var
->message_name().c_str(),
1303 dep
->message_name().c_str());
1304 go_inform(dep
->location(), "%qs defined here",
1305 dep
->message_name().c_str());
1313 var_to_init
.clear();
1314 for (Var_inits::iterator pvar
= var_inits
->begin();
1315 pvar
!= var_inits
->end();
1319 // If there are no dependencies then the declaration order is sorted.
1320 if (!init_deps
.empty() && !init_loop
)
1322 // Otherwise, sort variable initializations by emitting all variables with
1323 // no dependencies in declaration order. VAR_INITS is already in
1324 // declaration order.
1326 while (!var_inits
->empty())
1328 Var_inits::iterator v1
;;
1329 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1331 if (v1
->dep_count() == 0)
1334 go_assert(v1
!= var_inits
->end());
1336 // V1 either has no dependencies or its dependencies have already
1337 // been emitted, add it to READY next. When V1 is emitted, remove
1338 // a dependency from each V that depends on V1.
1339 ready
.splice(ready
.end(), *var_inits
, v1
);
1341 Init_deps::iterator p1
= init_deps
.find(*v1
);
1342 if (p1
!= init_deps
.end())
1344 std::set
<Var_init
*> resolved
= p1
->second
;
1345 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1346 pv
!= resolved
.end();
1348 (*pv
)->remove_dependency();
1349 init_deps
.erase(p1
);
1352 var_inits
->swap(ready
);
1353 go_assert(init_deps
.empty());
1357 // Give an error if the initialization expression for VAR depends on
1358 // itself. We only check if INIT is not NULL and there is no
1359 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1360 // which we will interpret as a loop.
1363 Gogo::check_self_dep(Named_object
* var
)
1365 Expression
* init
= var
->var_value()->init();
1366 Block
* preinit
= var
->var_value()->preinit();
1367 Named_object
* dep
= this->var_depends_on(var
->var_value());
1370 && expression_requires(init
, preinit
, NULL
, var
))
1371 go_error_at(var
->location(),
1372 "initialization expression for %qs depends upon itself",
1373 var
->message_name().c_str());
1376 // Write out the global definitions.
1379 Gogo::write_globals()
1381 this->build_interface_method_tables();
1383 Bindings
* bindings
= this->current_bindings();
1385 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1386 p
!= bindings
->end_declarations();
1389 // If any function declarations needed a descriptor, make sure
1391 Named_object
* no
= p
->second
;
1392 if (no
->is_function_declaration())
1393 no
->func_declaration_value()->build_backend_descriptor(this);
1396 // Lists of globally declared types, variables, constants, and functions
1397 // that must be defined.
1398 std::vector
<Btype
*> type_decls
;
1399 std::vector
<Bvariable
*> var_decls
;
1400 std::vector
<Bexpression
*> const_decls
;
1401 std::vector
<Bfunction
*> func_decls
;
1403 // The init function declaration and associated Bfunction, if necessary.
1404 Named_object
* init_fndecl
= NULL
;
1405 Bfunction
* init_bfn
= NULL
;
1407 std::vector
<Bstatement
*> init_stmts
;
1408 std::vector
<Bstatement
*> var_init_stmts
;
1410 if (this->is_main_package())
1412 init_fndecl
= this->initialization_function_decl();
1413 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1414 this->init_imports(init_stmts
, init_bfn
);
1417 // A list of variable initializations.
1418 Var_inits var_inits
;
1420 // A list of variables which need to be registered with the garbage
1422 size_t count_definitions
= bindings
->size_definitions();
1423 std::vector
<Named_object
*> var_gc
;
1424 var_gc
.reserve(count_definitions
);
1426 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1427 p
!= bindings
->end_definitions();
1430 Named_object
* no
= *p
;
1431 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1433 // There is nothing to do for a package.
1434 if (no
->is_package())
1437 // There is nothing to do for an object which was imported from
1438 // a different package into the global scope.
1439 if (no
->package() != NULL
)
1442 // Skip blank named functions and constants.
1443 if ((no
->is_function() && no
->func_value()->is_sink())
1444 || (no
->is_const() && no
->const_value()->is_sink()))
1447 // There is nothing useful we can output for constants which
1448 // have ideal or non-integral type.
1451 Type
* type
= no
->const_value()->type();
1453 type
= no
->const_value()->expr()->type();
1454 if (type
->is_abstract() || !type
->is_numeric_type())
1458 if (!no
->is_variable())
1459 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1462 Variable
* var
= no
->var_value();
1463 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1464 var_decls
.push_back(bvar
);
1466 // Check for a sink variable, which may be used to run an
1467 // initializer purely for its side effects.
1468 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1470 Bstatement
* var_init_stmt
= NULL
;
1471 if (!var
->has_pre_init())
1473 // If the backend representation of the variable initializer is
1474 // constant, we can just set the initial value using
1475 // global_var_set_init instead of during the init() function.
1476 // The initializer is constant if it is the zero-value of the
1477 // variable's type or if the initial value is an immutable value
1478 // that is not copied to the heap.
1479 bool is_static_initializer
= false;
1480 if (var
->init() == NULL
)
1481 is_static_initializer
= true;
1484 Type
* var_type
= var
->type();
1485 Expression
* init
= var
->init();
1486 Expression
* init_cast
=
1487 Expression::make_cast(var_type
, init
, var
->location());
1488 is_static_initializer
= init_cast
->is_static_initializer();
1491 // Non-constant variable initializations might need to create
1492 // temporary variables, which will need the initialization
1493 // function as context.
1494 Named_object
* var_init_fn
;
1495 if (is_static_initializer
)
1499 if (init_fndecl
== NULL
)
1501 init_fndecl
= this->initialization_function_decl();
1502 Function
* func
= init_fndecl
->func_value();
1503 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1505 var_init_fn
= init_fndecl
;
1507 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1509 if (var_binit
== NULL
)
1511 else if (is_static_initializer
)
1513 if (expression_requires(var
->init(), NULL
,
1514 this->var_depends_on(var
), no
))
1515 go_error_at(no
->location(),
1516 "initialization expression for %qs depends "
1518 no
->message_name().c_str());
1519 this->backend()->global_variable_set_init(bvar
, var_binit
);
1523 this->backend()->expression_statement(init_bfn
, var_binit
);
1526 Location loc
= var
->location();
1527 Bexpression
* var_expr
=
1528 this->backend()->var_expression(bvar
, loc
);
1530 this->backend()->assignment_statement(init_bfn
, var_expr
,
1536 // We are going to create temporary variables which
1537 // means that we need an fndecl.
1538 if (init_fndecl
== NULL
)
1539 init_fndecl
= this->initialization_function_decl();
1541 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1542 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1545 if (var_init_stmt
!= NULL
)
1547 if (var
->init() == NULL
&& !var
->has_pre_init())
1548 var_init_stmts
.push_back(var_init_stmt
);
1550 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1552 else if (this->var_depends_on(var
) != NULL
)
1554 // This variable is initialized from something that is
1555 // not in its init or preinit. This variable needs to
1556 // participate in dependency analysis sorting, in case
1557 // some other variable depends on this one.
1558 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1559 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1560 Bstatement
* zero_stmt
=
1561 this->backend()->expression_statement(init_bfn
, zero
);
1562 var_inits
.push_back(Var_init(no
, zero_stmt
));
1565 // Collect a list of all global variables with pointers,
1566 // to register them for the garbage collector.
1567 if (!is_sink
&& var
->type()->has_pointer())
1569 // Avoid putting runtime.gcRoots itself on the list.
1570 if (this->compiling_runtime()
1571 && this->package_name() == "runtime"
1572 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1573 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1576 var_gc
.push_back(no
);
1581 // Output inline functions, which are in different packages.
1582 for (std::vector
<Named_object
*>::const_iterator p
=
1583 this->imported_inline_functions_
.begin();
1584 p
!= this->imported_inline_functions_
.end();
1586 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1588 // Register global variables with the garbage collector.
1589 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1591 // Simple variable initializations, after all variables are
1593 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1595 // Complete variable initializations, first sorting them into a
1597 if (!var_inits
.empty())
1599 sort_var_inits(this, &var_inits
);
1600 for (Var_inits::const_iterator p
= var_inits
.begin();
1601 p
!= var_inits
.end();
1603 init_stmts
.push_back(p
->init());
1606 // After all the variables are initialized, call the init
1607 // functions if there are any. Init functions take no arguments, so
1608 // we pass in EMPTY_ARGS to call them.
1609 std::vector
<Bexpression
*> empty_args
;
1610 for (std::vector
<Named_object
*>::const_iterator p
=
1611 this->init_functions_
.begin();
1612 p
!= this->init_functions_
.end();
1615 Location func_loc
= (*p
)->location();
1616 Function
* func
= (*p
)->func_value();
1617 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1618 Bexpression
* func_code
=
1619 this->backend()->function_code_expression(initfn
, func_loc
);
1620 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1623 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1624 init_stmts
.push_back(ist
);
1627 // Set up a magic function to do all the initialization actions.
1628 // This will be called if this package is imported.
1629 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1630 if (this->need_init_fn_
|| this->is_main_package())
1633 this->create_initialization_function(init_fndecl
, init_fncode
);
1634 if (init_fndecl
!= NULL
)
1635 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1638 // We should not have seen any new bindings created during the conversion.
1639 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1641 // Define all globally declared values.
1643 this->backend()->write_global_definitions(type_decls
, const_decls
,
1644 func_decls
, var_decls
);
1647 // Return the current block.
1650 Gogo::current_block()
1652 if (this->functions_
.empty())
1655 return this->functions_
.back().blocks
.back();
1658 // Look up a name in the current binding contour. If PFUNCTION is not
1659 // NULL, set it to the function in which the name is defined, or NULL
1660 // if the name is defined in global scope.
1663 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1665 if (pfunction
!= NULL
)
1668 if (Gogo::is_sink_name(name
))
1669 return Named_object::make_sink();
1671 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1672 p
!= this->functions_
.rend();
1675 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1678 if (pfunction
!= NULL
)
1679 *pfunction
= p
->function
;
1684 if (this->package_
!= NULL
)
1686 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1689 if (ret
->package() != NULL
)
1691 std::string dot_alias
= "." + ret
->package()->package_name();
1692 ret
->package()->note_usage(dot_alias
);
1698 // We do not look in the global namespace. If we did, the global
1699 // namespace would effectively hide names which were defined in
1700 // package scope which we have not yet seen. Instead,
1701 // define_global_names is called after parsing is over to connect
1702 // undefined names at package scope with names defined at global
1708 // Look up a name in the current block, without searching enclosing
1712 Gogo::lookup_in_block(const std::string
& name
) const
1714 go_assert(!this->functions_
.empty());
1715 go_assert(!this->functions_
.back().blocks
.empty());
1716 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1719 // Look up a name in the global namespace.
1722 Gogo::lookup_global(const char* name
) const
1724 return this->globals_
->lookup(name
);
1727 // Add an imported package.
1730 Gogo::add_imported_package(const std::string
& real_name
,
1731 const std::string
& alias_arg
,
1732 bool is_alias_exported
,
1733 const std::string
& pkgpath
,
1734 const std::string
& pkgpath_symbol
,
1736 bool* padd_to_globals
)
1738 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1739 ret
->set_package_name(real_name
, location
);
1741 *padd_to_globals
= false;
1743 if (alias_arg
== "_")
1745 else if (alias_arg
== ".")
1747 *padd_to_globals
= true;
1748 std::string dot_alias
= "." + real_name
;
1749 ret
->add_alias(dot_alias
, location
);
1753 std::string alias
= alias_arg
;
1757 is_alias_exported
= Lex::is_exported_name(alias
);
1759 ret
->add_alias(alias
, location
);
1760 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1761 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1762 if (!no
->is_package())
1769 // Register a package. This package may or may not be imported. This
1770 // returns the Package structure for the package, creating if it
1771 // necessary. LOCATION is the location of the import statement that
1772 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1773 // for names in the package; it may be the empty string, in which case
1774 // we either get it later or make a guess when we need it.
1777 Gogo::register_package(const std::string
& pkgpath
,
1778 const std::string
& pkgpath_symbol
, Location location
)
1780 Package
* package
= NULL
;
1781 std::pair
<Packages::iterator
, bool> ins
=
1782 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1785 // We have seen this package name before.
1786 package
= ins
.first
->second
;
1787 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1788 if (!pkgpath_symbol
.empty())
1789 package
->set_pkgpath_symbol(pkgpath_symbol
);
1790 if (Linemap::is_unknown_location(package
->location()))
1791 package
->set_location(location
);
1795 // First time we have seen this package name.
1796 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1797 go_assert(ins
.first
->second
== NULL
);
1798 ins
.first
->second
= package
;
1804 // Return the pkgpath symbol for a package, given the pkgpath.
1807 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1809 Packages::iterator p
= this->packages_
.find(pkgpath
);
1810 go_assert(p
!= this->packages_
.end());
1811 return p
->second
->pkgpath_symbol();
1814 // Start compiling a function.
1817 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1818 bool add_method_to_type
, Location location
)
1820 bool at_top_level
= this->functions_
.empty();
1822 Block
* block
= new Block(NULL
, location
);
1824 Named_object
* enclosing
= (at_top_level
1826 : this->functions_
.back().function
);
1828 Function
* function
= new Function(type
, enclosing
, block
, location
);
1830 if (type
->is_method())
1832 const Typed_identifier
* receiver
= type
->receiver();
1833 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1834 true, true, location
);
1835 std::string rname
= receiver
->name();
1836 unsigned rcounter
= 0;
1838 // We need to give a nameless receiver parameter a synthesized name to
1839 // avoid having it clash with some other nameless param. FIXME.
1840 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
1842 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1845 const Typed_identifier_list
* parameters
= type
->parameters();
1846 bool is_varargs
= type
->is_varargs();
1847 unsigned pcounter
= 0;
1848 if (parameters
!= NULL
)
1850 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1851 p
!= parameters
->end();
1854 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1856 if (is_varargs
&& p
+ 1 == parameters
->end())
1857 param
->set_is_varargs_parameter();
1859 std::string pname
= p
->name();
1861 // We need to give each nameless parameter a non-empty name to avoid
1862 // having it clash with some other nameless param. FIXME.
1863 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
1865 block
->bindings()->add_variable(pname
, NULL
, param
);
1869 function
->create_result_variables(this);
1871 const std::string
* pname
;
1872 std::string nested_name
;
1873 bool is_init
= false;
1874 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1876 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1877 || (type
->results() != NULL
&& !type
->results()->empty()))
1878 go_error_at(location
,
1879 "func init must have no arguments and no return values");
1880 // There can be multiple "init" functions, so give them each a
1882 nested_name
= this->init_function_name();
1883 pname
= &nested_name
;
1886 else if (!name
.empty())
1890 // Invent a name for a nested function.
1891 nested_name
= this->nested_function_name(enclosing
);
1892 pname
= &nested_name
;
1896 if (Gogo::is_sink_name(*pname
))
1898 std::string
sname(this->sink_function_name());
1899 ret
= Named_object::make_function(sname
, NULL
, function
);
1900 ret
->func_value()->set_is_sink();
1902 if (!type
->is_method())
1903 ret
= this->package_
->bindings()->add_named_object(ret
);
1904 else if (add_method_to_type
)
1906 // We should report errors even for sink methods.
1907 Type
* rtype
= type
->receiver()->type();
1908 // Avoid points_to and deref to avoid getting an error if
1909 // the type is not yet defined.
1910 if (rtype
->classification() == Type::TYPE_POINTER
)
1911 rtype
= rtype
->points_to();
1912 while (rtype
->named_type() != NULL
1913 && rtype
->named_type()->is_alias())
1914 rtype
= rtype
->named_type()->real_type()->forwarded();
1915 if (rtype
->is_error_type())
1917 else if (rtype
->named_type() != NULL
)
1919 if (rtype
->named_type()->named_object()->package() != NULL
)
1920 go_error_at(type
->receiver()->location(),
1921 "may not define methods on non-local type");
1923 else if (rtype
->forward_declaration_type() != NULL
)
1925 // Go ahead and add the method in case we need to report
1926 // an error when we see the definition.
1927 rtype
->forward_declaration_type()->add_existing_method(ret
);
1930 go_error_at(type
->receiver()->location(),
1931 ("invalid receiver type "
1932 "(receiver must be a named type)"));
1935 else if (!type
->is_method())
1937 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1938 if (!ret
->is_function() || ret
->func_value() != function
)
1940 // Redefinition error. Invent a name to avoid knockon
1942 std::string
rname(this->redefined_function_name());
1943 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
1948 if (!add_method_to_type
)
1949 ret
= Named_object::make_function(name
, NULL
, function
);
1952 go_assert(at_top_level
);
1953 Type
* rtype
= type
->receiver()->type();
1955 while (rtype
->named_type() != NULL
1956 && rtype
->named_type()->is_alias())
1957 rtype
= rtype
->named_type()->real_type()->forwarded();
1959 // We want to look through the pointer created by the
1960 // parser, without getting an error if the type is not yet
1962 if (rtype
->classification() == Type::TYPE_POINTER
)
1963 rtype
= rtype
->points_to();
1965 while (rtype
->named_type() != NULL
1966 && rtype
->named_type()->is_alias())
1967 rtype
= rtype
->named_type()->real_type()->forwarded();
1969 if (rtype
->is_error_type())
1970 ret
= Named_object::make_function(name
, NULL
, function
);
1971 else if (rtype
->named_type() != NULL
)
1973 if (rtype
->named_type()->named_object()->package() != NULL
)
1975 go_error_at(type
->receiver()->location(),
1976 "may not define methods on non-local type");
1977 ret
= Named_object::make_function(name
, NULL
, function
);
1981 ret
= rtype
->named_type()->add_method(name
, function
);
1982 if (!ret
->is_function())
1984 // Redefinition error.
1985 ret
= Named_object::make_function(name
, NULL
, function
);
1989 else if (rtype
->forward_declaration_type() != NULL
)
1991 Named_object
* type_no
=
1992 rtype
->forward_declaration_type()->named_object();
1993 if (type_no
->is_unknown())
1995 // If we are seeing methods it really must be a
1996 // type. Declare it as such. An alternative would
1997 // be to support lists of methods for unknown
1998 // expressions. Either way the error messages if
1999 // this is not a type are going to get confusing.
2000 Named_object
* declared
=
2001 this->declare_package_type(type_no
->name(),
2002 type_no
->location());
2004 == type_no
->unknown_value()->real_named_object());
2006 ret
= rtype
->forward_declaration_type()->add_method(name
,
2011 go_error_at(type
->receiver()->location(),
2012 ("invalid receiver type (receiver must "
2013 "be a named type)"));
2014 ret
= Named_object::make_function(name
, NULL
, function
);
2017 this->package_
->bindings()->add_method(ret
);
2020 this->functions_
.resize(this->functions_
.size() + 1);
2021 Open_function
& of(this->functions_
.back());
2023 of
.blocks
.push_back(block
);
2027 this->init_functions_
.push_back(ret
);
2028 this->need_init_fn_
= true;
2034 // Finish compiling a function.
2037 Gogo::finish_function(Location location
)
2039 this->finish_block(location
);
2040 go_assert(this->functions_
.back().blocks
.empty());
2041 this->functions_
.pop_back();
2044 // Return the current function.
2047 Gogo::current_function() const
2049 go_assert(!this->functions_
.empty());
2050 return this->functions_
.back().function
;
2053 // Start a new block.
2056 Gogo::start_block(Location location
)
2058 go_assert(!this->functions_
.empty());
2059 Block
* block
= new Block(this->current_block(), location
);
2060 this->functions_
.back().blocks
.push_back(block
);
2066 Gogo::finish_block(Location location
)
2068 go_assert(!this->functions_
.empty());
2069 go_assert(!this->functions_
.back().blocks
.empty());
2070 Block
* block
= this->functions_
.back().blocks
.back();
2071 this->functions_
.back().blocks
.pop_back();
2072 block
->set_end_location(location
);
2076 // Add an erroneous name.
2079 Gogo::add_erroneous_name(const std::string
& name
)
2081 return this->package_
->bindings()->add_erroneous_name(name
);
2084 // Add an unknown name.
2087 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2089 return this->package_
->bindings()->add_unknown_name(name
, location
);
2092 // Declare a function.
2095 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2098 if (!type
->is_method())
2099 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2103 // We don't bother to add this to the list of global
2105 Type
* rtype
= type
->receiver()->type();
2107 while (rtype
->named_type() != NULL
2108 && rtype
->named_type()->is_alias())
2109 rtype
= rtype
->named_type()->real_type()->forwarded();
2111 // We want to look through the pointer created by the
2112 // parser, without getting an error if the type is not yet
2114 if (rtype
->classification() == Type::TYPE_POINTER
)
2115 rtype
= rtype
->points_to();
2117 while (rtype
->named_type() != NULL
2118 && rtype
->named_type()->is_alias())
2119 rtype
= rtype
->named_type()->real_type()->forwarded();
2121 if (rtype
->is_error_type())
2123 else if (rtype
->named_type() != NULL
)
2124 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2126 else if (rtype
->forward_declaration_type() != NULL
)
2128 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2129 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2133 go_error_at(type
->receiver()->location(),
2134 "invalid receiver type (receiver must be a named type)");
2135 return Named_object::make_erroneous_name(name
);
2140 // Add a label definition.
2143 Gogo::add_label_definition(const std::string
& label_name
,
2146 go_assert(!this->functions_
.empty());
2147 Function
* func
= this->functions_
.back().function
->func_value();
2148 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2149 this->add_statement(Statement::make_label_statement(label
, location
));
2153 // Add a label reference.
2156 Gogo::add_label_reference(const std::string
& label_name
,
2157 Location location
, bool issue_goto_errors
)
2159 go_assert(!this->functions_
.empty());
2160 Function
* func
= this->functions_
.back().function
->func_value();
2161 return func
->add_label_reference(this, label_name
, location
,
2165 // Return the current binding state.
2168 Gogo::bindings_snapshot(Location location
)
2170 return new Bindings_snapshot(this->current_block(), location
);
2176 Gogo::add_statement(Statement
* statement
)
2178 go_assert(!this->functions_
.empty()
2179 && !this->functions_
.back().blocks
.empty());
2180 this->functions_
.back().blocks
.back()->add_statement(statement
);
2186 Gogo::add_block(Block
* block
, Location location
)
2188 go_assert(!this->functions_
.empty()
2189 && !this->functions_
.back().blocks
.empty());
2190 Statement
* statement
= Statement::make_block_statement(block
, location
);
2191 this->functions_
.back().blocks
.back()->add_statement(statement
);
2197 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2200 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2206 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2208 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2210 if (!this->in_global_scope() && no
->is_type())
2212 Named_object
* f
= this->functions_
.back().function
;
2214 if (f
->is_function())
2215 index
= f
->func_value()->new_local_type_index();
2218 no
->type_value()->set_in_function(f
, index
);
2222 // Add a named type.
2225 Gogo::add_named_type(Named_type
* type
)
2227 go_assert(this->in_global_scope());
2228 this->current_bindings()->add_named_type(type
);
2234 Gogo::declare_type(const std::string
& name
, Location location
)
2236 Bindings
* bindings
= this->current_bindings();
2237 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2238 if (!this->in_global_scope() && no
->is_type_declaration())
2240 Named_object
* f
= this->functions_
.back().function
;
2242 if (f
->is_function())
2243 index
= f
->func_value()->new_local_type_index();
2246 no
->type_declaration_value()->set_in_function(f
, index
);
2251 // Declare a type at the package level.
2254 Gogo::declare_package_type(const std::string
& name
, Location location
)
2256 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2259 // Declare a function at the package level.
2262 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2265 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2269 // Add a function declaration to the list of functions we may want to
2273 Gogo::add_imported_inlinable_function(Named_object
* no
)
2275 go_assert(no
->is_function_declaration());
2276 Function_declaration
* fd
= no
->func_declaration_value();
2277 if (fd
->is_on_inlinable_list())
2279 this->imported_inlinable_functions_
.push_back(no
);
2280 fd
->set_is_on_inlinable_list();
2283 // Define a type which was already declared.
2286 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2288 this->current_bindings()->define_type(no
, type
);
2294 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2296 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2299 // In a function the middle-end wants to see a DECL_EXPR node.
2301 && no
->is_variable()
2302 && !no
->var_value()->is_parameter()
2303 && !this->functions_
.empty())
2304 this->add_statement(Statement::make_variable_declaration(no
));
2310 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2312 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2315 go_assert(strlen(tag
) < 10);
2316 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2323 // Add a sink--a reference to the blank identifier _.
2328 return Named_object::make_sink();
2331 // Add a named object for a dot import.
2334 Gogo::add_dot_import_object(Named_object
* no
)
2336 // If the name already exists, then it was defined in some file seen
2337 // earlier. If the earlier name is just a declaration, don't add
2338 // this name, because that will cause the previous declaration to
2339 // merge to this imported name, which should not happen. Just add
2340 // this name to the list of file block names to get appropriate
2341 // errors if we see a later definition.
2342 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2343 if (e
!= NULL
&& e
->package() == NULL
)
2345 if (e
->is_unknown())
2347 if (e
->package() == NULL
2348 && (e
->is_type_declaration()
2349 || e
->is_function_declaration()
2350 || e
->is_unknown()))
2352 this->add_file_block_name(no
->name(), no
->location());
2357 this->current_bindings()->add_named_object(no
);
2360 // Add a linkname. This implements the go:linkname compiler directive.
2361 // We only support this for functions and function declarations.
2364 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2365 const std::string
& ext_name
, Location loc
)
2368 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2371 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2372 else if (no
->is_function())
2373 no
->func_value()->set_asm_name(ext_name
);
2374 else if (no
->is_function_declaration())
2375 no
->func_declaration_value()->set_asm_name(ext_name
);
2378 ("%s is not a function; "
2379 "//go:linkname is only supported for functions"),
2383 // Mark all local variables used. This is used when some types of
2384 // parse error occur.
2387 Gogo::mark_locals_used()
2389 for (Open_functions::iterator pf
= this->functions_
.begin();
2390 pf
!= this->functions_
.end();
2393 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2394 pb
!= pf
->blocks
.end();
2396 (*pb
)->bindings()->mark_locals_used();
2400 // Record that we've seen an interface type.
2403 Gogo::record_interface_type(Interface_type
* itype
)
2405 this->interface_types_
.push_back(itype
);
2408 // Define the global names. We do this only after parsing all the
2409 // input files, because the program might define the global names
2413 Gogo::define_global_names()
2415 if (this->is_main_package())
2417 // Every Go program has to import the runtime package, so that
2418 // it is properly initialized.
2419 this->import_package("runtime", "_", false, false,
2420 Linemap::predeclared_location());
2423 for (Bindings::const_declarations_iterator p
=
2424 this->globals_
->begin_declarations();
2425 p
!= this->globals_
->end_declarations();
2428 Named_object
* global_no
= p
->second
;
2429 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2430 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2434 if (no
->is_type_declaration())
2436 if (global_no
->is_type())
2438 if (no
->type_declaration_value()->has_methods())
2440 for (std::vector
<Named_object
*>::const_iterator p
=
2441 no
->type_declaration_value()->methods()->begin();
2442 p
!= no
->type_declaration_value()->methods()->end();
2444 go_error_at((*p
)->location(),
2445 "may not define methods on non-local type");
2447 no
->set_type_value(global_no
->type_value());
2451 go_error_at(no
->location(), "expected type");
2452 Type
* errtype
= Type::make_error_type();
2454 Named_object::make_type("erroneous_type", NULL
, errtype
,
2455 Linemap::predeclared_location());
2456 no
->set_type_value(err
->type_value());
2459 else if (no
->is_unknown())
2460 no
->unknown_value()->set_real_named_object(global_no
);
2463 // Give an error if any name is defined in both the package block
2464 // and the file block. For example, this can happen if one file
2465 // imports "fmt" and another file defines a global variable fmt.
2466 for (Bindings::const_declarations_iterator p
=
2467 this->package_
->bindings()->begin_declarations();
2468 p
!= this->package_
->bindings()->end_declarations();
2471 if (p
->second
->is_unknown()
2472 && p
->second
->unknown_value()->real_named_object() == NULL
)
2474 // No point in warning about an undefined name, as we will
2475 // get other errors later anyhow.
2478 File_block_names::const_iterator pf
=
2479 this->file_block_names_
.find(p
->second
->name());
2480 if (pf
!= this->file_block_names_
.end())
2482 std::string n
= p
->second
->message_name();
2483 go_error_at(p
->second
->location(),
2484 "%qs defined as both imported name and global name",
2486 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2489 // No package scope identifier may be named "init".
2490 if (!p
->second
->is_function()
2491 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2493 go_error_at(p
->second
->location(),
2494 "cannot declare init - must be func");
2499 // Clear out names in file scope.
2502 Gogo::clear_file_scope()
2504 this->package_
->bindings()->clear_file_scope(this);
2506 // Warn about packages which were imported but not used.
2507 bool quiet
= saw_errors();
2508 for (Packages::iterator p
= this->packages_
.begin();
2509 p
!= this->packages_
.end();
2512 Package
* package
= p
->second
;
2513 if (package
!= this->package_
&& !quiet
)
2515 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2516 p1
!= package
->aliases().end();
2519 if (!p1
->second
->used())
2521 // Give a more refined error message if the alias name is known.
2522 std::string pkg_name
= package
->package_name();
2523 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2525 go_error_at(p1
->second
->location(),
2526 "imported and not used: %s as %s",
2527 Gogo::message_name(pkg_name
).c_str(),
2528 Gogo::message_name(p1
->first
).c_str());
2531 go_error_at(p1
->second
->location(),
2532 "imported and not used: %s",
2533 Gogo::message_name(pkg_name
).c_str());
2537 package
->clear_used();
2540 this->current_file_imported_unsafe_
= false;
2543 // Queue up a type specific function for later writing. These are
2544 // written out in write_specific_type_functions, called after the
2545 // parse tree is lowered.
2548 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
, int64_t size
,
2549 const std::string
& hash_name
,
2550 Function_type
* hash_fntype
,
2551 const std::string
& equal_name
,
2552 Function_type
* equal_fntype
)
2554 go_assert(!this->specific_type_functions_are_written_
);
2555 go_assert(!this->in_global_scope());
2556 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2561 this->specific_type_functions_
.push_back(tsf
);
2564 // Look for types which need specific hash or equality functions.
2566 class Specific_type_functions
: public Traverse
2569 Specific_type_functions(Gogo
* gogo
)
2570 : Traverse(traverse_types
),
2582 Specific_type_functions::type(Type
* t
)
2584 Named_object
* hash_fn
;
2585 Named_object
* equal_fn
;
2586 switch (t
->classification())
2588 case Type::TYPE_NAMED
:
2590 Named_type
* nt
= t
->named_type();
2592 return TRAVERSE_CONTINUE
;
2593 if (t
->needs_specific_type_functions(this->gogo_
))
2594 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2596 // If this is a struct type, we don't want to make functions
2597 // for the unnamed struct.
2598 Type
* rt
= nt
->real_type();
2599 if (rt
->struct_type() == NULL
)
2601 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2602 return TRAVERSE_EXIT
;
2606 // If this type is defined in another package, then we don't
2607 // need to worry about the unexported fields.
2608 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2609 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2610 for (Struct_field_list::const_iterator p
= fields
->begin();
2614 if (is_defined_elsewhere
2615 && Gogo::is_hidden_name(p
->field_name()))
2617 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2618 return TRAVERSE_EXIT
;
2622 return TRAVERSE_SKIP_COMPONENTS
;
2625 case Type::TYPE_STRUCT
:
2626 case Type::TYPE_ARRAY
:
2627 if (t
->needs_specific_type_functions(this->gogo_
))
2628 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2635 return TRAVERSE_CONTINUE
;
2638 // Write out type specific functions.
2641 Gogo::write_specific_type_functions()
2643 Specific_type_functions
stf(this);
2644 this->traverse(&stf
);
2646 while (!this->specific_type_functions_
.empty())
2648 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2649 this->specific_type_functions_
.pop_back();
2650 tsf
->type
->write_specific_type_functions(this, tsf
->name
, tsf
->size
,
2657 this->specific_type_functions_are_written_
= true;
2660 // Traverse the tree.
2663 Gogo::traverse(Traverse
* traverse
)
2665 // Traverse the current package first for consistency. The other
2666 // packages will only contain imported types, constants, and
2668 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2670 for (Packages::const_iterator p
= this->packages_
.begin();
2671 p
!= this->packages_
.end();
2674 if (p
->second
!= this->package_
)
2676 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2682 // Add a type to verify. This is used for types of sink variables, in
2683 // order to give appropriate error messages.
2686 Gogo::add_type_to_verify(Type
* type
)
2688 this->verify_types_
.push_back(type
);
2691 // Traversal class used to verify types.
2693 class Verify_types
: public Traverse
2697 : Traverse(traverse_types
)
2704 // Verify that a type is correct.
2707 Verify_types::type(Type
* t
)
2710 return TRAVERSE_SKIP_COMPONENTS
;
2711 return TRAVERSE_CONTINUE
;
2714 // Verify that all types are correct.
2717 Gogo::verify_types()
2719 Verify_types traverse
;
2720 this->traverse(&traverse
);
2722 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2723 p
!= this->verify_types_
.end();
2726 this->verify_types_
.clear();
2729 // Traversal class used to lower parse tree.
2731 class Lower_parse_tree
: public Traverse
2734 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2735 : Traverse(traverse_variables
2736 | traverse_constants
2737 | traverse_functions
2738 | traverse_statements
2739 | traverse_expressions
),
2740 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2744 set_inserter(const Statement_inserter
* inserter
)
2745 { this->inserter_
= *inserter
; }
2748 variable(Named_object
*);
2751 constant(Named_object
*, bool);
2754 function(Named_object
*);
2757 statement(Block
*, size_t* pindex
, Statement
*);
2760 expression(Expression
**);
2765 // The function we are traversing.
2766 Named_object
* function_
;
2767 // Value to use for the predeclared constant iota.
2769 // Current statement inserter for use by expressions.
2770 Statement_inserter inserter_
;
2776 Lower_parse_tree::variable(Named_object
* no
)
2778 if (!no
->is_variable())
2779 return TRAVERSE_CONTINUE
;
2781 if (no
->is_variable() && no
->var_value()->is_global())
2783 // Global variables can have loops in their initialization
2784 // expressions. This is handled in lower_init_expression.
2785 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2787 return TRAVERSE_CONTINUE
;
2790 // This is a local variable. We are going to return
2791 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2792 // initialization expression when we reach the variable declaration
2793 // statement. However, that means that we need to traverse the type
2795 if (no
->var_value()->has_type())
2797 Type
* type
= no
->var_value()->type();
2800 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2801 return TRAVERSE_EXIT
;
2804 go_assert(!no
->var_value()->has_pre_init());
2806 return TRAVERSE_SKIP_COMPONENTS
;
2809 // Lower constants. We handle constants specially so that we can set
2810 // the right value for the predeclared constant iota. This works in
2811 // conjunction with the way we lower Const_expression objects.
2814 Lower_parse_tree::constant(Named_object
* no
, bool)
2816 Named_constant
* nc
= no
->const_value();
2818 // Don't get into trouble if the constant's initializer expression
2819 // refers to the constant itself.
2821 return TRAVERSE_CONTINUE
;
2824 go_assert(this->iota_value_
== -1);
2825 this->iota_value_
= nc
->iota_value();
2826 nc
->traverse_expression(this);
2827 this->iota_value_
= -1;
2829 nc
->clear_lowering();
2831 // We will traverse the expression a second time, but that will be
2834 return TRAVERSE_CONTINUE
;
2837 // Lower the body of a function, and set the closure type. Record the
2838 // function while lowering it, so that we can pass it down when
2839 // lowering an expression.
2842 Lower_parse_tree::function(Named_object
* no
)
2844 no
->func_value()->set_closure_type();
2846 go_assert(this->function_
== NULL
);
2847 this->function_
= no
;
2848 int t
= no
->func_value()->traverse(this);
2849 this->function_
= NULL
;
2851 if (t
== TRAVERSE_EXIT
)
2853 return TRAVERSE_SKIP_COMPONENTS
;
2856 // Lower statement parse trees.
2859 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2861 // Because we explicitly traverse the statement's contents
2862 // ourselves, we want to skip block statements here. There is
2863 // nothing to lower in a block statement.
2864 if (sorig
->is_block_statement())
2865 return TRAVERSE_CONTINUE
;
2867 Statement_inserter
hold_inserter(this->inserter_
);
2868 this->inserter_
= Statement_inserter(block
, pindex
);
2870 // Lower the expressions first.
2871 int t
= sorig
->traverse_contents(this);
2872 if (t
== TRAVERSE_EXIT
)
2874 this->inserter_
= hold_inserter
;
2878 // Keep lowering until nothing changes.
2879 Statement
* s
= sorig
;
2882 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2887 t
= s
->traverse_contents(this);
2888 if (t
== TRAVERSE_EXIT
)
2890 this->inserter_
= hold_inserter
;
2896 block
->replace_statement(*pindex
, s
);
2898 this->inserter_
= hold_inserter
;
2899 return TRAVERSE_SKIP_COMPONENTS
;
2902 // Lower expression parse trees.
2905 Lower_parse_tree::expression(Expression
** pexpr
)
2907 // We have to lower all subexpressions first, so that we can get
2908 // their type if necessary. This is awkward, because we don't have
2909 // a postorder traversal pass.
2910 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2911 return TRAVERSE_EXIT
;
2912 // Keep lowering until nothing changes.
2915 Expression
* e
= *pexpr
;
2916 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2917 &this->inserter_
, this->iota_value_
);
2920 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2921 return TRAVERSE_EXIT
;
2925 // Lower the type of this expression before the parent looks at it,
2926 // in case the type contains an array that has expressions in its
2927 // length. Skip an Unknown_expression, as at this point that means
2928 // a composite literal key that does not have a type.
2929 if ((*pexpr
)->unknown_expression() == NULL
)
2930 Type::traverse((*pexpr
)->type(), this);
2932 return TRAVERSE_SKIP_COMPONENTS
;
2935 // Lower the parse tree. This is called after the parse is complete,
2936 // when all names should be resolved.
2939 Gogo::lower_parse_tree()
2941 Lower_parse_tree
lower_parse_tree(this, NULL
);
2942 this->traverse(&lower_parse_tree
);
2944 // If we found any functions defined in other packages that are
2945 // inlinables, import their bodies and turn them into functions.
2947 // Note that as we import inlinable functions we may find more
2948 // inlinable functions, so don't use an iterator.
2949 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
2951 Named_object
* no
= this->imported_inlinable_functions_
[i
];
2952 no
->func_declaration_value()->import_function_body(this, no
);
2955 // There might be type definitions that involve expressions such as the
2956 // array length. Make sure to lower these expressions as well. Otherwise,
2957 // errors hidden within a type can introduce unexpected errors into later
2959 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2960 p
!= this->verify_types_
.end();
2962 Type::traverse(*p
, &lower_parse_tree
);
2968 Gogo::lower_block(Named_object
* function
, Block
* block
)
2970 Lower_parse_tree
lower_parse_tree(this, function
);
2971 block
->traverse(&lower_parse_tree
);
2974 // Lower an expression. INSERTER may be NULL, in which case the
2975 // expression had better not need to create any temporaries.
2978 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2981 Lower_parse_tree
lower_parse_tree(this, function
);
2982 if (inserter
!= NULL
)
2983 lower_parse_tree
.set_inserter(inserter
);
2984 lower_parse_tree
.expression(pexpr
);
2987 // Lower a constant. This is called when lowering a reference to a
2988 // constant. We have to make sure that the constant has already been
2992 Gogo::lower_constant(Named_object
* no
)
2994 go_assert(no
->is_const());
2995 Lower_parse_tree
lower(this, NULL
);
2996 lower
.constant(no
, false);
2999 // Traverse the tree to create function descriptors as needed.
3001 class Create_function_descriptors
: public Traverse
3004 Create_function_descriptors(Gogo
* gogo
)
3005 : Traverse(traverse_functions
| traverse_expressions
),
3010 function(Named_object
*);
3013 expression(Expression
**);
3019 // Create a descriptor for every top-level exported function.
3022 Create_function_descriptors::function(Named_object
* no
)
3024 if (no
->is_function()
3025 && no
->func_value()->enclosing() == NULL
3026 && !no
->func_value()->is_method()
3027 && !Gogo::is_hidden_name(no
->name())
3028 && !Gogo::is_thunk(no
))
3029 no
->func_value()->descriptor(this->gogo_
, no
);
3031 return TRAVERSE_CONTINUE
;
3034 // If we see a function referenced in any way other than calling it,
3035 // create a descriptor for it.
3038 Create_function_descriptors::expression(Expression
** pexpr
)
3040 Expression
* expr
= *pexpr
;
3042 Func_expression
* fe
= expr
->func_expression();
3045 // We would not get here for a call to this function, so this is
3046 // a reference to a function other than calling it. We need a
3048 if (fe
->closure() != NULL
)
3049 return TRAVERSE_CONTINUE
;
3050 Named_object
* no
= fe
->named_object();
3051 if (no
->is_function() && !no
->func_value()->is_method())
3052 no
->func_value()->descriptor(this->gogo_
, no
);
3053 else if (no
->is_function_declaration()
3054 && !no
->func_declaration_value()->type()->is_method()
3055 && !Linemap::is_predeclared_location(no
->location()))
3056 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3057 return TRAVERSE_CONTINUE
;
3060 Bound_method_expression
* bme
= expr
->bound_method_expression();
3063 // We would not get here for a call to this method, so this is a
3064 // method value. We need to create a thunk.
3065 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3067 return TRAVERSE_CONTINUE
;
3070 Interface_field_reference_expression
* ifre
=
3071 expr
->interface_field_reference_expression();
3074 // We would not get here for a call to this interface method, so
3075 // this is a method value. We need to create a thunk.
3076 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3078 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3080 return TRAVERSE_CONTINUE
;
3083 Call_expression
* ce
= expr
->call_expression();
3086 Expression
* fn
= ce
->fn();
3087 if (fn
->func_expression() != NULL
3088 || fn
->bound_method_expression() != NULL
3089 || fn
->interface_field_reference_expression() != NULL
)
3091 // Traverse the arguments but not the function.
3092 Expression_list
* args
= ce
->args();
3095 if (args
->traverse(this) == TRAVERSE_EXIT
)
3096 return TRAVERSE_EXIT
;
3098 return TRAVERSE_SKIP_COMPONENTS
;
3102 return TRAVERSE_CONTINUE
;
3105 // Create function descriptors as needed. We need a function
3106 // descriptor for all exported functions and for all functions that
3107 // are referenced without being called.
3110 Gogo::create_function_descriptors()
3112 // Create a function descriptor for any exported function that is
3113 // declared in this package. This is so that we have a descriptor
3114 // for functions written in assembly. Gather the descriptors first
3115 // so that we don't add declarations while looping over them.
3116 std::vector
<Named_object
*> fndecls
;
3117 Bindings
* b
= this->package_
->bindings();
3118 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3119 p
!= b
->end_declarations();
3122 Named_object
* no
= p
->second
;
3123 if (no
->is_function_declaration()
3124 && !no
->func_declaration_value()->type()->is_method()
3125 && !Linemap::is_predeclared_location(no
->location())
3126 && !Gogo::is_hidden_name(no
->name()))
3127 fndecls
.push_back(no
);
3129 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3132 (*p
)->func_declaration_value()->descriptor(this, *p
);
3135 Create_function_descriptors
cfd(this);
3136 this->traverse(&cfd
);
3139 // Look for interface types to finalize methods of inherited
3142 class Finalize_methods
: public Traverse
3145 Finalize_methods(Gogo
* gogo
)
3146 : Traverse(traverse_types
),
3157 // Finalize the methods of an interface type.
3160 Finalize_methods::type(Type
* t
)
3162 // Check the classification so that we don't finalize the methods
3163 // twice for a named interface type.
3164 switch (t
->classification())
3166 case Type::TYPE_INTERFACE
:
3167 t
->interface_type()->finalize_methods();
3170 case Type::TYPE_NAMED
:
3172 Named_type
* nt
= t
->named_type();
3173 Type
* rt
= nt
->real_type();
3174 if (rt
->classification() != Type::TYPE_STRUCT
)
3176 // Finalize the methods of the real type first.
3177 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3178 return TRAVERSE_EXIT
;
3180 // Finalize the methods of this type.
3181 nt
->finalize_methods(this->gogo_
);
3185 // We don't want to finalize the methods of a named struct
3186 // type, as the methods should be attached to the named
3187 // type, not the struct type. We just want to finalize
3190 // It is possible that a field type refers indirectly to
3191 // this type, such as via a field with function type with
3192 // an argument or result whose type is this type. To
3193 // avoid the cycle, first finalize the methods of any
3194 // embedded types, which are the only types we need to
3195 // know to finalize the methods of this type.
3196 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3199 for (Struct_field_list::const_iterator pf
= fields
->begin();
3200 pf
!= fields
->end();
3203 if (pf
->is_anonymous())
3205 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3206 return TRAVERSE_EXIT
;
3211 // Finalize the methods of this type.
3212 nt
->finalize_methods(this->gogo_
);
3214 // Finalize all the struct fields.
3215 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3216 return TRAVERSE_EXIT
;
3219 // If this type is defined in a different package, then finalize the
3220 // types of all the methods, since we won't see them otherwise.
3221 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3223 const Methods
* methods
= nt
->methods();
3224 for (Methods::const_iterator p
= methods
->begin();
3225 p
!= methods
->end();
3228 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3229 return TRAVERSE_EXIT
;
3233 // Finalize the types of all methods that are declared but not
3234 // defined, since we won't see the declarations otherwise.
3235 if (nt
->named_object()->package() == NULL
3236 && nt
->local_methods() != NULL
)
3238 const Bindings
* methods
= nt
->local_methods();
3239 for (Bindings::const_declarations_iterator p
=
3240 methods
->begin_declarations();
3241 p
!= methods
->end_declarations();
3244 if (p
->second
->is_function_declaration())
3246 Type
* mt
= p
->second
->func_declaration_value()->type();
3247 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3248 return TRAVERSE_EXIT
;
3253 return TRAVERSE_SKIP_COMPONENTS
;
3256 case Type::TYPE_STRUCT
:
3257 // Traverse the field types first in case there is an embedded
3258 // field with methods that the struct should inherit.
3259 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3260 return TRAVERSE_EXIT
;
3261 t
->struct_type()->finalize_methods(this->gogo_
);
3262 return TRAVERSE_SKIP_COMPONENTS
;
3268 return TRAVERSE_CONTINUE
;
3271 // Finalize method lists and build stub methods for types.
3274 Gogo::finalize_methods()
3276 Finalize_methods
finalize(this);
3277 this->traverse(&finalize
);
3280 // Finalize the method list for a type. This is called when a type is
3281 // parsed for an inlined function body, which happens after the
3282 // finalize_methods pass.
3285 Gogo::finalize_methods_for_type(Type
* type
)
3287 Finalize_methods
finalize(this);
3288 Type::traverse(type
, &finalize
);
3291 // Set types for unspecified variables and constants.
3294 Gogo::determine_types()
3296 Bindings
* bindings
= this->current_bindings();
3297 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3298 p
!= bindings
->end_definitions();
3301 if ((*p
)->is_function())
3302 (*p
)->func_value()->determine_types();
3303 else if ((*p
)->is_variable())
3304 (*p
)->var_value()->determine_type();
3305 else if ((*p
)->is_const())
3306 (*p
)->const_value()->determine_type();
3308 // See if a variable requires us to build an initialization
3309 // function. We know that we will see all global variables
3311 if (!this->need_init_fn_
&& (*p
)->is_variable())
3313 Variable
* variable
= (*p
)->var_value();
3315 // If this is a global variable which requires runtime
3316 // initialization, we need an initialization function.
3317 if (!variable
->is_global())
3319 else if (variable
->init() == NULL
)
3321 else if (variable
->type()->interface_type() != NULL
)
3322 this->need_init_fn_
= true;
3323 else if (variable
->init()->is_constant())
3325 else if (!variable
->init()->is_composite_literal())
3326 this->need_init_fn_
= true;
3327 else if (variable
->init()->is_nonconstant_composite_literal())
3328 this->need_init_fn_
= true;
3330 // If this is a global variable which holds a pointer value,
3331 // then we need an initialization function to register it as a
3333 if (variable
->is_global() && variable
->type()->has_pointer())
3334 this->need_init_fn_
= true;
3338 // Determine the types of constants in packages.
3339 for (Packages::const_iterator p
= this->packages_
.begin();
3340 p
!= this->packages_
.end();
3342 p
->second
->determine_types();
3345 // Traversal class used for type checking.
3347 class Check_types_traverse
: public Traverse
3350 Check_types_traverse(Gogo
* gogo
)
3351 : Traverse(traverse_variables
3352 | traverse_constants
3353 | traverse_functions
3354 | traverse_statements
3355 | traverse_expressions
),
3360 variable(Named_object
*);
3363 constant(Named_object
*, bool);
3366 function(Named_object
*);
3369 statement(Block
*, size_t* pindex
, Statement
*);
3372 expression(Expression
**);
3379 // Check that a variable initializer has the right type.
3382 Check_types_traverse::variable(Named_object
* named_object
)
3384 if (named_object
->is_variable())
3386 Variable
* var
= named_object
->var_value();
3388 // Give error if variable type is not defined.
3389 var
->type()->base();
3391 Expression
* init
= var
->init();
3394 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3397 go_error_at(var
->location(), "incompatible type in initialization");
3399 go_error_at(var
->location(),
3400 "incompatible type in initialization (%s)",
3402 init
= Expression::make_error(named_object
->location());
3405 else if (init
!= NULL
3406 && init
->func_expression() != NULL
)
3408 Named_object
* no
= init
->func_expression()->named_object();
3409 Function_type
* fntype
;
3410 if (no
->is_function())
3411 fntype
= no
->func_value()->type();
3412 else if (no
->is_function_declaration())
3413 fntype
= no
->func_declaration_value()->type();
3417 // Builtin functions cannot be used as function values for variable
3419 if (fntype
->is_builtin())
3421 go_error_at(init
->location(),
3422 "invalid use of special builtin function %qs; "
3424 no
->message_name().c_str());
3428 && !var
->is_global()
3429 && !var
->is_parameter()
3430 && !var
->is_receiver()
3431 && !var
->type()->is_error()
3432 && (init
== NULL
|| !init
->is_error_expression())
3433 && !Lex::is_invalid_identifier(named_object
->name()))
3434 go_error_at(var
->location(), "%qs declared and not used",
3435 named_object
->message_name().c_str());
3437 return TRAVERSE_CONTINUE
;
3440 // Check that a constant initializer has the right type.
3443 Check_types_traverse::constant(Named_object
* named_object
, bool)
3445 Named_constant
* constant
= named_object
->const_value();
3446 Type
* ctype
= constant
->type();
3447 if (ctype
->integer_type() == NULL
3448 && ctype
->float_type() == NULL
3449 && ctype
->complex_type() == NULL
3450 && !ctype
->is_boolean_type()
3451 && !ctype
->is_string_type())
3453 if (ctype
->is_nil_type())
3454 go_error_at(constant
->location(), "const initializer cannot be nil");
3455 else if (!ctype
->is_error())
3456 go_error_at(constant
->location(), "invalid constant type");
3457 constant
->set_error();
3459 else if (!constant
->expr()->is_constant())
3461 go_error_at(constant
->expr()->location(), "expression is not constant");
3462 constant
->set_error();
3464 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3467 go_error_at(constant
->location(),
3468 "initialization expression has wrong type");
3469 constant
->set_error();
3471 return TRAVERSE_CONTINUE
;
3474 // There are no types to check in a function, but this is where we
3475 // issue warnings about labels which are defined but not referenced.
3478 Check_types_traverse::function(Named_object
* no
)
3480 no
->func_value()->check_labels();
3481 return TRAVERSE_CONTINUE
;
3484 // Check that types are valid in a statement.
3487 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3489 s
->check_types(this->gogo_
);
3490 return TRAVERSE_CONTINUE
;
3493 // Check that types are valid in an expression.
3496 Check_types_traverse::expression(Expression
** expr
)
3498 (*expr
)->check_types(this->gogo_
);
3499 return TRAVERSE_CONTINUE
;
3502 // Check that types are valid.
3507 Check_types_traverse
traverse(this);
3508 this->traverse(&traverse
);
3510 Bindings
* bindings
= this->current_bindings();
3511 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3512 p
!= bindings
->end_declarations();
3515 // Also check the types in a function declaration's signature.
3516 Named_object
* no
= p
->second
;
3517 if (no
->is_function_declaration())
3518 no
->func_declaration_value()->check_types();
3522 // Check the types in a single block.
3525 Gogo::check_types_in_block(Block
* block
)
3527 Check_types_traverse
traverse(this);
3528 block
->traverse(&traverse
);
3531 // A traversal class which finds all the expressions which must be
3532 // evaluated in order within a statement or larger expression. This
3533 // is used to implement the rules about order of evaluation.
3535 class Find_eval_ordering
: public Traverse
3538 typedef std::vector
<Expression
**> Expression_pointers
;
3541 Find_eval_ordering()
3542 : Traverse(traverse_blocks
3543 | traverse_statements
3544 | traverse_expressions
),
3550 { return this->exprs_
.size(); }
3552 typedef Expression_pointers::const_iterator const_iterator
;
3556 { return this->exprs_
.begin(); }
3560 { return this->exprs_
.end(); }
3565 { return TRAVERSE_SKIP_COMPONENTS
; }
3568 statement(Block
*, size_t*, Statement
*)
3569 { return TRAVERSE_SKIP_COMPONENTS
; }
3572 expression(Expression
**);
3575 // A list of pointers to expressions with side-effects.
3576 Expression_pointers exprs_
;
3579 // If an expression must be evaluated in order, put it on the list.
3582 Find_eval_ordering::expression(Expression
** expression_pointer
)
3584 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3586 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3588 // Shortcut expressions may potentially have side effects which need
3589 // to be ordered, so add them to the list.
3590 // We don't order its subexpressions here since they may be evaluated
3591 // conditionally. This is handled in remove_shortcuts.
3592 this->exprs_
.push_back(expression_pointer
);
3593 return TRAVERSE_SKIP_COMPONENTS
;
3596 // We have to look at subexpressions before this one.
3597 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3598 return TRAVERSE_EXIT
;
3599 if ((*expression_pointer
)->must_eval_in_order())
3600 this->exprs_
.push_back(expression_pointer
);
3601 return TRAVERSE_SKIP_COMPONENTS
;
3604 // A traversal class for ordering evaluations.
3606 class Order_eval
: public Traverse
3609 Order_eval(Gogo
* gogo
)
3610 : Traverse(traverse_variables
3611 | traverse_statements
),
3616 variable(Named_object
*);
3619 statement(Block
*, size_t*, Statement
*);
3626 // Implement the order of evaluation rules for a statement.
3629 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3631 // FIXME: This approach doesn't work for switch statements, because
3632 // we add the new statements before the whole switch when we need to
3633 // instead add them just before the switch expression. The right
3634 // fix is probably to lower switch statements with nonconstant cases
3635 // to a series of conditionals.
3636 if (stmt
->switch_statement() != NULL
)
3637 return TRAVERSE_CONTINUE
;
3639 Find_eval_ordering find_eval_ordering
;
3641 // If S is a variable declaration, then ordinary traversal won't do
3642 // anything. We want to explicitly traverse the initialization
3643 // expression if there is one.
3644 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
3645 Expression
* init
= NULL
;
3646 Expression
* orig_init
= NULL
;
3648 stmt
->traverse_contents(&find_eval_ordering
);
3651 init
= vds
->var()->var_value()->init();
3653 return TRAVERSE_CONTINUE
;
3656 // It might seem that this could be
3657 // init->traverse_subexpressions. Unfortunately that can fail
3660 // newvar, err := call(arg())
3661 // Here newvar will have an init of call result 0 of
3662 // call(arg()). If we only traverse subexpressions, we will
3663 // only find arg(), and we won't bother to move anything out.
3664 // Then we get to the assignment to err, we will traverse the
3665 // whole statement, and this time we will find both call() and
3666 // arg(), and so we will move them out. This will cause them to
3667 // be put into temporary variables before the assignment to err
3668 // but after the declaration of newvar. To avoid that problem,
3669 // we traverse the entire expression here.
3670 Expression::traverse(&init
, &find_eval_ordering
);
3673 size_t c
= find_eval_ordering
.size();
3675 return TRAVERSE_CONTINUE
;
3677 // If there is only one expression with a side-effect, we can
3678 // usually leave it in place.
3681 switch (stmt
->classification())
3683 case Statement::STATEMENT_ASSIGNMENT
:
3684 // For an assignment statement, we need to evaluate an
3685 // expression on the right hand side before we evaluate any
3686 // index expression on the left hand side, so for that case
3687 // we always move the expression. Otherwise we mishandle
3688 // m[0] = len(m) where m is a map.
3691 case Statement::STATEMENT_EXPRESSION
:
3693 // If this is a call statement that doesn't return any
3694 // values, it will not have been counted as a value to
3695 // move. We need to move any subexpressions in case they
3696 // are themselves call statements that require passing a
3698 Expression
* expr
= stmt
->expression_statement()->expr();
3699 if (expr
->call_expression() != NULL
3700 && expr
->call_expression()->result_count() == 0)
3702 return TRAVERSE_CONTINUE
;
3706 // We can leave the expression in place.
3707 return TRAVERSE_CONTINUE
;
3711 bool is_thunk
= stmt
->thunk_statement() != NULL
;
3712 Expression_statement
* es
= stmt
->expression_statement();
3713 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3714 p
!= find_eval_ordering
.end();
3717 Expression
** pexpr
= *p
;
3719 // The last expression in a thunk will be the call passed to go
3720 // or defer, which we must not evaluate early.
3721 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3724 Location loc
= (*pexpr
)->location();
3726 if ((*pexpr
)->call_expression() == NULL
3727 || (*pexpr
)->call_expression()->result_count() < 2)
3729 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3732 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3736 // A call expression which returns multiple results needs to
3737 // be handled specially. We can't create a temporary
3738 // because there is no type to give it. Any actual uses of
3739 // the values will be done via Call_result_expressions.
3741 // Since a given call expression can be shared by multiple
3742 // Call_result_expressions, avoid hoisting the call the
3743 // second time we see it here. In addition, don't try to
3744 // hoist the top-level multi-return call in the statement,
3745 // since doing this would result a tree with more than one copy
3747 if (this->remember_expression(*pexpr
))
3749 else if (es
!= NULL
&& *pexpr
== es
->expr())
3752 s
= Statement::make_statement(*pexpr
, true);
3757 block
->insert_statement_before(*pindex
, s
);
3762 if (init
!= orig_init
)
3763 vds
->var()->var_value()->set_init(init
);
3765 return TRAVERSE_CONTINUE
;
3768 // Implement the order of evaluation rules for the initializer of a
3772 Order_eval::variable(Named_object
* no
)
3774 if (no
->is_result_variable())
3775 return TRAVERSE_CONTINUE
;
3776 Variable
* var
= no
->var_value();
3777 Expression
* init
= var
->init();
3778 if (!var
->is_global() || init
== NULL
)
3779 return TRAVERSE_CONTINUE
;
3781 Find_eval_ordering find_eval_ordering
;
3782 Expression::traverse(&init
, &find_eval_ordering
);
3784 if (find_eval_ordering
.size() <= 1)
3786 // If there is only one expression with a side-effect, we can
3787 // leave it in place.
3788 return TRAVERSE_SKIP_COMPONENTS
;
3791 Expression
* orig_init
= init
;
3793 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3794 p
!= find_eval_ordering
.end();
3797 Expression
** pexpr
= *p
;
3798 Location loc
= (*pexpr
)->location();
3800 if ((*pexpr
)->call_expression() == NULL
3801 || (*pexpr
)->call_expression()->result_count() < 2)
3803 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3806 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3810 // A call expression which returns multiple results needs to
3811 // be handled specially.
3812 s
= Statement::make_statement(*pexpr
, true);
3814 var
->add_preinit_statement(this->gogo_
, s
);
3817 if (init
!= orig_init
)
3818 var
->set_init(init
);
3820 return TRAVERSE_SKIP_COMPONENTS
;
3823 // Use temporary variables to implement the order of evaluation rules.
3826 Gogo::order_evaluations()
3828 Order_eval
order_eval(this);
3829 this->traverse(&order_eval
);
3832 // A traversal class used to find a single shortcut operator within an
3835 class Find_shortcut
: public Traverse
3839 : Traverse(traverse_blocks
3840 | traverse_statements
3841 | traverse_expressions
),
3845 // A pointer to the expression which was found, or NULL if none was
3849 { return this->found_
; }
3854 { return TRAVERSE_SKIP_COMPONENTS
; }
3857 statement(Block
*, size_t*, Statement
*)
3858 { return TRAVERSE_SKIP_COMPONENTS
; }
3861 expression(Expression
**);
3864 Expression
** found_
;
3867 // Find a shortcut expression.
3870 Find_shortcut::expression(Expression
** pexpr
)
3872 Expression
* expr
= *pexpr
;
3873 Binary_expression
* be
= expr
->binary_expression();
3875 return TRAVERSE_CONTINUE
;
3876 Operator op
= be
->op();
3877 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3878 return TRAVERSE_CONTINUE
;
3879 go_assert(this->found_
== NULL
);
3880 this->found_
= pexpr
;
3881 return TRAVERSE_EXIT
;
3884 // A traversal class used to turn shortcut operators into explicit if
3887 class Shortcuts
: public Traverse
3890 Shortcuts(Gogo
* gogo
)
3891 : Traverse(traverse_variables
3892 | traverse_statements
),
3898 variable(Named_object
*);
3901 statement(Block
*, size_t*, Statement
*);
3904 // Convert a shortcut operator.
3906 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3912 // Remove shortcut operators in a single statement.
3915 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3917 // FIXME: This approach doesn't work for switch statements, because
3918 // we add the new statements before the whole switch when we need to
3919 // instead add them just before the switch expression. The right
3920 // fix is probably to lower switch statements with nonconstant cases
3921 // to a series of conditionals.
3922 if (s
->switch_statement() != NULL
)
3923 return TRAVERSE_CONTINUE
;
3927 Find_shortcut find_shortcut
;
3929 // If S is a variable declaration, then ordinary traversal won't
3930 // do anything. We want to explicitly traverse the
3931 // initialization expression if there is one.
3932 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3933 Expression
* init
= NULL
;
3935 s
->traverse_contents(&find_shortcut
);
3938 init
= vds
->var()->var_value()->init();
3940 return TRAVERSE_CONTINUE
;
3941 init
->traverse(&init
, &find_shortcut
);
3943 Expression
** pshortcut
= find_shortcut
.found();
3944 if (pshortcut
== NULL
)
3945 return TRAVERSE_CONTINUE
;
3947 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3948 block
->insert_statement_before(*pindex
, snew
);
3951 if (pshortcut
== &init
)
3952 vds
->var()->var_value()->set_init(init
);
3956 // Remove shortcut operators in the initializer of a global variable.
3959 Shortcuts::variable(Named_object
* no
)
3961 if (no
->is_result_variable())
3962 return TRAVERSE_CONTINUE
;
3963 Variable
* var
= no
->var_value();
3964 Expression
* init
= var
->init();
3965 if (!var
->is_global() || init
== NULL
)
3966 return TRAVERSE_CONTINUE
;
3970 Find_shortcut find_shortcut
;
3971 init
->traverse(&init
, &find_shortcut
);
3972 Expression
** pshortcut
= find_shortcut
.found();
3973 if (pshortcut
== NULL
)
3974 return TRAVERSE_CONTINUE
;
3976 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3977 var
->add_preinit_statement(this->gogo_
, snew
);
3978 if (pshortcut
== &init
)
3979 var
->set_init(init
);
3983 // Given an expression which uses a shortcut operator, return a
3984 // statement which implements it, and update *PSHORTCUT accordingly.
3987 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3989 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3990 Expression
* left
= shortcut
->left();
3991 Expression
* right
= shortcut
->right();
3992 Location loc
= shortcut
->location();
3994 Block
* retblock
= new Block(enclosing
, loc
);
3995 retblock
->set_end_location(loc
);
3997 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3999 retblock
->add_statement(ts
);
4001 Block
* block
= new Block(retblock
, loc
);
4002 block
->set_end_location(loc
);
4003 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4004 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4005 block
->add_statement(assign
);
4007 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4008 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4009 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4011 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4013 retblock
->add_statement(if_statement
);
4015 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4019 // Now convert any shortcut operators in LEFT and RIGHT.
4020 // LEFT and RIGHT were skipped in the top level
4021 // Gogo::order_evaluations. We need to order their
4022 // components first.
4023 Order_eval
order_eval(this->gogo_
);
4024 retblock
->traverse(&order_eval
);
4025 Shortcuts
shortcuts(this->gogo_
);
4026 retblock
->traverse(&shortcuts
);
4028 return Statement::make_block_statement(retblock
, loc
);
4031 // Turn shortcut operators into explicit if statements. Doing this
4032 // considerably simplifies the order of evaluation rules.
4035 Gogo::remove_shortcuts()
4037 Shortcuts
shortcuts(this);
4038 this->traverse(&shortcuts
);
4041 // Traversal to flatten parse tree after order of evaluation rules are applied.
4043 class Flatten
: public Traverse
4046 Flatten(Gogo
* gogo
, Named_object
* function
)
4047 : Traverse(traverse_variables
4048 | traverse_functions
4049 | traverse_statements
4050 | traverse_expressions
),
4051 gogo_(gogo
), function_(function
), inserter_()
4055 set_inserter(const Statement_inserter
* inserter
)
4056 { this->inserter_
= *inserter
; }
4059 variable(Named_object
*);
4062 function(Named_object
*);
4065 statement(Block
*, size_t* pindex
, Statement
*);
4068 expression(Expression
**);
4073 // The function we are traversing.
4074 Named_object
* function_
;
4075 // Current statement inserter for use by expressions.
4076 Statement_inserter inserter_
;
4079 // Flatten variables.
4082 Flatten::variable(Named_object
* no
)
4084 if (!no
->is_variable())
4085 return TRAVERSE_CONTINUE
;
4087 if (no
->is_variable() && no
->var_value()->is_global())
4089 // Global variables can have loops in their initialization
4090 // expressions. This is handled in flatten_init_expression.
4091 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4093 return TRAVERSE_CONTINUE
;
4096 if (!no
->var_value()->is_parameter()
4097 && !no
->var_value()->is_receiver()
4098 && !no
->var_value()->is_closure()
4099 && no
->var_value()->is_non_escaping_address_taken()
4100 && !no
->var_value()->is_in_heap()
4101 && no
->var_value()->toplevel_decl() == NULL
)
4103 // Local variable that has address taken but not escape.
4104 // It needs to be live beyond its lexical scope. So we
4105 // create a top-level declaration for it.
4106 // No need to do it if it is already in the top level.
4107 Block
* top_block
= function_
->func_value()->block();
4108 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4110 Variable
* var
= no
->var_value();
4111 Temporary_statement
* ts
=
4112 Statement::make_temporary(var
->type(), NULL
, var
->location());
4113 ts
->set_is_address_taken();
4114 top_block
->add_statement_at_front(ts
);
4115 var
->set_toplevel_decl(ts
);
4119 go_assert(!no
->var_value()->has_pre_init());
4121 return TRAVERSE_SKIP_COMPONENTS
;
4124 // Flatten the body of a function. Record the function while flattening it,
4125 // so that we can pass it down when flattening an expression.
4128 Flatten::function(Named_object
* no
)
4130 go_assert(this->function_
== NULL
);
4131 this->function_
= no
;
4132 int t
= no
->func_value()->traverse(this);
4133 this->function_
= NULL
;
4135 if (t
== TRAVERSE_EXIT
)
4137 return TRAVERSE_SKIP_COMPONENTS
;
4140 // Flatten statement parse trees.
4143 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4145 // Because we explicitly traverse the statement's contents
4146 // ourselves, we want to skip block statements here. There is
4147 // nothing to flatten in a block statement.
4148 if (sorig
->is_block_statement())
4149 return TRAVERSE_CONTINUE
;
4151 Statement_inserter
hold_inserter(this->inserter_
);
4152 this->inserter_
= Statement_inserter(block
, pindex
);
4154 // Flatten the expressions first.
4155 int t
= sorig
->traverse_contents(this);
4156 if (t
== TRAVERSE_EXIT
)
4158 this->inserter_
= hold_inserter
;
4162 // Keep flattening until nothing changes.
4163 Statement
* s
= sorig
;
4166 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4171 t
= s
->traverse_contents(this);
4172 if (t
== TRAVERSE_EXIT
)
4174 this->inserter_
= hold_inserter
;
4180 block
->replace_statement(*pindex
, s
);
4182 this->inserter_
= hold_inserter
;
4183 return TRAVERSE_SKIP_COMPONENTS
;
4186 // Flatten expression parse trees.
4189 Flatten::expression(Expression
** pexpr
)
4191 // Keep flattening until nothing changes.
4194 Expression
* e
= *pexpr
;
4195 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4196 return TRAVERSE_EXIT
;
4198 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4204 return TRAVERSE_SKIP_COMPONENTS
;
4210 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4212 Flatten
flatten(this, function
);
4213 block
->traverse(&flatten
);
4216 // Flatten an expression. INSERTER may be NULL, in which case the
4217 // expression had better not need to create any temporaries.
4220 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4223 Flatten
flatten(this, function
);
4224 if (inserter
!= NULL
)
4225 flatten
.set_inserter(inserter
);
4226 flatten
.expression(pexpr
);
4232 Flatten
flatten(this, NULL
);
4233 this->traverse(&flatten
);
4236 // Traversal to convert calls to the predeclared recover function to
4237 // pass in an argument indicating whether it can recover from a panic
4240 class Convert_recover
: public Traverse
4243 Convert_recover(Named_object
* arg
)
4244 : Traverse(traverse_expressions
),
4250 expression(Expression
**);
4253 // The argument to pass to the function.
4257 // Convert calls to recover.
4260 Convert_recover::expression(Expression
** pp
)
4262 Call_expression
* ce
= (*pp
)->call_expression();
4263 if (ce
!= NULL
&& ce
->is_recover_call())
4264 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4266 return TRAVERSE_CONTINUE
;
4269 // Traversal for build_recover_thunks.
4271 class Build_recover_thunks
: public Traverse
4274 Build_recover_thunks(Gogo
* gogo
)
4275 : Traverse(traverse_functions
),
4280 function(Named_object
*);
4284 can_recover_arg(Location
);
4290 // If this function calls recover, turn it into a thunk.
4293 Build_recover_thunks::function(Named_object
* orig_no
)
4295 Function
* orig_func
= orig_no
->func_value();
4296 if (!orig_func
->calls_recover()
4297 || orig_func
->is_recover_thunk()
4298 || orig_func
->has_recover_thunk())
4299 return TRAVERSE_CONTINUE
;
4301 Gogo
* gogo
= this->gogo_
;
4302 Location location
= orig_func
->location();
4307 Function_type
* orig_fntype
= orig_func
->type();
4308 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4309 std::string receiver_name
;
4310 if (orig_fntype
->is_method())
4312 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4313 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4315 receiver_name
= buf
;
4316 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4317 receiver
->location()));
4319 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4320 if (orig_params
!= NULL
&& !orig_params
->empty())
4322 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4323 p
!= orig_params
->end();
4326 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4328 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4332 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4334 std::string can_recover_name
= buf
;
4335 new_params
->push_back(Typed_identifier(can_recover_name
,
4336 Type::lookup_bool_type(),
4337 orig_fntype
->location()));
4339 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4340 Typed_identifier_list
* new_results
;
4341 if (orig_results
== NULL
|| orig_results
->empty())
4345 new_results
= new Typed_identifier_list();
4346 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4347 p
!= orig_results
->end();
4349 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4352 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4354 orig_fntype
->location());
4355 if (orig_fntype
->is_varargs())
4356 new_fntype
->set_is_varargs();
4359 if (orig_fntype
->is_method())
4360 rtype
= orig_fntype
->receiver()->type();
4361 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4362 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4364 Function
*new_func
= new_no
->func_value();
4365 if (orig_func
->enclosing() != NULL
)
4366 new_func
->set_enclosing(orig_func
->enclosing());
4368 // We build the code for the original function attached to the new
4369 // function, and then swap the original and new function bodies.
4370 // This means that existing references to the original function will
4371 // then refer to the new function. That makes this code a little
4372 // confusing, in that the reference to NEW_NO really refers to the
4373 // other function, not the one we are building.
4375 Expression
* closure
= NULL
;
4376 if (orig_func
->needs_closure())
4378 // For the new function we are creating, declare a new parameter
4379 // variable NEW_CLOSURE_NO and set it to be the closure variable
4380 // of the function. This will be set to the closure value
4381 // passed in by the caller. Then pass a reference to this
4382 // variable as the closure value when calling the original
4383 // function. In other words, simply pass the closure value
4384 // through the thunk we are creating.
4385 Named_object
* orig_closure_no
= orig_func
->closure_var();
4386 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4387 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4388 false, false, location
);
4389 new_var
->set_is_closure();
4390 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4392 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4394 new_func
->set_closure_var(new_closure_no
);
4395 closure
= Expression::make_var_reference(new_closure_no
, location
);
4398 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4400 Expression_list
* args
= new Expression_list();
4401 if (new_params
!= NULL
)
4403 // Note that we skip the last parameter, which is the boolean
4404 // indicating whether recover can succed.
4405 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4406 p
+ 1 != new_params
->end();
4409 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4410 go_assert(p_no
!= NULL
4411 && p_no
->is_variable()
4412 && p_no
->var_value()->is_parameter());
4413 args
->push_back(Expression::make_var_reference(p_no
, location
));
4416 args
->push_back(this->can_recover_arg(location
));
4418 gogo
->start_block(location
);
4420 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4422 // Any varargs call has already been lowered.
4423 call
->set_varargs_are_lowered();
4425 Statement
* s
= Statement::make_return_from_call(call
, location
);
4426 s
->determine_types();
4427 gogo
->add_statement(s
);
4429 Block
* b
= gogo
->finish_block(location
);
4431 gogo
->add_block(b
, location
);
4433 // Lower the call in case it returns multiple results.
4434 gogo
->lower_block(new_no
, b
);
4436 gogo
->finish_function(location
);
4438 // Swap the function bodies and types.
4439 new_func
->swap_for_recover(orig_func
);
4440 orig_func
->set_is_recover_thunk();
4441 new_func
->set_calls_recover();
4442 new_func
->set_has_recover_thunk();
4444 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4445 Bindings
* new_bindings
= new_func
->block()->bindings();
4446 if (orig_fntype
->is_method())
4448 // We changed the receiver to be a regular parameter. We have
4449 // to update the binding accordingly in both functions.
4450 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4451 go_assert(orig_rec_no
!= NULL
4452 && orig_rec_no
->is_variable()
4453 && !orig_rec_no
->var_value()->is_receiver());
4454 orig_rec_no
->var_value()->set_is_receiver();
4456 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4457 if (new_receiver_name
.empty())
4459 // Find the receiver. It was named "r.NNN" in
4460 // Gogo::start_function.
4461 for (Bindings::const_definitions_iterator p
=
4462 new_bindings
->begin_definitions();
4463 p
!= new_bindings
->end_definitions();
4466 const std::string
& pname((*p
)->name());
4467 if (pname
[0] == 'r' && pname
[1] == '.')
4469 new_receiver_name
= pname
;
4473 go_assert(!new_receiver_name
.empty());
4475 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4476 if (new_rec_no
== NULL
)
4477 go_assert(saw_errors());
4480 go_assert(new_rec_no
->is_variable()
4481 && new_rec_no
->var_value()->is_receiver());
4482 new_rec_no
->var_value()->set_is_not_receiver();
4486 // Because we flipped blocks but not types, the can_recover
4487 // parameter appears in the (now) old bindings as a parameter.
4488 // Change it to a local variable, whereupon it will be discarded.
4489 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4490 go_assert(can_recover_no
!= NULL
4491 && can_recover_no
->is_variable()
4492 && can_recover_no
->var_value()->is_parameter());
4493 orig_bindings
->remove_binding(can_recover_no
);
4495 // Add the can_recover argument to the (now) new bindings, and
4496 // attach it to any recover statements.
4497 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4498 false, true, false, location
);
4499 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4501 Convert_recover
convert_recover(can_recover_no
);
4502 new_func
->traverse(&convert_recover
);
4504 // Update the function pointers in any named results.
4505 new_func
->update_result_variables();
4506 orig_func
->update_result_variables();
4508 return TRAVERSE_CONTINUE
;
4511 // Return the expression to pass for the .can_recover parameter to the
4512 // new function. This indicates whether a call to recover may return
4513 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4516 Build_recover_thunks::can_recover_arg(Location location
)
4518 static Named_object
* builtin_return_address
;
4519 if (builtin_return_address
== NULL
)
4520 builtin_return_address
=
4521 Gogo::declare_builtin_rf_address("__builtin_return_address", true);
4523 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4524 static Named_object
* can_recover
;
4525 if (can_recover
== NULL
)
4527 const Location bloc
= Linemap::predeclared_location();
4528 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4529 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4530 Type
* boolean_type
= Type::lookup_bool_type();
4531 Typed_identifier_list
* results
= new Typed_identifier_list();
4532 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4533 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4536 Named_object::make_function_declaration("runtime_canrecover",
4537 NULL
, fntype
, bloc
);
4538 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4541 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4544 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4545 Expression_list
*args
= new Expression_list();
4546 args
->push_back(zexpr
);
4548 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4549 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4551 args
= new Expression_list();
4552 args
->push_back(call
);
4554 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4555 return Expression::make_call(fn
, args
, false, location
);
4558 // Build thunks for functions which call recover. We build a new
4559 // function with an extra parameter, which is whether a call to
4560 // recover can succeed. We then move the body of this function to
4561 // that one. We then turn this function into a thunk which calls the
4562 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4563 // The function will be marked as not splitting the stack. This will
4564 // cooperate with the implementation of defer to make recover do the
4568 Gogo::build_recover_thunks()
4570 Build_recover_thunks
build_recover_thunks(this);
4571 this->traverse(&build_recover_thunks
);
4574 // Return a declaration for __builtin_return_address or
4575 // __builtin_dwarf_cfa.
4578 Gogo::declare_builtin_rf_address(const char* name
, bool hasarg
)
4580 const Location bloc
= Linemap::predeclared_location();
4582 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4585 Type
* uint32_type
= Type::lookup_integer_type("uint32");
4586 param_types
->push_back(Typed_identifier("l", uint32_type
, bloc
));
4589 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4590 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4591 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4593 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4594 return_types
, bloc
);
4595 Named_object
* ret
= Named_object::make_function_declaration(name
, NULL
,
4597 ret
->func_declaration_value()->set_asm_name(name
);
4601 // Build a call to the runtime error function.
4604 Gogo::runtime_error(int code
, Location location
)
4606 Type
* int32_type
= Type::lookup_integer_type("int32");
4607 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4609 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4612 // Look for named types to see whether we need to create an interface
4615 class Build_method_tables
: public Traverse
4618 Build_method_tables(Gogo
* gogo
,
4619 const std::vector
<Interface_type
*>& interfaces
)
4620 : Traverse(traverse_types
),
4621 gogo_(gogo
), interfaces_(interfaces
)
4630 // A list of locally defined interfaces which have hidden methods.
4631 const std::vector
<Interface_type
*>& interfaces_
;
4634 // Build all required interface method tables for types. We need to
4635 // ensure that we have an interface method table for every interface
4636 // which has a hidden method, for every named type which implements
4637 // that interface. Normally we can just build interface method tables
4638 // as we need them. However, in some cases we can require an
4639 // interface method table for an interface defined in a different
4640 // package for a type defined in that package. If that interface and
4641 // type both use a hidden method, that is OK. However, we will not be
4642 // able to build that interface method table when we need it, because
4643 // the type's hidden method will be static. So we have to build it
4644 // here, and just refer it from other packages as needed.
4647 Gogo::build_interface_method_tables()
4652 std::vector
<Interface_type
*> hidden_interfaces
;
4653 hidden_interfaces
.reserve(this->interface_types_
.size());
4654 for (std::vector
<Interface_type
*>::const_iterator pi
=
4655 this->interface_types_
.begin();
4656 pi
!= this->interface_types_
.end();
4659 const Typed_identifier_list
* methods
= (*pi
)->methods();
4660 if (methods
== NULL
)
4662 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4663 pm
!= methods
->end();
4666 if (Gogo::is_hidden_name(pm
->name()))
4668 hidden_interfaces
.push_back(*pi
);
4674 if (!hidden_interfaces
.empty())
4676 // Now traverse the tree looking for all named types.
4677 Build_method_tables
bmt(this, hidden_interfaces
);
4678 this->traverse(&bmt
);
4681 // We no longer need the list of interfaces.
4683 this->interface_types_
.clear();
4686 // This is called for each type. For a named type, for each of the
4687 // interfaces with hidden methods that it implements, create the
4691 Build_method_tables::type(Type
* type
)
4693 Named_type
* nt
= type
->named_type();
4694 Struct_type
* st
= type
->struct_type();
4695 if (nt
!= NULL
|| st
!= NULL
)
4697 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4698 for (std::vector
<Interface_type
*>::const_iterator p
=
4699 this->interfaces_
.begin();
4700 p
!= this->interfaces_
.end();
4703 // We ask whether a pointer to the named type implements the
4704 // interface, because a pointer can implement more methods
4708 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4711 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4712 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4717 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4720 st
->interface_method_table(*p
, false)->get_backend(&context
);
4721 st
->interface_method_table(*p
, true)->get_backend(&context
);
4726 return TRAVERSE_CONTINUE
;
4729 // Return an expression which allocates memory to hold values of type TYPE.
4732 Gogo::allocate_memory(Type
* type
, Location location
)
4734 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4735 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
4738 // Traversal class used to check for return statements.
4740 class Check_return_statements_traverse
: public Traverse
4743 Check_return_statements_traverse()
4744 : Traverse(traverse_functions
)
4748 function(Named_object
*);
4751 // Check that a function has a return statement if it needs one.
4754 Check_return_statements_traverse::function(Named_object
* no
)
4756 Function
* func
= no
->func_value();
4757 const Function_type
* fntype
= func
->type();
4758 const Typed_identifier_list
* results
= fntype
->results();
4760 // We only need a return statement if there is a return value.
4761 if (results
== NULL
|| results
->empty())
4762 return TRAVERSE_CONTINUE
;
4764 if (func
->block()->may_fall_through())
4765 go_error_at(func
->block()->end_location(),
4766 "missing return at end of function");
4768 return TRAVERSE_CONTINUE
;
4771 // Check return statements.
4774 Gogo::check_return_statements()
4776 Check_return_statements_traverse traverse
;
4777 this->traverse(&traverse
);
4780 // Traversal class to decide whether a function body is less than the
4781 // inlining budget. This adjusts *available as it goes, and stops the
4782 // traversal if it goes negative.
4784 class Inline_within_budget
: public Traverse
4787 Inline_within_budget(int* available
)
4788 : Traverse(traverse_statements
4789 | traverse_expressions
),
4790 available_(available
)
4794 statement(Block
*, size_t*, Statement
*);
4797 expression(Expression
**);
4800 // Pointer to remaining budget.
4804 // Adjust the budget for the inlining cost of a statement.
4807 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
4809 if (*this->available_
< 0)
4810 return TRAVERSE_EXIT
;
4811 *this->available_
-= s
->inlining_cost();
4812 return TRAVERSE_CONTINUE
;
4815 // Adjust the budget for the inlining cost of an expression.
4818 Inline_within_budget::expression(Expression
** pexpr
)
4820 if (*this->available_
< 0)
4821 return TRAVERSE_EXIT
;
4822 *this->available_
-= (*pexpr
)->inlining_cost();
4823 return TRAVERSE_CONTINUE
;
4826 // Traversal class to find functions whose body should be exported for
4827 // inlining by other packages.
4829 class Mark_inline_candidates
: public Traverse
4832 Mark_inline_candidates()
4833 : Traverse(traverse_functions
4838 function(Named_object
*);
4844 // We traverse the function body trying to determine how expensive
4845 // it is for inlining. We start with a budget, and decrease that
4846 // budget for each statement and expression. If the budget goes
4847 // negative, we do not export the function body. The value of this
4848 // budget is a heuristic. In the usual GCC spirit, we could
4849 // consider setting this via a command line option.
4850 const int budget_heuristic
= 80;
4853 // Mark a function if it is an inline candidate.
4856 Mark_inline_candidates::function(Named_object
* no
)
4858 Function
* func
= no
->func_value();
4859 int budget
= budget_heuristic
;
4860 Inline_within_budget
iwb(&budget
);
4861 func
->block()->traverse(&iwb
);
4863 func
->set_export_for_inlining();
4864 return TRAVERSE_CONTINUE
;
4867 // Mark methods if they are inline candidates.
4870 Mark_inline_candidates::type(Type
* t
)
4872 Named_type
* nt
= t
->named_type();
4873 if (nt
== NULL
|| nt
->is_alias())
4874 return TRAVERSE_CONTINUE
;
4875 const Bindings
* methods
= nt
->local_methods();
4876 if (methods
== NULL
)
4877 return TRAVERSE_CONTINUE
;
4878 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
4879 p
!= methods
->end_definitions();
4882 Named_object
* no
= *p
;
4883 go_assert(no
->is_function());
4884 Function
*func
= no
->func_value();
4885 int budget
= budget_heuristic
;
4886 Inline_within_budget
iwb(&budget
);
4887 func
->block()->traverse(&iwb
);
4889 func
->set_export_for_inlining();
4891 return TRAVERSE_CONTINUE
;
4894 // Export identifiers as requested.
4899 // Mark any functions whose body should be exported for inlining by
4901 Mark_inline_candidates mic
;
4902 this->traverse(&mic
);
4904 // For now we always stream to a section. Later we may want to
4905 // support streaming to a separate file.
4906 Stream_to_section
stream(this->backend());
4908 // Write out either the prefix or pkgpath depending on how we were
4911 std::string pkgpath
;
4912 if (this->pkgpath_from_option_
)
4913 pkgpath
= this->pkgpath_
;
4914 else if (this->prefix_from_option_
)
4915 prefix
= this->prefix_
;
4916 else if (this->is_main_package())
4921 Export
exp(&stream
);
4922 exp
.register_builtin_types(this);
4923 exp
.export_globals(this->package_name(),
4928 (this->need_init_fn_
&& !this->is_main_package()
4929 ? this->get_init_fn_name()
4931 this->imported_init_fns_
,
4932 this->package_
->bindings());
4934 if (!this->c_header_
.empty() && !saw_errors())
4935 this->write_c_header();
4938 // Write the top level named struct types in C format to a C header
4939 // file. This is used when building the runtime package, to share
4940 // struct definitions between C and Go.
4943 Gogo::write_c_header()
4946 out
.open(this->c_header_
.c_str());
4949 go_error_at(Linemap::unknown_location(),
4950 "cannot open %s: %m", this->c_header_
.c_str());
4954 std::list
<Named_object
*> types
;
4955 Bindings
* top
= this->package_
->bindings();
4956 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
4957 p
!= top
->end_definitions();
4960 Named_object
* no
= *p
;
4962 // Skip names that start with underscore followed by something
4963 // other than an uppercase letter, as when compiling the runtime
4964 // package they are mostly types defined by mkrsysinfo.sh based
4965 // on the C system header files. We don't need to translate
4966 // types to C and back to Go. But do accept the special cases
4967 // _defer and _panic.
4968 std::string name
= Gogo::unpack_hidden_name(no
->name());
4970 && (name
[1] < 'A' || name
[1] > 'Z')
4971 && (name
!= "_defer" && name
!= "_panic"))
4974 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
4975 types
.push_back(no
);
4977 && no
->const_value()->type()->integer_type() != NULL
4978 && !no
->const_value()->is_sink())
4980 Numeric_constant nc
;
4982 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
4983 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
4985 out
<< "#define " << no
->message_name() << ' ' << val
4991 std::vector
<const Named_object
*> written
;
4993 while (!types
.empty())
4995 Named_object
* no
= types
.front();
4998 std::vector
<const Named_object
*> requires
;
4999 std::vector
<const Named_object
*> declare
;
5000 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
5005 for (std::vector
<const Named_object
*>::const_iterator pr
5007 pr
!= requires
.end() && ok
;
5010 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5011 pt
!= types
.end() && ok
;
5021 // This should be impossible since the code parsed and
5026 types
.push_back(no
);
5030 for (std::vector
<const Named_object
*>::const_iterator pd
5032 pd
!= declare
.end();
5038 std::vector
<const Named_object
*> drequires
;
5039 std::vector
<const Named_object
*> ddeclare
;
5040 if (!(*pd
)->type_value()->struct_type()->
5041 can_write_to_c_header(&drequires
, &ddeclare
))
5045 for (std::vector
<const Named_object
*>::const_iterator pw
5047 pw
!= written
.end();
5059 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5060 written
.push_back(*pd
);
5065 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5066 no
->type_value()->struct_type()->write_to_c_header(out
);
5067 out
<< "};" << std::endl
;
5068 written
.push_back(no
);
5073 go_error_at(Linemap::unknown_location(),
5074 "error writing to %s: %m", this->c_header_
.c_str());
5077 // Find the blocks in order to convert named types defined in blocks.
5079 class Convert_named_types
: public Traverse
5082 Convert_named_types(Gogo
* gogo
)
5083 : Traverse(traverse_blocks
),
5089 block(Block
* block
);
5096 Convert_named_types::block(Block
* block
)
5098 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5099 return TRAVERSE_CONTINUE
;
5102 // Convert all named types to the backend representation. Since named
5103 // types can refer to other types, this needs to be done in the right
5104 // sequence, which is handled by Named_type::convert. Here we arrange
5105 // to call that for each named type.
5108 Gogo::convert_named_types()
5110 this->convert_named_types_in_bindings(this->globals_
);
5111 for (Packages::iterator p
= this->packages_
.begin();
5112 p
!= this->packages_
.end();
5115 Package
* package
= p
->second
;
5116 this->convert_named_types_in_bindings(package
->bindings());
5119 Convert_named_types
cnt(this);
5120 this->traverse(&cnt
);
5122 // Make all the builtin named types used for type descriptors, and
5123 // then convert them. They will only be written out if they are
5125 Type::make_type_descriptor_type();
5126 Type::make_type_descriptor_ptr_type();
5127 Function_type::make_function_type_descriptor_type();
5128 Pointer_type::make_pointer_type_descriptor_type();
5129 Struct_type::make_struct_type_descriptor_type();
5130 Array_type::make_array_type_descriptor_type();
5131 Array_type::make_slice_type_descriptor_type();
5132 Map_type::make_map_type_descriptor_type();
5133 Channel_type::make_chan_type_descriptor_type();
5134 Interface_type::make_interface_type_descriptor_type();
5135 Expression::make_func_descriptor_type();
5136 Type::convert_builtin_named_types(this);
5138 Runtime::convert_types(this);
5140 this->named_types_are_converted_
= true;
5142 Type::finish_pointer_types(this);
5145 // Convert all names types in a set of bindings.
5148 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5150 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5151 p
!= bindings
->end_definitions();
5154 if ((*p
)->is_type())
5155 (*p
)->type_value()->convert(this);
5161 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5163 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5164 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5165 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5166 pragmas_(0), nested_functions_(0), is_sink_(false),
5167 results_are_named_(false), is_unnamed_type_stub_method_(false),
5168 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5169 calls_defer_retaddr_(false), is_type_specific_function_(false),
5170 in_unique_section_(false), export_for_inlining_(false),
5171 is_inline_only_(false)
5175 // Create the named result variables.
5178 Function::create_result_variables(Gogo
* gogo
)
5180 const Typed_identifier_list
* results
= this->type_
->results();
5181 if (results
== NULL
|| results
->empty())
5184 if (!results
->front().name().empty())
5185 this->results_are_named_
= true;
5187 this->results_
= new Results();
5188 this->results_
->reserve(results
->size());
5190 Block
* block
= this->block_
;
5192 for (Typed_identifier_list::const_iterator p
= results
->begin();
5193 p
!= results
->end();
5196 std::string name
= p
->name();
5197 if (name
.empty() || Gogo::is_sink_name(name
))
5199 static int result_counter
;
5201 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5203 name
= gogo
->pack_hidden_name(buf
, false);
5205 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5207 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5208 if (no
->is_result_variable())
5209 this->results_
->push_back(no
);
5212 static int dummy_result_count
;
5214 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5215 ++dummy_result_count
;
5216 name
= gogo
->pack_hidden_name(buf
, false);
5217 no
= block
->bindings()->add_result_variable(name
, result
);
5218 go_assert(no
->is_result_variable());
5219 this->results_
->push_back(no
);
5224 // Update the named result variables when cloning a function which
5228 Function::update_result_variables()
5230 if (this->results_
== NULL
)
5233 for (Results::iterator p
= this->results_
->begin();
5234 p
!= this->results_
->end();
5236 (*p
)->result_var_value()->set_function(this);
5239 // Whether this method should not be included in the type descriptor.
5242 Function::nointerface() const
5244 go_assert(this->is_method());
5245 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5248 // Record that this method should not be included in the type
5252 Function::set_nointerface()
5254 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5257 // Return the closure variable, creating it if necessary.
5260 Function::closure_var()
5262 if (this->closure_var_
== NULL
)
5264 go_assert(this->descriptor_
== NULL
);
5265 // We don't know the type of the variable yet. We add fields as
5267 Location loc
= this->type_
->location();
5268 Struct_field_list
* sfl
= new Struct_field_list
;
5269 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5270 struct_type
->set_is_struct_incomparable();
5271 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5272 NULL
, false, false, false, loc
);
5274 var
->set_is_closure();
5275 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5276 // Note that the new variable is not in any binding contour.
5278 return this->closure_var_
;
5281 // Set the type of the closure variable.
5284 Function::set_closure_type()
5286 if (this->closure_var_
== NULL
)
5288 Named_object
* closure
= this->closure_var_
;
5289 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5291 // The first field of a closure is always a pointer to the function
5293 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5294 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5297 unsigned int index
= 1;
5298 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5299 p
!= this->closure_fields_
.end();
5302 Named_object
* no
= p
->first
;
5304 snprintf(buf
, sizeof buf
, "%u", index
);
5305 std::string n
= no
->name() + buf
;
5307 if (no
->is_variable())
5308 var_type
= no
->var_value()->type();
5310 var_type
= no
->result_var_value()->type();
5311 Type
* field_type
= Type::make_pointer_type(var_type
);
5312 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5316 // Return whether this function is a method.
5319 Function::is_method() const
5321 return this->type_
->is_method();
5324 // Add a label definition.
5327 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5330 Label
* lnull
= NULL
;
5331 std::pair
<Labels::iterator
, bool> ins
=
5332 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5334 if (label_name
== "_")
5336 label
= Label::create_dummy_label();
5338 ins
.first
->second
= label
;
5340 else if (ins
.second
)
5342 // This is a new label.
5343 label
= new Label(label_name
);
5344 ins
.first
->second
= label
;
5348 // The label was already in the hash table.
5349 label
= ins
.first
->second
;
5350 if (label
->is_defined())
5352 go_error_at(location
, "label %qs already defined",
5353 Gogo::message_name(label_name
).c_str());
5354 go_inform(label
->location(), "previous definition of %qs was here",
5355 Gogo::message_name(label_name
).c_str());
5356 return new Label(label_name
);
5360 label
->define(location
, gogo
->bindings_snapshot(location
));
5362 // Issue any errors appropriate for any previous goto's to this
5364 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5365 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5368 (*p
)->check_goto_to(gogo
->current_block());
5369 label
->clear_refs();
5374 // Add a reference to a label.
5377 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5378 Location location
, bool issue_goto_errors
)
5380 Label
* lnull
= NULL
;
5381 std::pair
<Labels::iterator
, bool> ins
=
5382 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5386 // The label was already in the hash table.
5387 label
= ins
.first
->second
;
5391 go_assert(ins
.first
->second
== NULL
);
5392 label
= new Label(label_name
);
5393 ins
.first
->second
= label
;
5396 label
->set_is_used();
5398 if (issue_goto_errors
)
5400 Bindings_snapshot
* snapshot
= label
->snapshot();
5401 if (snapshot
!= NULL
)
5402 snapshot
->check_goto_from(gogo
->current_block(), location
);
5404 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5410 // Warn about labels that are defined but not used.
5413 Function::check_labels() const
5415 for (Labels::const_iterator p
= this->labels_
.begin();
5416 p
!= this->labels_
.end();
5419 Label
* label
= p
->second
;
5420 if (!label
->is_used())
5421 go_error_at(label
->location(), "label %qs defined and not used",
5422 Gogo::message_name(label
->name()).c_str());
5426 // Swap one function with another. This is used when building the
5427 // thunk we use to call a function which calls recover. It may not
5428 // work for any other case.
5431 Function::swap_for_recover(Function
*x
)
5433 go_assert(this->enclosing_
== x
->enclosing_
);
5434 std::swap(this->results_
, x
->results_
);
5435 std::swap(this->closure_var_
, x
->closure_var_
);
5436 std::swap(this->block_
, x
->block_
);
5437 go_assert(this->location_
== x
->location_
);
5438 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5439 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5442 // Traverse the tree.
5445 Function::traverse(Traverse
* traverse
)
5447 unsigned int traverse_mask
= traverse
->traverse_mask();
5450 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5453 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5454 return TRAVERSE_EXIT
;
5457 // FIXME: We should check traverse_functions here if nested
5458 // functions are stored in block bindings.
5459 if (this->block_
!= NULL
5461 & (Traverse::traverse_variables
5462 | Traverse::traverse_constants
5463 | Traverse::traverse_blocks
5464 | Traverse::traverse_statements
5465 | Traverse::traverse_expressions
5466 | Traverse::traverse_types
)) != 0)
5468 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5469 return TRAVERSE_EXIT
;
5472 return TRAVERSE_CONTINUE
;
5475 // Work out types for unspecified variables and constants.
5478 Function::determine_types()
5480 if (this->block_
!= NULL
)
5481 this->block_
->determine_types();
5484 // Return the function descriptor, the value you get when you refer to
5485 // the function in Go code without calling it.
5488 Function::descriptor(Gogo
*, Named_object
* no
)
5490 go_assert(!this->is_method());
5491 go_assert(this->closure_var_
== NULL
);
5492 if (this->descriptor_
== NULL
)
5493 this->descriptor_
= Expression::make_func_descriptor(no
);
5494 return this->descriptor_
;
5497 // Get a pointer to the variable representing the defer stack for this
5498 // function, making it if necessary. The value of the variable is set
5499 // by the runtime routines to true if the function is returning,
5500 // rather than panicing through. A pointer to this variable is used
5501 // as a marker for the functions on the defer stack associated with
5502 // this function. A function-specific variable permits inlining a
5503 // function which uses defer.
5506 Function::defer_stack(Location location
)
5508 if (this->defer_stack_
== NULL
)
5510 Type
* t
= Type::lookup_bool_type();
5511 Expression
* n
= Expression::make_boolean(false, location
);
5512 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5513 this->defer_stack_
->set_is_address_taken();
5515 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5517 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5520 // Export the function.
5523 Function::export_func(Export
* exp
, const std::string
& name
) const
5525 Block
* block
= NULL
;
5526 if (this->export_for_inlining())
5527 block
= this->block_
;
5528 Function::export_func_with_type(exp
, name
, this->type_
, this->results_
,
5529 this->is_method() && this->nointerface(),
5530 block
, this->location_
);
5533 // Export a function with a type.
5536 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
5537 const Function_type
* fntype
,
5538 Function::Results
* result_vars
,
5539 bool nointerface
, Block
* block
, Location loc
)
5541 exp
->write_c_string("func ");
5545 go_assert(fntype
->is_method());
5546 exp
->write_c_string("/*nointerface*/ ");
5549 if (fntype
->is_method())
5551 exp
->write_c_string("(");
5552 const Typed_identifier
* receiver
= fntype
->receiver();
5553 exp
->write_name(receiver
->name());
5554 exp
->write_escape(receiver
->note());
5555 exp
->write_c_string(" ");
5556 exp
->write_type(receiver
->type());
5557 exp
->write_c_string(") ");
5560 exp
->write_string(name
);
5562 exp
->write_c_string(" (");
5563 const Typed_identifier_list
* parameters
= fntype
->parameters();
5564 if (parameters
!= NULL
)
5567 bool is_varargs
= fntype
->is_varargs();
5569 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5570 p
!= parameters
->end();
5576 exp
->write_c_string(", ");
5577 exp
->write_name(p
->name());
5578 exp
->write_escape(p
->note());
5579 exp
->write_c_string(" ");
5580 if (!is_varargs
|| p
+ 1 != parameters
->end())
5581 exp
->write_type(p
->type());
5584 exp
->write_c_string("...");
5585 exp
->write_type(p
->type()->array_type()->element_type());
5589 exp
->write_c_string(")");
5591 const Typed_identifier_list
* result_decls
= fntype
->results();
5592 if (result_decls
!= NULL
)
5594 if (result_decls
->size() == 1
5595 && result_decls
->begin()->name().empty()
5598 exp
->write_c_string(" ");
5599 exp
->write_type(result_decls
->begin()->type());
5603 exp
->write_c_string(" (");
5605 Results::const_iterator pr
;
5606 if (result_vars
!= NULL
)
5607 pr
= result_vars
->begin();
5608 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
5609 pd
!= result_decls
->end();
5615 exp
->write_c_string(", ");
5616 // We only use pr->name, which may be artificial, if
5617 // need it for inlining.
5618 if (block
== NULL
|| result_vars
== NULL
)
5619 exp
->write_name(pd
->name());
5621 exp
->write_name((*pr
)->name());
5622 exp
->write_escape(pd
->note());
5623 exp
->write_c_string(" ");
5624 exp
->write_type(pd
->type());
5625 if (result_vars
!= NULL
)
5628 if (result_vars
!= NULL
)
5629 go_assert(pr
== result_vars
->end());
5630 exp
->write_c_string(")");
5635 exp
->write_c_string("\n");
5639 if (fntype
->is_method())
5642 Export_function_body
efb(exp
, indent
);
5645 efb
.write_c_string("// ");
5646 efb
.write_string(Linemap::location_to_file(block
->start_location()));
5647 efb
.write_char(':');
5649 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
5650 efb
.write_c_string(buf
);
5651 efb
.write_char('\n');
5652 block
->export_block(&efb
);
5654 const std::string
& body(efb
.body());
5656 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
5657 static_cast<unsigned long>(body
.length()));
5658 exp
->write_c_string(buf
);
5660 exp
->write_string(body
);
5664 // Import a function.
5667 Function::import_func(Import
* imp
, std::string
* pname
,
5668 Typed_identifier
** preceiver
,
5669 Typed_identifier_list
** pparameters
,
5670 Typed_identifier_list
** presults
,
5675 imp
->require_c_string("func ");
5677 *nointerface
= false;
5678 if (imp
->match_c_string("/*"))
5680 imp
->require_c_string("/*nointerface*/ ");
5681 *nointerface
= true;
5683 // Only a method can be nointerface.
5684 go_assert(imp
->peek_char() == '(');
5688 if (imp
->peek_char() == '(')
5690 imp
->require_c_string("(");
5691 std::string name
= imp
->read_name();
5692 std::string escape_note
= imp
->read_escape();
5693 imp
->require_c_string(" ");
5694 Type
* rtype
= imp
->read_type();
5695 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5696 (*preceiver
)->set_note(escape_note
);
5697 imp
->require_c_string(") ");
5700 *pname
= imp
->read_identifier();
5702 Typed_identifier_list
* parameters
;
5703 *is_varargs
= false;
5704 imp
->require_c_string(" (");
5705 if (imp
->peek_char() == ')')
5709 parameters
= new Typed_identifier_list();
5712 std::string name
= imp
->read_name();
5713 std::string escape_note
= imp
->read_escape();
5714 imp
->require_c_string(" ");
5716 if (imp
->match_c_string("..."))
5722 Type
* ptype
= imp
->read_type();
5724 ptype
= Type::make_array_type(ptype
, NULL
);
5725 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
5726 t
.set_note(escape_note
);
5727 parameters
->push_back(t
);
5728 if (imp
->peek_char() != ',')
5730 go_assert(!*is_varargs
);
5731 imp
->require_c_string(", ");
5734 imp
->require_c_string(")");
5735 *pparameters
= parameters
;
5737 Typed_identifier_list
* results
;
5738 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
5742 results
= new Typed_identifier_list();
5743 imp
->require_c_string(" ");
5744 if (imp
->peek_char() != '(')
5746 Type
* rtype
= imp
->read_type();
5747 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5751 imp
->require_c_string("(");
5754 std::string name
= imp
->read_name();
5755 std::string note
= imp
->read_escape();
5756 imp
->require_c_string(" ");
5757 Type
* rtype
= imp
->read_type();
5758 Typed_identifier t
= Typed_identifier(name
, rtype
,
5761 results
->push_back(t
);
5762 if (imp
->peek_char() != ',')
5764 imp
->require_c_string(", ");
5766 imp
->require_c_string(")");
5769 *presults
= results
;
5771 if (!imp
->match_c_string(" <inl:"))
5773 imp
->require_semicolon_if_old_version();
5774 imp
->require_c_string("\n");
5779 imp
->require_c_string(" <inl:");
5784 c
= imp
->peek_char();
5785 if (c
< '0' || c
> '9')
5790 imp
->require_c_string(">\n");
5794 long llen
= strtol(lenstr
.c_str(), &end
, 10);
5797 || (llen
== LONG_MAX
&& errno
== ERANGE
))
5799 go_error_at(imp
->location(), "invalid inline function length %s",
5804 *body
= imp
->read(static_cast<size_t>(llen
));
5808 // Get the backend representation.
5811 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5813 if (this->fndecl_
== NULL
)
5815 unsigned int flags
= 0;
5816 bool is_init_fn
= false;
5817 if (no
->package() != NULL
)
5819 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5821 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5822 && !this->type_
->is_method())
5824 else if (no
->name() == gogo
->get_init_fn_name())
5826 flags
|= Backend::function_is_visible
;
5829 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5830 && gogo
->is_main_package())
5831 flags
|= Backend::function_is_visible
;
5832 // Methods have to be public even if they are hidden because
5833 // they can be pulled into type descriptors when using
5834 // anonymous fields.
5835 else if (!Gogo::is_hidden_name(no
->name())
5836 || this->type_
->is_method())
5838 if (!this->is_unnamed_type_stub_method_
)
5839 flags
|= Backend::function_is_visible
;
5843 if (this->type_
->is_method())
5844 rtype
= this->type_
->receiver()->type();
5846 std::string asm_name
;
5847 if (!this->asm_name_
.empty())
5849 asm_name
= this->asm_name_
;
5851 // If an assembler name is explicitly specified, there must
5852 // be some reason to refer to the symbol from a different
5854 flags
|= Backend::function_is_visible
;
5856 else if (is_init_fn
)
5858 // These names appear in the export data and are used
5859 // directly in the assembler code. If we change this here
5860 // we need to change Gogo::init_imports.
5861 asm_name
= no
->name();
5864 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
5866 // If a function calls the predeclared recover function, we
5867 // can't inline it, because recover behaves differently in a
5868 // function passed directly to defer. If this is a recover
5869 // thunk that we built to test whether a function can be
5870 // recovered, we can't inline it, because that will mess up
5871 // our return address comparison.
5872 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5874 // If a function calls __go_set_defer_retaddr, then mark it as
5875 // uninlinable. This prevents the GCC backend from splitting
5876 // the function; splitting the function is a bad idea because we
5877 // want the return address label to be in the same function as
5879 if (this->calls_defer_retaddr_
)
5880 is_inlinable
= false;
5882 // Check the //go:noinline compiler directive.
5883 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
5884 is_inlinable
= false;
5887 flags
|= Backend::function_is_inlinable
;
5889 // If this is a thunk created to call a function which calls
5890 // the predeclared recover function, we need to disable
5891 // stack splitting for the thunk.
5892 bool disable_split_stack
= this->is_recover_thunk_
;
5894 // Check the //go:nosplit compiler directive.
5895 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
5896 disable_split_stack
= true;
5898 if (disable_split_stack
)
5899 flags
|= Backend::function_no_split_stack
;
5901 // This should go into a unique section if that has been
5902 // requested elsewhere, or if this is a nointerface function.
5903 // We want to put a nointerface function into a unique section
5904 // because there is a good chance that the linker garbage
5905 // collection can discard it.
5906 if (this->in_unique_section_
5907 || (this->is_method() && this->nointerface()))
5908 flags
|= Backend::function_in_unique_section
;
5910 if (this->is_inline_only_
)
5911 flags
|= Backend::function_only_inline
;
5913 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5915 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5916 flags
, this->location());
5918 return this->fndecl_
;
5921 // Get the backend representation.
5924 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5926 if (this->fndecl_
== NULL
)
5928 unsigned int flags
=
5929 (Backend::function_is_visible
5930 | Backend::function_is_declaration
5931 | Backend::function_is_inlinable
);
5933 // Let Go code use an asm declaration to pick up a builtin
5935 if (!this->asm_name_
.empty())
5937 Bfunction
* builtin_decl
=
5938 gogo
->backend()->lookup_builtin(this->asm_name_
);
5939 if (builtin_decl
!= NULL
)
5941 this->fndecl_
= builtin_decl
;
5942 return this->fndecl_
;
5945 if (this->asm_name_
== "runtime.gopanic"
5946 || this->asm_name_
== "__go_runtime_error")
5947 flags
|= Backend::function_does_not_return
;
5950 std::string asm_name
;
5951 if (this->asm_name_
.empty())
5954 if (this->fntype_
->is_method())
5955 rtype
= this->fntype_
->receiver()->type();
5956 asm_name
= gogo
->function_asm_name(no
->name(), no
->package(), rtype
);
5958 else if (go_id_needs_encoding(no
->get_id(gogo
)))
5959 asm_name
= go_encode_id(no
->get_id(gogo
));
5961 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5963 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5964 flags
, this->location());
5967 return this->fndecl_
;
5970 // Build the descriptor for a function declaration. This won't
5971 // necessarily happen if the package has just a declaration for the
5972 // function and no other reference to it, but we may still need the
5973 // descriptor for references from other packages.
5975 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5977 if (this->descriptor_
!= NULL
)
5979 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5980 this->descriptor_
->get_backend(&context
);
5984 // Check that the types used in this declaration's signature are defined.
5985 // Reports errors for any undefined type.
5988 Function_declaration::check_types() const
5990 // Calling Type::base will give errors for any undefined types.
5991 Function_type
* fntype
= this->type();
5992 if (fntype
->receiver() != NULL
)
5993 fntype
->receiver()->type()->base();
5994 if (fntype
->parameters() != NULL
)
5996 const Typed_identifier_list
* params
= fntype
->parameters();
5997 for (Typed_identifier_list::const_iterator p
= params
->begin();
6004 // Return the function's decl after it has been built.
6007 Function::get_decl() const
6009 go_assert(this->fndecl_
!= NULL
);
6010 return this->fndecl_
;
6013 // Build the backend representation for the function code.
6016 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6018 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6020 // A list of parameter variables for this function.
6021 std::vector
<Bvariable
*> param_vars
;
6023 // Variables that need to be declared for this function and their
6025 std::vector
<Bvariable
*> vars
;
6026 std::vector
<Bexpression
*> var_inits
;
6027 std::vector
<Statement
*> var_decls_stmts
;
6028 for (Bindings::const_definitions_iterator p
=
6029 this->block_
->bindings()->begin_definitions();
6030 p
!= this->block_
->bindings()->end_definitions();
6033 Location loc
= (*p
)->location();
6034 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6036 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6037 Bvariable
* parm_bvar
= bvar
;
6039 // We always pass the receiver to a method as a pointer. If
6040 // the receiver is declared as a non-pointer type, then we
6041 // copy the value into a local variable.
6042 if ((*p
)->var_value()->is_receiver()
6043 && !(*p
)->var_value()->type()->is_direct_iface_type())
6045 std::string name
= (*p
)->name() + ".pointer";
6046 Type
* var_type
= (*p
)->var_value()->type();
6047 Variable
* parm_var
=
6048 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6050 Named_object
* parm_no
=
6051 Named_object::make_variable(name
, NULL
, parm_var
);
6052 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6054 vars
.push_back(bvar
);
6055 Expression
* parm_ref
=
6056 Expression::make_var_reference(parm_no
, loc
);
6058 Expression::make_dereference(parm_ref
,
6059 Expression::NIL_CHECK_NEEDED
,
6061 if ((*p
)->var_value()->is_in_heap())
6062 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6063 var_inits
.push_back(parm_ref
->get_backend(&context
));
6065 else if ((*p
)->var_value()->is_in_heap())
6067 // If we take the address of a parameter, then we need
6068 // to copy it into the heap.
6069 std::string parm_name
= (*p
)->name() + ".param";
6070 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6071 false, true, false, loc
);
6072 Named_object
* parm_no
=
6073 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6074 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6076 vars
.push_back(bvar
);
6077 Expression
* var_ref
=
6078 Expression::make_var_reference(parm_no
, loc
);
6079 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6080 var_inits
.push_back(var_ref
->get_backend(&context
));
6082 param_vars
.push_back(parm_bvar
);
6084 else if ((*p
)->is_result_variable())
6086 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6088 Type
* type
= (*p
)->result_var_value()->type();
6090 if (!(*p
)->result_var_value()->is_in_heap())
6092 Btype
* btype
= type
->get_backend(gogo
);
6093 init
= gogo
->backend()->zero_expression(btype
);
6096 init
= Expression::make_allocation(type
,
6097 loc
)->get_backend(&context
);
6099 vars
.push_back(bvar
);
6100 var_inits
.push_back(init
);
6102 else if (this->defer_stack_
!= NULL
6103 && (*p
)->is_variable()
6104 && (*p
)->var_value()->is_non_escaping_address_taken()
6105 && !(*p
)->var_value()->is_in_heap())
6107 // Local variable captured by deferred closure needs to be live
6108 // until the end of the function. We create a top-level
6109 // declaration for it.
6110 // TODO: we don't need to do this if the variable is not captured
6111 // by the defer closure. There is no easy way to check it here,
6112 // so we do this for all address-taken variables for now.
6113 Variable
* var
= (*p
)->var_value();
6114 Temporary_statement
* ts
=
6115 Statement::make_temporary(var
->type(), NULL
, var
->location());
6116 ts
->set_is_address_taken();
6117 var
->set_toplevel_decl(ts
);
6118 var_decls_stmts
.push_back(ts
);
6121 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6123 go_assert(saw_errors());
6127 // If we need a closure variable, make sure to create it.
6128 // It gets installed in the function as a side effect of creation.
6129 if (this->closure_var_
!= NULL
)
6131 go_assert(this->closure_var_
->var_value()->is_closure());
6132 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6135 if (this->block_
!= NULL
)
6137 // Declare variables if necessary.
6138 Bblock
* var_decls
= NULL
;
6139 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6140 Bstatement
* defer_init
= NULL
;
6141 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6144 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6145 this->block_
->start_location(),
6146 this->block_
->end_location());
6148 if (this->defer_stack_
!= NULL
)
6150 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6152 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6153 var_decls_bstmt_list
.push_back(defer_init
);
6154 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6155 p
!= var_decls_stmts
.end();
6158 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6159 var_decls_bstmt_list
.push_back(bstmt
);
6164 // Build the backend representation for all the statements in the
6166 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6167 Bblock
* code_block
= this->block_
->get_backend(&context
);
6169 // Initialize variables if necessary.
6170 std::vector
<Bstatement
*> init
;
6171 go_assert(vars
.size() == var_inits
.size());
6172 for (size_t i
= 0; i
< vars
.size(); ++i
)
6174 Bstatement
* init_stmt
=
6175 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6177 init
.push_back(init_stmt
);
6179 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6181 // Initialize all variables before executing this code block.
6182 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6183 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6185 // If we have a defer stack, initialize it at the start of a
6187 Bstatement
* except
= NULL
;
6188 Bstatement
* fini
= NULL
;
6189 if (defer_init
!= NULL
)
6191 // Clean up the defer stack when we leave the function.
6192 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6194 // Wrap the code for this function in an exception handler to handle
6197 gogo
->backend()->exception_handler_statement(code_stmt
,
6202 // Stick the code into the block we built for the receiver, if
6204 if (var_decls
!= NULL
)
6206 var_decls_bstmt_list
.push_back(code_stmt
);
6207 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6208 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6211 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6213 go_assert(saw_errors());
6218 // If we created a descriptor for the function, make sure we emit it.
6219 if (this->descriptor_
!= NULL
)
6221 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6222 this->descriptor_
->get_backend(&context
);
6226 // Build the wrappers around function code needed if the function has
6227 // any defer statements. This sets *EXCEPT to an exception handler
6228 // and *FINI to a finally handler.
6231 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6232 Bstatement
** except
, Bstatement
** fini
)
6234 Location end_loc
= this->block_
->end_location();
6236 // Add an exception handler. This is used if a panic occurs. Its
6237 // purpose is to stop the stack unwinding if a deferred function
6238 // calls recover. There are more details in
6239 // libgo/runtime/go-unwind.c.
6241 std::vector
<Bstatement
*> stmts
;
6242 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6243 this->defer_stack(end_loc
));
6244 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6245 Bexpression
* defer
= call
->get_backend(&context
);
6246 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6248 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6249 if (ret_bstmt
!= NULL
)
6250 stmts
.push_back(ret_bstmt
);
6252 go_assert(*except
== NULL
);
6253 *except
= gogo
->backend()->statement_list(stmts
);
6255 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6256 this->defer_stack(end_loc
));
6257 defer
= call
->get_backend(&context
);
6259 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
6260 this->defer_stack(end_loc
));
6261 Bexpression
* undefer
= call
->get_backend(&context
);
6262 Bstatement
* function_defer
=
6263 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6265 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6266 if (this->type_
->results() != NULL
6267 && !this->type_
->results()->empty()
6268 && !this->type_
->results()->front().name().empty())
6270 // If the result variables are named, and we are returning from
6271 // this function rather than panicing through it, we need to
6272 // return them again, because they might have been changed by a
6273 // defer function. The runtime routines set the defer_stack
6274 // variable to true if we are returning from this function.
6276 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6277 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6279 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6281 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6282 Bexpression
* bref
= ref
->get_backend(&context
);
6283 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6284 NULL
, bref
, ret
, NULL
,
6286 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6289 go_assert(*fini
== NULL
);
6290 *fini
= gogo
->backend()->statement_list(stmts
);
6293 // Return the statement that assigns values to this function's result struct.
6296 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6297 Location location
) const
6299 const Typed_identifier_list
* results
= this->type_
->results();
6300 if (results
== NULL
|| results
->empty())
6303 go_assert(this->results_
!= NULL
);
6304 if (this->results_
->size() != results
->size())
6306 go_assert(saw_errors());
6307 return gogo
->backend()->error_statement();
6310 std::vector
<Bexpression
*> vals(results
->size());
6311 for (size_t i
= 0; i
< vals
.size(); ++i
)
6313 Named_object
* no
= (*this->results_
)[i
];
6314 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6315 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6316 if (no
->result_var_value()->is_in_heap())
6318 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6319 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6323 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6328 Block::Block(Block
* enclosing
, Location location
)
6329 : enclosing_(enclosing
), statements_(),
6330 bindings_(new Bindings(enclosing
== NULL
6332 : enclosing
->bindings())),
6333 start_location_(location
),
6334 end_location_(Linemap::unknown_location())
6338 // Add a statement to a block.
6341 Block::add_statement(Statement
* statement
)
6343 this->statements_
.push_back(statement
);
6346 // Add a statement to the front of a block. This is slow but is only
6347 // used for reference counts of parameters.
6350 Block::add_statement_at_front(Statement
* statement
)
6352 this->statements_
.insert(this->statements_
.begin(), statement
);
6355 // Replace a statement in a block.
6358 Block::replace_statement(size_t index
, Statement
* s
)
6360 go_assert(index
< this->statements_
.size());
6361 this->statements_
[index
] = s
;
6364 // Add a statement before another statement.
6367 Block::insert_statement_before(size_t index
, Statement
* s
)
6369 go_assert(index
< this->statements_
.size());
6370 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6373 // Add a statement after another statement.
6376 Block::insert_statement_after(size_t index
, Statement
* s
)
6378 go_assert(index
< this->statements_
.size());
6379 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6382 // Traverse the tree.
6385 Block::traverse(Traverse
* traverse
)
6387 unsigned int traverse_mask
= traverse
->traverse_mask();
6389 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6391 int t
= traverse
->block(this);
6392 if (t
== TRAVERSE_EXIT
)
6393 return TRAVERSE_EXIT
;
6394 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6395 return TRAVERSE_CONTINUE
;
6399 & (Traverse::traverse_variables
6400 | Traverse::traverse_constants
6401 | Traverse::traverse_expressions
6402 | Traverse::traverse_types
)) != 0)
6404 const unsigned int e_or_t
= (Traverse::traverse_expressions
6405 | Traverse::traverse_types
);
6406 const unsigned int e_or_t_or_s
= (e_or_t
6407 | Traverse::traverse_statements
);
6408 for (Bindings::const_definitions_iterator pb
=
6409 this->bindings_
->begin_definitions();
6410 pb
!= this->bindings_
->end_definitions();
6413 int t
= TRAVERSE_CONTINUE
;
6414 switch ((*pb
)->classification())
6416 case Named_object::NAMED_OBJECT_CONST
:
6417 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
6418 t
= traverse
->constant(*pb
, false);
6419 if (t
== TRAVERSE_CONTINUE
6420 && (traverse_mask
& e_or_t
) != 0)
6422 Type
* tc
= (*pb
)->const_value()->type();
6424 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
6425 return TRAVERSE_EXIT
;
6426 t
= (*pb
)->const_value()->traverse_expression(traverse
);
6430 case Named_object::NAMED_OBJECT_VAR
:
6431 case Named_object::NAMED_OBJECT_RESULT_VAR
:
6432 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
6433 t
= traverse
->variable(*pb
);
6434 if (t
== TRAVERSE_CONTINUE
6435 && (traverse_mask
& e_or_t
) != 0)
6437 if ((*pb
)->is_result_variable()
6438 || (*pb
)->var_value()->has_type())
6440 Type
* tv
= ((*pb
)->is_variable()
6441 ? (*pb
)->var_value()->type()
6442 : (*pb
)->result_var_value()->type());
6444 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
6445 return TRAVERSE_EXIT
;
6448 if (t
== TRAVERSE_CONTINUE
6449 && (traverse_mask
& e_or_t_or_s
) != 0
6450 && (*pb
)->is_variable())
6451 t
= (*pb
)->var_value()->traverse_expression(traverse
,
6455 case Named_object::NAMED_OBJECT_FUNC
:
6456 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
6459 case Named_object::NAMED_OBJECT_TYPE
:
6460 if ((traverse_mask
& e_or_t
) != 0)
6461 t
= Type::traverse((*pb
)->type_value(), traverse
);
6464 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
6465 case Named_object::NAMED_OBJECT_UNKNOWN
:
6466 case Named_object::NAMED_OBJECT_ERRONEOUS
:
6469 case Named_object::NAMED_OBJECT_PACKAGE
:
6470 case Named_object::NAMED_OBJECT_SINK
:
6477 if (t
== TRAVERSE_EXIT
)
6478 return TRAVERSE_EXIT
;
6482 // No point in checking traverse_mask here--if we got here we always
6483 // want to walk the statements. The traversal can insert new
6484 // statements before or after the current statement. Inserting
6485 // statements before the current statement requires updating I via
6486 // the pointer; those statements will not be traversed. Any new
6487 // statements inserted after the current statement will be traversed
6489 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6491 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6492 return TRAVERSE_EXIT
;
6495 return TRAVERSE_CONTINUE
;
6498 // Work out types for unspecified variables and constants.
6501 Block::determine_types()
6503 for (Bindings::const_definitions_iterator pb
=
6504 this->bindings_
->begin_definitions();
6505 pb
!= this->bindings_
->end_definitions();
6508 if ((*pb
)->is_variable())
6509 (*pb
)->var_value()->determine_type();
6510 else if ((*pb
)->is_const())
6511 (*pb
)->const_value()->determine_type();
6514 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6515 ps
!= this->statements_
.end();
6517 (*ps
)->determine_types();
6520 // Return true if the statements in this block may fall through.
6523 Block::may_fall_through() const
6525 if (this->statements_
.empty())
6527 return this->statements_
.back()->may_fall_through();
6530 // Write export data for a block.
6533 Block::export_block(Export_function_body
* efb
)
6535 for (Block::iterator p
= this->begin();
6541 efb
->increment_indent();
6542 (*p
)->export_statement(efb
);
6543 efb
->decrement_indent();
6545 Location loc
= (*p
)->location();
6546 if ((*p
)->is_block_statement())
6548 // For a block we put the start location on the first brace
6549 // in Block_statement::do_export_statement. Here we put the
6550 // end location on the final brace.
6551 loc
= (*p
)->block_statement()->block()->end_location();
6554 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
6555 efb
->write_c_string(buf
);
6559 // Add exported block data to SET, reading from BODY starting at OFF.
6560 // Returns whether the import succeeded.
6563 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
6565 Location eloc
= ifb
->location();
6566 Location sloc
= loc
;
6567 const std::string
& body(ifb
->body());
6568 size_t off
= ifb
->off();
6569 while (off
< body
.length())
6571 int indent
= ifb
->indent();
6572 if (off
+ indent
>= body
.length())
6575 "invalid export data for %qs: insufficient indentation",
6576 ifb
->name().c_str());
6579 for (int i
= 0; i
< indent
- 1; i
++)
6581 if (body
[off
+ i
] != ' ')
6584 "invalid export data for %qs: bad indentation",
6585 ifb
->name().c_str());
6590 bool at_end
= false;
6591 if (body
[off
+ indent
- 1] == '}')
6593 else if (body
[off
+ indent
- 1] != ' ')
6596 "invalid export data for %qs: bad indentation",
6597 ifb
->name().c_str());
6603 size_t nl
= body
.find('\n', off
);
6604 if (nl
== std::string::npos
)
6606 go_error_at(eloc
, "invalid export data for %qs: missing newline",
6607 ifb
->name().c_str());
6611 size_t lineno_pos
= body
.find(" //", off
);
6612 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
6614 go_error_at(eloc
, "invalid export data for %qs: missing line number",
6615 ifb
->name().c_str());
6619 unsigned int lineno
= 0;
6620 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
6623 if (c
< '0' || c
> '9')
6626 "invalid export data for %qs: invalid line number",
6627 ifb
->name().c_str());
6630 lineno
= lineno
* 10 + c
- '0';
6633 ifb
->gogo()->linemap()->start_line(lineno
, 1);
6634 sloc
= ifb
->gogo()->linemap()->get_location(0);
6643 Statement
* s
= Statement::import_statement(ifb
, sloc
);
6647 set
->add_statement(s
);
6649 size_t at
= ifb
->off();
6657 set
->set_end_location(sloc
);
6661 // Convert a block to the backend representation.
6664 Block::get_backend(Translate_context
* context
)
6666 Gogo
* gogo
= context
->gogo();
6667 Named_object
* function
= context
->function();
6668 std::vector
<Bvariable
*> vars
;
6669 vars
.reserve(this->bindings_
->size_definitions());
6670 for (Bindings::const_definitions_iterator pv
=
6671 this->bindings_
->begin_definitions();
6672 pv
!= this->bindings_
->end_definitions();
6675 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
6676 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
6679 go_assert(function
!= NULL
);
6680 Bfunction
* bfunction
=
6681 function
->func_value()->get_or_make_decl(gogo
, function
);
6682 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
6683 vars
, this->start_location_
,
6684 this->end_location_
);
6686 Translate_context
subcontext(gogo
, function
, this, ret
);
6687 std::vector
<Bstatement
*> bstatements
;
6688 bstatements
.reserve(this->statements_
.size());
6689 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
6690 p
!= this->statements_
.end();
6692 bstatements
.push_back((*p
)->get_backend(&subcontext
));
6694 context
->backend()->block_add_statements(ret
, bstatements
);
6699 // Class Bindings_snapshot.
6701 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
6702 : block_(b
), counts_(), location_(location
)
6706 this->counts_
.push_back(b
->bindings()->size_definitions());
6711 // Report errors appropriate for a goto from B to this.
6714 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
6717 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
6719 this->check_goto_defs(loc
, this->block_
,
6720 this->block_
->bindings()->size_definitions(),
6724 // Report errors appropriate for a goto from this to B.
6727 Bindings_snapshot::check_goto_to(const Block
* b
)
6730 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
6732 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
6733 b
->bindings()->size_definitions());
6736 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6737 // Return true if all is well, false if we reported an error. If this
6738 // returns true, it sets *PINDEX to the number of blocks BTO is above
6742 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
6743 const Block
* bto
, size_t* pindex
)
6745 // It is an error if BTO is not either BFROM or above BFROM.
6747 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
6751 go_error_at(loc
, "goto jumps into block");
6752 go_inform(bto
->start_location(), "goto target block starts here");
6760 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6761 // CFROM is the number of names defined at the point of the goto and
6762 // CTO is the number of names defined at the point of the label.
6765 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
6766 size_t cfrom
, size_t cto
)
6770 Bindings::const_definitions_iterator p
=
6771 block
->bindings()->begin_definitions();
6772 for (size_t i
= 0; i
< cfrom
; ++i
)
6774 go_assert(p
!= block
->bindings()->end_definitions());
6777 go_assert(p
!= block
->bindings()->end_definitions());
6779 for (; p
!= block
->bindings()->end_definitions(); ++p
)
6781 if ((*p
)->is_variable())
6783 std::string n
= (*p
)->message_name();
6784 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
6785 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
6791 // Class Function_declaration.
6793 // Whether this declares a method.
6796 Function_declaration::is_method() const
6798 return this->fntype_
->is_method();
6801 // Whether this method should not be included in the type descriptor.
6804 Function_declaration::nointerface() const
6806 go_assert(this->is_method());
6807 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
6810 // Record that this method should not be included in the type
6814 Function_declaration::set_nointerface()
6816 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
6819 // Import an inlinable function. This is used for an inlinable
6820 // function whose body is recorded in the export data. Parse the
6821 // export data into a Block and create a regular function using that
6822 // Block as its body. Redeclare this function declaration as the
6826 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
6828 go_assert(no
->func_declaration_value() == this);
6829 go_assert(no
->package() != NULL
);
6830 const std::string
& body(this->imported_body_
);
6831 go_assert(!body
.empty());
6833 // Read the "//FILE:LINE" comment starts the export data.
6836 if (this->is_method())
6839 for (; i
< indent
; i
++)
6841 if (body
.at(i
) != ' ')
6843 go_error_at(this->location_
,
6844 "invalid export body for %qs: bad initial indentation",
6845 no
->message_name().c_str());
6850 if (body
.substr(i
, 2) != "//")
6852 go_error_at(this->location_
,
6853 "invalid export body for %qs: missing file comment",
6854 no
->message_name().c_str());
6858 size_t colon
= body
.find(':', i
+ 2);
6859 size_t nl
= body
.find('\n', i
+ 2);
6860 if (nl
== std::string::npos
)
6862 go_error_at(this->location_
,
6863 "invalid export body for %qs: missing file name",
6864 no
->message_name().c_str());
6867 if (colon
== std::string::npos
|| nl
< colon
)
6869 go_error_at(this->location_
,
6870 "invalid export body for %qs: missing initial line number",
6871 no
->message_name().c_str());
6875 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
6876 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
6878 long linenol
= strtol(linestr
.c_str(), &end
, 10);
6881 go_error_at(this->location_
,
6882 "invalid export body for %qs: invalid initial line number",
6883 no
->message_name().c_str());
6886 unsigned int lineno
= static_cast<unsigned int>(linenol
);
6888 // Turn the file/line into a location.
6890 char* alc
= new char[file
.length() + 1];
6891 memcpy(alc
, file
.data(), file
.length());
6892 alc
[file
.length()] = '\0';
6893 gogo
->linemap()->start_file(alc
, lineno
);
6894 gogo
->linemap()->start_line(lineno
, 1);
6895 Location start_loc
= gogo
->linemap()->get_location(0);
6897 // Define the function with an outer block that declares the
6900 Function_type
* fntype
= this->fntype_
;
6902 Block
* outer
= new Block(NULL
, start_loc
);
6904 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
6905 fn
->set_is_inline_only();
6907 if (fntype
->is_method())
6909 if (this->nointerface())
6910 fn
->set_nointerface();
6911 const Typed_identifier
* receiver
= fntype
->receiver();
6912 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
6913 true, true, start_loc
);
6915 std::string rname
= receiver
->name();
6916 unsigned rcounter
= 0;
6918 // We need to give a nameless receiver a name to avoid having it
6919 // clash with some other nameless param. FIXME.
6920 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
6922 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
6925 const Typed_identifier_list
* params
= fntype
->parameters();
6926 bool is_varargs
= fntype
->is_varargs();
6927 unsigned pcounter
= 0;
6930 for (Typed_identifier_list::const_iterator p
= params
->begin();
6934 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
6936 if (is_varargs
&& p
+ 1 == params
->end())
6937 param
->set_is_varargs_parameter();
6939 std::string pname
= p
->name();
6941 // We need to give each nameless parameter a non-empty name to avoid
6942 // having it clash with some other nameless param. FIXME.
6943 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
6945 outer
->bindings()->add_variable(pname
, NULL
, param
);
6949 fn
->create_result_variables(gogo
);
6951 if (!fntype
->is_method())
6953 const Package
* package
= no
->package();
6954 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
6958 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
6959 go_assert(rtype
!= NULL
);
6960 no
= rtype
->add_method(no
->name(), fn
);
6963 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
6965 if (!Block::import_block(outer
, &ifb
, start_loc
))
6968 gogo
->lower_block(no
, outer
);
6970 gogo
->add_imported_inline_function(no
);
6973 // Return the function descriptor.
6976 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
6978 go_assert(!this->fntype_
->is_method());
6979 if (this->descriptor_
== NULL
)
6980 this->descriptor_
= Expression::make_func_descriptor(no
);
6981 return this->descriptor_
;
6986 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
6987 bool is_parameter
, bool is_receiver
,
6989 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
6990 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
6991 is_closure_(false), is_receiver_(is_receiver
),
6992 is_varargs_parameter_(false), is_used_(false),
6993 is_address_taken_(false), is_non_escaping_address_taken_(false),
6994 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6995 type_from_init_tuple_(false), type_from_range_index_(false),
6996 type_from_range_value_(false), type_from_chan_element_(false),
6997 is_type_switch_var_(false), determined_type_(false),
6998 in_unique_section_(false), toplevel_decl_(NULL
)
7000 go_assert(type
!= NULL
|| init
!= NULL
);
7001 go_assert(!is_parameter
|| init
== NULL
);
7004 // Traverse the initializer expression.
7007 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7009 if (this->preinit_
!= NULL
)
7011 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7012 return TRAVERSE_EXIT
;
7014 if (this->init_
!= NULL
7016 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7019 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7020 return TRAVERSE_EXIT
;
7022 return TRAVERSE_CONTINUE
;
7025 // Lower the initialization expression after parsing is complete.
7028 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7029 Statement_inserter
* inserter
)
7031 Named_object
* dep
= gogo
->var_depends_on(this);
7032 if (dep
!= NULL
&& dep
->is_variable())
7033 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7035 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7039 // We will give an error elsewhere, this is just to prevent
7040 // an infinite loop.
7045 Statement_inserter global_inserter
;
7046 if (this->is_global_
)
7048 global_inserter
= Statement_inserter(gogo
, this);
7049 inserter
= &global_inserter
;
7052 gogo
->lower_expression(function
, inserter
, &this->init_
);
7054 this->seen_
= false;
7056 this->init_is_lowered_
= true;
7060 // Flatten the initialization expression after ordering evaluations.
7063 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7064 Statement_inserter
* inserter
)
7066 Named_object
* dep
= gogo
->var_depends_on(this);
7067 if (dep
!= NULL
&& dep
->is_variable())
7068 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7070 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7074 // We will give an error elsewhere, this is just to prevent
7075 // an infinite loop.
7080 Statement_inserter global_inserter
;
7081 if (this->is_global_
)
7083 global_inserter
= Statement_inserter(gogo
, this);
7084 inserter
= &global_inserter
;
7087 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7089 // If an interface conversion is needed, we need a temporary
7091 if (this->type_
!= NULL
7092 && !Type::are_identical(this->type_
, this->init_
->type(),
7093 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7095 && this->init_
->type()->interface_type() != NULL
7096 && !this->init_
->is_variable())
7098 Temporary_statement
* temp
=
7099 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7100 inserter
->insert(temp
);
7101 this->init_
= Expression::make_temporary_reference(temp
,
7105 this->seen_
= false;
7106 this->init_is_flattened_
= true;
7110 // Get the preinit block.
7113 Variable::preinit_block(Gogo
* gogo
)
7115 go_assert(this->is_global_
);
7116 if (this->preinit_
== NULL
)
7117 this->preinit_
= new Block(NULL
, this->location());
7119 // If a global variable has a preinitialization statement, then we
7120 // need to have an initialization function.
7121 gogo
->set_need_init_fn();
7123 return this->preinit_
;
7126 // Add a statement to be run before the initialization expression.
7129 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7131 Block
* b
= this->preinit_block(gogo
);
7132 b
->add_statement(s
);
7133 b
->set_end_location(s
->location());
7136 // Whether this variable has a type.
7139 Variable::has_type() const
7141 if (this->type_
== NULL
)
7144 // A variable created in a type switch case nil does not actually
7145 // have a type yet. It will be changed to use the initializer's
7146 // type in determine_type.
7147 if (this->is_type_switch_var_
7148 && this->type_
->is_nil_constant_as_type())
7154 // In an assignment which sets a variable to a tuple of EXPR, return
7155 // the type of the first element of the tuple.
7158 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7160 if (expr
->map_index_expression() != NULL
)
7162 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
7164 return Type::make_error_type();
7165 return mt
->val_type();
7167 else if (expr
->receive_expression() != NULL
)
7169 Expression
* channel
= expr
->receive_expression()->channel();
7170 Type
* channel_type
= channel
->type();
7171 if (channel_type
->channel_type() == NULL
)
7172 return Type::make_error_type();
7173 return channel_type
->channel_type()->element_type();
7178 go_error_at(this->location(), "invalid tuple definition");
7179 return Type::make_error_type();
7183 // Given EXPR used in a range clause, return either the index type or
7184 // the value type of the range, depending upon GET_INDEX_TYPE.
7187 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7188 bool report_error
) const
7190 Type
* t
= expr
->type();
7191 if (t
->array_type() != NULL
7192 || (t
->points_to() != NULL
7193 && t
->points_to()->array_type() != NULL
7194 && !t
->points_to()->is_slice_type()))
7197 return Type::lookup_integer_type("int");
7199 return t
->deref()->array_type()->element_type();
7201 else if (t
->is_string_type())
7204 return Type::lookup_integer_type("int");
7206 return Type::lookup_integer_type("int32");
7208 else if (t
->map_type() != NULL
)
7211 return t
->map_type()->key_type();
7213 return t
->map_type()->val_type();
7215 else if (t
->channel_type() != NULL
)
7218 return t
->channel_type()->element_type();
7222 go_error_at(this->location(),
7223 ("invalid definition of value variable "
7224 "for channel range"));
7225 return Type::make_error_type();
7231 go_error_at(this->location(), "invalid type for range clause");
7232 return Type::make_error_type();
7236 // EXPR should be a channel. Return the channel's element type.
7239 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7241 Type
* t
= expr
->type();
7242 if (t
->channel_type() != NULL
)
7243 return t
->channel_type()->element_type();
7247 go_error_at(this->location(), "expected channel");
7248 return Type::make_error_type();
7252 // Return the type of the Variable. This may be called before
7253 // Variable::determine_type is called, which means that we may need to
7254 // get the type from the initializer. FIXME: If we combine lowering
7255 // with type determination, then this should be unnecessary.
7260 // A variable in a type switch with a nil case will have the wrong
7261 // type here. This gets fixed up in determine_type, below.
7262 Type
* type
= this->type_
;
7263 Expression
* init
= this->init_
;
7264 if (this->is_type_switch_var_
7266 && this->type_
->is_nil_constant_as_type())
7268 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7269 go_assert(tge
!= NULL
);
7276 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7278 go_error_at(this->location_
, "variable initializer refers to itself");
7279 this->type_
= Type::make_error_type();
7288 else if (this->type_from_init_tuple_
)
7289 type
= this->type_from_tuple(init
, false);
7290 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7291 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7292 else if (this->type_from_chan_element_
)
7293 type
= this->type_from_chan_element(init
, false);
7296 go_assert(init
!= NULL
);
7297 type
= init
->type();
7298 go_assert(type
!= NULL
);
7300 // Variables should not have abstract types.
7301 if (type
->is_abstract())
7302 type
= type
->make_non_abstract_type();
7304 if (type
->is_void_type())
7305 type
= Type::make_error_type();
7308 this->seen_
= false;
7313 // Fetch the type from a const pointer, in which case it should have
7314 // been set already.
7317 Variable::type() const
7319 go_assert(this->type_
!= NULL
);
7323 // Set the type if necessary.
7326 Variable::determine_type()
7328 if (this->determined_type_
)
7330 this->determined_type_
= true;
7332 if (this->preinit_
!= NULL
)
7333 this->preinit_
->determine_types();
7335 // A variable in a type switch with a nil case will have the wrong
7336 // type here. It will have an initializer which is a type guard.
7337 // We want to initialize it to the value without the type guard, and
7338 // use the type of that value as well.
7339 if (this->is_type_switch_var_
7340 && this->type_
!= NULL
7341 && this->type_
->is_nil_constant_as_type())
7343 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7344 go_assert(tge
!= NULL
);
7346 this->init_
= tge
->expr();
7349 if (this->init_
== NULL
)
7350 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7351 else if (this->type_from_init_tuple_
)
7353 Expression
*init
= this->init_
;
7354 init
->determine_type_no_context();
7355 this->type_
= this->type_from_tuple(init
, true);
7358 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7360 Expression
* init
= this->init_
;
7361 init
->determine_type_no_context();
7362 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7366 else if (this->type_from_chan_element_
)
7368 Expression
* init
= this->init_
;
7369 init
->determine_type_no_context();
7370 this->type_
= this->type_from_chan_element(init
, true);
7375 Type_context
context(this->type_
, false);
7376 this->init_
->determine_type(&context
);
7377 if (this->type_
== NULL
)
7379 Type
* type
= this->init_
->type();
7380 go_assert(type
!= NULL
);
7381 if (type
->is_abstract())
7382 type
= type
->make_non_abstract_type();
7384 if (type
->is_void_type())
7386 go_error_at(this->location_
, "variable has no type");
7387 type
= Type::make_error_type();
7389 else if (type
->is_nil_type())
7391 go_error_at(this->location_
, "variable defined to nil type");
7392 type
= Type::make_error_type();
7394 else if (type
->is_call_multiple_result_type())
7396 go_error_at(this->location_
,
7397 "single variable set to multiple-value function call");
7398 type
= Type::make_error_type();
7406 // Get the initial value of a variable. This does not
7407 // consider whether the variable is in the heap--it returns the
7408 // initial value as though it were always stored in the stack.
7411 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7413 go_assert(this->preinit_
== NULL
);
7414 Location loc
= this->location();
7415 if (this->init_
== NULL
)
7417 go_assert(!this->is_parameter_
);
7418 if (this->is_global_
|| this->is_in_heap())
7420 Btype
* btype
= this->type()->get_backend(gogo
);
7421 return gogo
->backend()->zero_expression(btype
);
7425 Translate_context
context(gogo
, function
, NULL
, NULL
);
7426 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7427 return init
->get_backend(&context
);
7431 // Get the initial value of a variable when a block is required.
7432 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7435 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7436 Bvariable
* var_decl
)
7438 go_assert(this->preinit_
!= NULL
);
7440 // We want to add the variable assignment to the end of the preinit
7443 Translate_context
context(gogo
, function
, NULL
, NULL
);
7444 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7445 Bfunction
* bfunction
=
7446 function
->func_value()->get_or_make_decl(gogo
, function
);
7448 // It's possible to have pre-init statements without an initializer
7449 // if the pre-init statements set the variable.
7450 Bstatement
* decl_init
= NULL
;
7451 if (this->init_
!= NULL
)
7453 if (var_decl
== NULL
)
7455 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7456 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7461 Location loc
= this->location();
7462 Expression
* val_expr
=
7463 Expression::make_cast(this->type(), this->init_
, loc
);
7464 Bexpression
* val
= val_expr
->get_backend(&context
);
7465 Bexpression
* var_ref
=
7466 gogo
->backend()->var_expression(var_decl
, loc
);
7467 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7471 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7472 if (decl_init
!= NULL
)
7473 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
7477 // Export the variable
7480 Variable::export_var(Export
* exp
, const std::string
& name
) const
7482 go_assert(this->is_global_
);
7483 exp
->write_c_string("var ");
7484 exp
->write_string(name
);
7485 exp
->write_c_string(" ");
7486 exp
->write_type(this->type());
7487 exp
->write_c_string("\n");
7490 // Import a variable.
7493 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
7495 imp
->require_c_string("var ");
7496 *pname
= imp
->read_identifier();
7497 imp
->require_c_string(" ");
7498 *ptype
= imp
->read_type();
7499 imp
->require_semicolon_if_old_version();
7500 imp
->require_c_string("\n");
7503 // Convert a variable to the backend representation.
7506 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7507 const Package
* package
, const std::string
& name
)
7509 if (this->backend_
== NULL
)
7511 Backend
* backend
= gogo
->backend();
7512 Type
* type
= this->type_
;
7513 if (type
->is_error_type()
7514 || (type
->is_undefined()
7515 && (!this->is_global_
|| package
== NULL
)))
7516 this->backend_
= backend
->error_variable();
7519 bool is_parameter
= this->is_parameter_
;
7520 if (this->is_receiver_
&& !type
->is_direct_iface_type())
7521 is_parameter
= false;
7522 if (this->is_in_heap())
7524 is_parameter
= false;
7525 type
= Type::make_pointer_type(type
);
7528 const std::string n
= Gogo::unpack_hidden_name(name
);
7529 Btype
* btype
= type
->get_backend(gogo
);
7532 if (Map_type::is_zero_value(this))
7533 bvar
= Map_type::backend_zero_value(gogo
);
7534 else if (this->is_global_
)
7536 std::string
var_name(package
!= NULL
7537 ? package
->package_name()
7538 : gogo
->package_name());
7539 var_name
.push_back('.');
7542 std::string
asm_name(gogo
->global_var_asm_name(name
, package
));
7544 bool is_hidden
= Gogo::is_hidden_name(name
);
7545 // Hack to export runtime.writeBarrier. FIXME.
7546 // This is because go:linkname doesn't work on variables.
7547 if (gogo
->compiling_runtime()
7548 && var_name
== "runtime.writeBarrier")
7551 bvar
= backend
->global_variable(var_name
,
7556 this->in_unique_section_
,
7559 else if (function
== NULL
)
7561 go_assert(saw_errors());
7562 bvar
= backend
->error_variable();
7566 Bfunction
* bfunction
= function
->func_value()->get_decl();
7567 bool is_address_taken
= (this->is_non_escaping_address_taken_
7568 && !this->is_in_heap());
7569 if (this->is_closure())
7570 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
7572 else if (is_parameter
)
7573 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
7578 Bvariable
* bvar_decl
= NULL
;
7579 if (this->toplevel_decl_
!= NULL
)
7581 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
7582 bvar_decl
= this->toplevel_decl_
->temporary_statement()
7583 ->get_backend_variable(&context
);
7585 bvar
= backend
->local_variable(bfunction
, n
, btype
,
7591 this->backend_
= bvar
;
7594 return this->backend_
;
7597 // Class Result_variable.
7599 // Convert a result variable to the backend representation.
7602 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7603 const std::string
& name
)
7605 if (this->backend_
== NULL
)
7607 Backend
* backend
= gogo
->backend();
7608 Type
* type
= this->type_
;
7609 if (type
->is_error())
7610 this->backend_
= backend
->error_variable();
7613 if (this->is_in_heap())
7614 type
= Type::make_pointer_type(type
);
7615 Btype
* btype
= type
->get_backend(gogo
);
7616 Bfunction
* bfunction
= function
->func_value()->get_decl();
7617 std::string n
= Gogo::unpack_hidden_name(name
);
7618 bool is_address_taken
= (this->is_non_escaping_address_taken_
7619 && !this->is_in_heap());
7620 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
7621 NULL
, is_address_taken
,
7625 return this->backend_
;
7628 // Class Named_constant.
7630 // Set the type of a named constant. This is only used to set the
7631 // type to an error type.
7634 Named_constant::set_type(Type
* t
)
7636 go_assert(this->type_
== NULL
|| t
->is_error_type());
7640 // Traverse the initializer expression.
7643 Named_constant::traverse_expression(Traverse
* traverse
)
7645 return Expression::traverse(&this->expr_
, traverse
);
7648 // Determine the type of the constant.
7651 Named_constant::determine_type()
7653 if (this->type_
!= NULL
)
7655 Type_context
context(this->type_
, false);
7656 this->expr_
->determine_type(&context
);
7660 // A constant may have an abstract type.
7661 Type_context
context(NULL
, true);
7662 this->expr_
->determine_type(&context
);
7663 this->type_
= this->expr_
->type();
7664 go_assert(this->type_
!= NULL
);
7668 // Indicate that we found and reported an error for this constant.
7671 Named_constant::set_error()
7673 this->type_
= Type::make_error_type();
7674 this->expr_
= Expression::make_error(this->location_
);
7677 // Export a constant.
7680 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
7682 exp
->write_c_string("const ");
7683 exp
->write_string(name
);
7684 exp
->write_c_string(" ");
7685 if (!this->type_
->is_abstract())
7687 exp
->write_type(this->type_
);
7688 exp
->write_c_string(" ");
7690 exp
->write_c_string("= ");
7692 Export_function_body
efb(exp
, 0);
7693 if (!this->type_
->is_abstract())
7694 efb
.set_type_context(this->type_
);
7695 this->expr()->export_expression(&efb
);
7696 exp
->write_string(efb
.body());
7698 exp
->write_c_string("\n");
7701 // Import a constant.
7704 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
7707 imp
->require_c_string("const ");
7708 *pname
= imp
->read_identifier();
7709 imp
->require_c_string(" ");
7710 if (imp
->peek_char() == '=')
7714 *ptype
= imp
->read_type();
7715 imp
->require_c_string(" ");
7717 imp
->require_c_string("= ");
7718 *pexpr
= Expression::import_expression(imp
, imp
->location());
7719 imp
->require_semicolon_if_old_version();
7720 imp
->require_c_string("\n");
7723 // Get the backend representation.
7726 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
7728 if (this->bconst_
== NULL
)
7730 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
7731 Type
* type
= this->type();
7732 Location loc
= this->location();
7734 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
7735 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
7736 if (type
!= NULL
&& type
->is_numeric_type())
7738 Btype
* btype
= type
->get_backend(gogo
);
7739 std::string name
= const_no
->get_id(gogo
);
7741 gogo
->backend()->named_constant_expression(btype
, name
,
7744 this->bconst_
= const_decl
;
7746 return this->bconst_
;
7752 Type_declaration::add_method(const std::string
& name
, Function
* function
)
7754 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
7755 this->methods_
.push_back(ret
);
7759 // Add a method declaration.
7762 Type_declaration::add_method_declaration(const std::string
& name
,
7764 Function_type
* type
,
7767 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
7769 this->methods_
.push_back(ret
);
7773 // Return whether any methods are defined.
7776 Type_declaration::has_methods() const
7778 return !this->methods_
.empty();
7781 // Define methods for the real type.
7784 Type_declaration::define_methods(Named_type
* nt
)
7786 if (this->methods_
.empty())
7789 while (nt
->is_alias())
7791 Type
*t
= nt
->real_type()->forwarded();
7792 if (t
->named_type() != NULL
)
7793 nt
= t
->named_type();
7794 else if (t
->forward_declaration_type() != NULL
)
7796 Named_object
* no
= t
->forward_declaration_type()->named_object();
7797 Type_declaration
* td
= no
->type_declaration_value();
7798 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
7799 this->methods_
.end());
7800 this->methods_
.clear();
7805 for (std::vector
<Named_object
*>::const_iterator p
=
7806 this->methods_
.begin();
7807 p
!= this->methods_
.end();
7809 go_error_at((*p
)->location(),
7810 ("invalid receiver type "
7811 "(receiver must be a named type"));
7816 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
7817 p
!= this->methods_
.end();
7820 if ((*p
)->is_function_declaration()
7821 || !(*p
)->func_value()->is_sink())
7822 nt
->add_existing_method(*p
);
7826 // We are using the type. Return true if we should issue a warning.
7829 Type_declaration::using_type()
7831 bool ret
= !this->issued_warning_
;
7832 this->issued_warning_
= true;
7836 // Class Unknown_name.
7838 // Set the real named object.
7841 Unknown_name::set_real_named_object(Named_object
* no
)
7843 go_assert(this->real_named_object_
== NULL
);
7844 go_assert(!no
->is_unknown());
7845 this->real_named_object_
= no
;
7848 // Class Named_object.
7850 Named_object::Named_object(const std::string
& name
,
7851 const Package
* package
,
7852 Classification classification
)
7853 : name_(name
), package_(package
), classification_(classification
),
7854 is_redefinition_(false)
7856 if (Gogo::is_sink_name(name
))
7857 go_assert(classification
== NAMED_OBJECT_SINK
);
7860 // Make an unknown name. This is used by the parser. The name must
7861 // be resolved later. Unknown names are only added in the current
7865 Named_object::make_unknown_name(const std::string
& name
,
7868 Named_object
* named_object
= new Named_object(name
, NULL
,
7869 NAMED_OBJECT_UNKNOWN
);
7870 Unknown_name
* value
= new Unknown_name(location
);
7871 named_object
->u_
.unknown_value
= value
;
7872 return named_object
;
7878 Named_object::make_constant(const Typed_identifier
& tid
,
7879 const Package
* package
, Expression
* expr
,
7882 Named_object
* named_object
= new Named_object(tid
.name(), package
,
7883 NAMED_OBJECT_CONST
);
7884 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
7887 named_object
->u_
.const_value
= named_constant
;
7888 return named_object
;
7891 // Make a named type.
7894 Named_object::make_type(const std::string
& name
, const Package
* package
,
7895 Type
* type
, Location location
)
7897 Named_object
* named_object
= new Named_object(name
, package
,
7899 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
7900 named_object
->u_
.type_value
= named_type
;
7901 return named_object
;
7904 // Make a type declaration.
7907 Named_object::make_type_declaration(const std::string
& name
,
7908 const Package
* package
,
7911 Named_object
* named_object
= new Named_object(name
, package
,
7912 NAMED_OBJECT_TYPE_DECLARATION
);
7913 Type_declaration
* type_declaration
= new Type_declaration(location
);
7914 named_object
->u_
.type_declaration
= type_declaration
;
7915 return named_object
;
7921 Named_object::make_variable(const std::string
& name
, const Package
* package
,
7924 Named_object
* named_object
= new Named_object(name
, package
,
7926 named_object
->u_
.var_value
= variable
;
7927 return named_object
;
7930 // Make a result variable.
7933 Named_object::make_result_variable(const std::string
& name
,
7934 Result_variable
* result
)
7936 Named_object
* named_object
= new Named_object(name
, NULL
,
7937 NAMED_OBJECT_RESULT_VAR
);
7938 named_object
->u_
.result_var_value
= result
;
7939 return named_object
;
7942 // Make a sink. This is used for the special blank identifier _.
7945 Named_object::make_sink()
7947 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
7950 // Make a named function.
7953 Named_object::make_function(const std::string
& name
, const Package
* package
,
7956 Named_object
* named_object
= new Named_object(name
, package
,
7958 named_object
->u_
.func_value
= function
;
7959 return named_object
;
7962 // Make a function declaration.
7965 Named_object::make_function_declaration(const std::string
& name
,
7966 const Package
* package
,
7967 Function_type
* fntype
,
7970 Named_object
* named_object
= new Named_object(name
, package
,
7971 NAMED_OBJECT_FUNC_DECLARATION
);
7972 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
7973 named_object
->u_
.func_declaration_value
= func_decl
;
7974 return named_object
;
7980 Named_object::make_package(const std::string
& alias
, Package
* package
)
7982 Named_object
* named_object
= new Named_object(alias
, NULL
,
7983 NAMED_OBJECT_PACKAGE
);
7984 named_object
->u_
.package_value
= package
;
7985 return named_object
;
7988 // Return the name to use in an error message.
7991 Named_object::message_name() const
7993 if (this->package_
== NULL
)
7994 return Gogo::message_name(this->name_
);
7996 if (this->package_
->has_package_name())
7997 ret
= this->package_
->package_name();
7999 ret
= this->package_
->pkgpath();
8000 ret
= Gogo::message_name(ret
);
8002 ret
+= Gogo::message_name(this->name_
);
8006 // Set the type when a declaration is defined.
8009 Named_object::set_type_value(Named_type
* named_type
)
8011 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8012 Type_declaration
* td
= this->u_
.type_declaration
;
8013 td
->define_methods(named_type
);
8015 Named_object
* in_function
= td
->in_function(&index
);
8016 if (in_function
!= NULL
)
8017 named_type
->set_in_function(in_function
, index
);
8019 this->classification_
= NAMED_OBJECT_TYPE
;
8020 this->u_
.type_value
= named_type
;
8023 // Define a function which was previously declared.
8026 Named_object::set_function_value(Function
* function
)
8028 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8029 if (this->func_declaration_value()->has_descriptor())
8031 Expression
* descriptor
=
8032 this->func_declaration_value()->descriptor(NULL
, NULL
);
8033 function
->set_descriptor(descriptor
);
8035 this->classification_
= NAMED_OBJECT_FUNC
;
8036 // FIXME: We should free the old value.
8037 this->u_
.func_value
= function
;
8040 // Declare an unknown object as a type declaration.
8043 Named_object::declare_as_type()
8045 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8046 Unknown_name
* unk
= this->u_
.unknown_value
;
8047 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8048 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8052 // Return the location of a named object.
8055 Named_object::location() const
8057 switch (this->classification_
)
8060 case NAMED_OBJECT_UNINITIALIZED
:
8063 case NAMED_OBJECT_ERRONEOUS
:
8064 return Linemap::unknown_location();
8066 case NAMED_OBJECT_UNKNOWN
:
8067 return this->unknown_value()->location();
8069 case NAMED_OBJECT_CONST
:
8070 return this->const_value()->location();
8072 case NAMED_OBJECT_TYPE
:
8073 return this->type_value()->location();
8075 case NAMED_OBJECT_TYPE_DECLARATION
:
8076 return this->type_declaration_value()->location();
8078 case NAMED_OBJECT_VAR
:
8079 return this->var_value()->location();
8081 case NAMED_OBJECT_RESULT_VAR
:
8082 return this->result_var_value()->location();
8084 case NAMED_OBJECT_SINK
:
8087 case NAMED_OBJECT_FUNC
:
8088 return this->func_value()->location();
8090 case NAMED_OBJECT_FUNC_DECLARATION
:
8091 return this->func_declaration_value()->location();
8093 case NAMED_OBJECT_PACKAGE
:
8094 return this->package_value()->location();
8098 // Export a named object.
8101 Named_object::export_named_object(Export
* exp
) const
8103 switch (this->classification_
)
8106 case NAMED_OBJECT_UNINITIALIZED
:
8107 case NAMED_OBJECT_UNKNOWN
:
8110 case NAMED_OBJECT_ERRONEOUS
:
8113 case NAMED_OBJECT_CONST
:
8114 this->const_value()->export_const(exp
, this->name_
);
8117 case NAMED_OBJECT_TYPE
:
8118 // Types are handled by export::write_types.
8121 case NAMED_OBJECT_TYPE_DECLARATION
:
8122 go_error_at(this->type_declaration_value()->location(),
8123 "attempt to export %<%s%> which was declared but not defined",
8124 this->message_name().c_str());
8127 case NAMED_OBJECT_FUNC_DECLARATION
:
8128 this->func_declaration_value()->export_func(exp
, this->name_
);
8131 case NAMED_OBJECT_VAR
:
8132 this->var_value()->export_var(exp
, this->name_
);
8135 case NAMED_OBJECT_RESULT_VAR
:
8136 case NAMED_OBJECT_SINK
:
8139 case NAMED_OBJECT_FUNC
:
8140 this->func_value()->export_func(exp
, this->name_
);
8145 // Convert a variable to the backend representation.
8148 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8150 if (this->classification_
== NAMED_OBJECT_VAR
)
8151 return this->var_value()->get_backend_variable(gogo
, function
,
8152 this->package_
, this->name_
);
8153 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8154 return this->result_var_value()->get_backend_variable(gogo
, function
,
8160 // Return the external identifier for this object.
8163 Named_object::get_id(Gogo
* gogo
)
8165 go_assert(!this->is_variable()
8166 && !this->is_result_variable()
8167 && !this->is_type());
8168 std::string decl_name
;
8169 if (this->is_function_declaration()
8170 && !this->func_declaration_value()->asm_name().empty())
8171 decl_name
= this->func_declaration_value()->asm_name();
8174 std::string package_name
;
8175 if (this->package_
== NULL
)
8176 package_name
= gogo
->package_name();
8178 package_name
= this->package_
->package_name();
8180 // Note that this will be misleading if this is an unexported
8181 // method generated for an embedded imported type. In that case
8182 // the unexported method should have the package name of the
8183 // package from which it is imported, but we are going to give
8184 // it our package name. Fixing this would require knowing the
8185 // package name, but we only know the package path. It might be
8186 // better to use package paths here anyhow. This doesn't affect
8187 // the assembler code, because we always set that name in
8188 // Function::get_or_make_decl anyhow. FIXME.
8190 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
8192 Function_type
* fntype
;
8193 if (this->is_function())
8194 fntype
= this->func_value()->type();
8195 else if (this->is_function_declaration())
8196 fntype
= this->func_declaration_value()->type();
8199 if (fntype
!= NULL
&& fntype
->is_method())
8201 decl_name
.push_back('.');
8202 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
8208 // Get the backend representation for this named object.
8211 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8212 std::vector
<Btype
*>& type_decls
,
8213 std::vector
<Bfunction
*>& func_decls
)
8215 // If this is a definition, avoid trying to get the backend
8216 // representation, as that can crash.
8217 if (this->is_redefinition_
)
8219 go_assert(saw_errors());
8223 switch (this->classification_
)
8225 case NAMED_OBJECT_CONST
:
8226 if (!Gogo::is_erroneous_name(this->name_
))
8227 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8230 case NAMED_OBJECT_TYPE
:
8232 Named_type
* named_type
= this->u_
.type_value
;
8233 if (!Gogo::is_erroneous_name(this->name_
) && !named_type
->is_alias())
8234 type_decls
.push_back(named_type
->get_backend(gogo
));
8236 // We need to produce a type descriptor for every named
8237 // type, and for a pointer to every named type, since
8238 // other files or packages might refer to them. We need
8239 // to do this even for hidden types, because they might
8240 // still be returned by some function. Simply calling the
8241 // type_descriptor method is enough to create the type
8242 // descriptor, even though we don't do anything with it.
8243 if (this->package_
== NULL
&& !saw_errors())
8246 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8247 named_type
->gc_symbol_pointer(gogo
);
8248 Type
* pn
= Type::make_pointer_type(named_type
);
8249 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8250 pn
->gc_symbol_pointer(gogo
);
8255 case NAMED_OBJECT_TYPE_DECLARATION
:
8256 go_error_at(Linemap::unknown_location(),
8257 "reference to undefined type %qs",
8258 this->message_name().c_str());
8261 case NAMED_OBJECT_VAR
:
8262 case NAMED_OBJECT_RESULT_VAR
:
8263 case NAMED_OBJECT_SINK
:
8266 case NAMED_OBJECT_FUNC
:
8268 Function
* func
= this->u_
.func_value
;
8269 if (!Gogo::is_erroneous_name(this->name_
))
8270 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
8272 if (func
->block() != NULL
)
8273 func
->build(gogo
, this);
8277 case NAMED_OBJECT_ERRONEOUS
:
8287 Bindings::Bindings(Bindings
* enclosing
)
8288 : enclosing_(enclosing
), named_objects_(), bindings_()
8295 Bindings::clear_file_scope(Gogo
* gogo
)
8297 Contour::iterator p
= this->bindings_
.begin();
8298 while (p
!= this->bindings_
.end())
8301 if (p
->second
->package() != NULL
)
8303 else if (p
->second
->is_package())
8305 else if (p
->second
->is_function()
8306 && !p
->second
->func_value()->type()->is_method()
8307 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
8316 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
8317 p
= this->bindings_
.erase(p
);
8322 // Look up a symbol.
8325 Bindings::lookup(const std::string
& name
) const
8327 Contour::const_iterator p
= this->bindings_
.find(name
);
8328 if (p
!= this->bindings_
.end())
8329 return p
->second
->resolve();
8330 else if (this->enclosing_
!= NULL
)
8331 return this->enclosing_
->lookup(name
);
8336 // Look up a symbol locally.
8339 Bindings::lookup_local(const std::string
& name
) const
8341 Contour::const_iterator p
= this->bindings_
.find(name
);
8342 if (p
== this->bindings_
.end())
8347 // Remove an object from a set of bindings. This is used for a
8348 // special case in thunks for functions which call recover.
8351 Bindings::remove_binding(Named_object
* no
)
8353 Contour::iterator pb
= this->bindings_
.find(no
->name());
8354 go_assert(pb
!= this->bindings_
.end());
8355 this->bindings_
.erase(pb
);
8356 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
8357 pn
!= this->named_objects_
.end();
8362 this->named_objects_
.erase(pn
);
8369 // Add a method to the list of objects. This is not added to the
8370 // lookup table. This is so that we have a single list of objects
8371 // declared at the top level, which we walk through when it's time to
8372 // convert to trees.
8375 Bindings::add_method(Named_object
* method
)
8377 this->named_objects_
.push_back(method
);
8380 // Add a generic Named_object to a Contour.
8383 Bindings::add_named_object_to_contour(Contour
* contour
,
8384 Named_object
* named_object
)
8386 go_assert(named_object
== named_object
->resolve());
8387 const std::string
& name(named_object
->name());
8388 go_assert(!Gogo::is_sink_name(name
));
8390 std::pair
<Contour::iterator
, bool> ins
=
8391 contour
->insert(std::make_pair(name
, named_object
));
8394 // The name was already there.
8395 if (named_object
->package() != NULL
8396 && ins
.first
->second
->package() == named_object
->package()
8397 && (ins
.first
->second
->classification()
8398 == named_object
->classification()))
8400 // This is a second import of the same object.
8401 return ins
.first
->second
;
8403 ins
.first
->second
= this->new_definition(ins
.first
->second
,
8405 return ins
.first
->second
;
8409 // Don't push declarations on the list. We push them on when
8410 // and if we find the definitions. That way we genericize the
8411 // functions in order.
8412 if (!named_object
->is_type_declaration()
8413 && !named_object
->is_function_declaration()
8414 && !named_object
->is_unknown())
8415 this->named_objects_
.push_back(named_object
);
8416 return named_object
;
8420 // We had an existing named object OLD_OBJECT, and we've seen a new
8421 // one NEW_OBJECT with the same name. FIXME: This does not free the
8422 // new object when we don't need it.
8425 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
8427 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
8431 switch (old_object
->classification())
8434 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8437 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8440 case Named_object::NAMED_OBJECT_UNKNOWN
:
8442 Named_object
* real
= old_object
->unknown_value()->real_named_object();
8444 return this->new_definition(real
, new_object
);
8445 go_assert(!new_object
->is_unknown());
8446 old_object
->unknown_value()->set_real_named_object(new_object
);
8447 if (!new_object
->is_type_declaration()
8448 && !new_object
->is_function_declaration())
8449 this->named_objects_
.push_back(new_object
);
8453 case Named_object::NAMED_OBJECT_CONST
:
8456 case Named_object::NAMED_OBJECT_TYPE
:
8457 if (new_object
->is_type_declaration())
8461 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8462 if (new_object
->is_type_declaration())
8464 if (new_object
->is_type())
8466 old_object
->set_type_value(new_object
->type_value());
8467 new_object
->type_value()->set_named_object(old_object
);
8468 this->named_objects_
.push_back(old_object
);
8473 case Named_object::NAMED_OBJECT_VAR
:
8474 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8475 // We have already given an error in the parser for cases where
8476 // one parameter or result variable redeclares another one.
8477 if ((new_object
->is_variable()
8478 && new_object
->var_value()->is_parameter())
8479 || new_object
->is_result_variable())
8483 case Named_object::NAMED_OBJECT_SINK
:
8486 case Named_object::NAMED_OBJECT_FUNC
:
8489 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8491 // We declare the hash and equality functions before defining
8492 // them, because we sometimes see that we need the declaration
8493 // while we are in the middle of a different function.
8495 // We declare the main function before the user defines it, to
8496 // give better error messages.
8498 // We declare inline functions before we define them, as we
8499 // only define them if we need them.
8500 if (new_object
->is_function()
8501 && ((Linemap::is_predeclared_location(old_object
->location())
8502 && Linemap::is_predeclared_location(new_object
->location()))
8503 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
8504 && Linemap::is_unknown_location(old_object
->location()))
8505 || (new_object
->package() != NULL
8506 && old_object
->func_declaration_value()->has_imported_body()
8507 && new_object
->func_value()->is_inline_only())))
8509 Function_type
* old_type
=
8510 old_object
->func_declaration_value()->type();
8511 Function_type
* new_type
= new_object
->func_value()->type();
8512 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
8514 Function_declaration
* fd
=
8515 old_object
->func_declaration_value();
8516 go_assert(fd
->asm_name().empty());
8517 old_object
->set_function_value(new_object
->func_value());
8518 this->named_objects_
.push_back(old_object
);
8525 case Named_object::NAMED_OBJECT_PACKAGE
:
8529 std::string n
= old_object
->message_name();
8531 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
8533 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
8535 old_object
->set_is_redefinition();
8536 new_object
->set_is_redefinition();
8538 if (!Linemap::is_unknown_location(old_object
->location())
8539 && !Linemap::is_predeclared_location(old_object
->location()))
8540 go_inform(old_object
->location(), "previous definition of %qs was here",
8546 // Add a named type.
8549 Bindings::add_named_type(Named_type
* named_type
)
8551 return this->add_named_object(named_type
->named_object());
8557 Bindings::add_function(const std::string
& name
, const Package
* package
,
8560 return this->add_named_object(Named_object::make_function(name
, package
,
8564 // Add a function declaration.
8567 Bindings::add_function_declaration(const std::string
& name
,
8568 const Package
* package
,
8569 Function_type
* type
,
8572 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
8574 return this->add_named_object(no
);
8577 // Define a type which was previously declared.
8580 Bindings::define_type(Named_object
* no
, Named_type
* type
)
8582 no
->set_type_value(type
);
8583 this->named_objects_
.push_back(no
);
8586 // Mark all local variables as used. This is used for some types of
8590 Bindings::mark_locals_used()
8592 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
8593 p
!= this->named_objects_
.end();
8595 if ((*p
)->is_variable())
8596 (*p
)->var_value()->set_is_used();
8599 // Traverse bindings.
8602 Bindings::traverse(Traverse
* traverse
, bool is_global
)
8604 unsigned int traverse_mask
= traverse
->traverse_mask();
8606 // We don't use an iterator because we permit the traversal to add
8607 // new global objects.
8608 const unsigned int e_or_t
= (Traverse::traverse_expressions
8609 | Traverse::traverse_types
);
8610 const unsigned int e_or_t_or_s
= (e_or_t
8611 | Traverse::traverse_statements
);
8612 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
8614 Named_object
* p
= this->named_objects_
[i
];
8615 int t
= TRAVERSE_CONTINUE
;
8616 switch (p
->classification())
8618 case Named_object::NAMED_OBJECT_CONST
:
8619 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
8620 t
= traverse
->constant(p
, is_global
);
8621 if (t
== TRAVERSE_CONTINUE
8622 && (traverse_mask
& e_or_t
) != 0)
8624 Type
* tc
= p
->const_value()->type();
8626 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
8627 return TRAVERSE_EXIT
;
8628 t
= p
->const_value()->traverse_expression(traverse
);
8632 case Named_object::NAMED_OBJECT_VAR
:
8633 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8634 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
8635 t
= traverse
->variable(p
);
8636 if (t
== TRAVERSE_CONTINUE
8637 && (traverse_mask
& e_or_t
) != 0)
8639 if (p
->is_result_variable()
8640 || p
->var_value()->has_type())
8642 Type
* tv
= (p
->is_variable()
8643 ? p
->var_value()->type()
8644 : p
->result_var_value()->type());
8646 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
8647 return TRAVERSE_EXIT
;
8650 if (t
== TRAVERSE_CONTINUE
8651 && (traverse_mask
& e_or_t_or_s
) != 0
8652 && p
->is_variable())
8653 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
8656 case Named_object::NAMED_OBJECT_FUNC
:
8657 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
8658 t
= traverse
->function(p
);
8660 if (t
== TRAVERSE_CONTINUE
8662 & (Traverse::traverse_variables
8663 | Traverse::traverse_constants
8664 | Traverse::traverse_functions
8665 | Traverse::traverse_blocks
8666 | Traverse::traverse_statements
8667 | Traverse::traverse_expressions
8668 | Traverse::traverse_types
)) != 0)
8669 t
= p
->func_value()->traverse(traverse
);
8672 case Named_object::NAMED_OBJECT_PACKAGE
:
8673 // These are traversed in Gogo::traverse.
8674 go_assert(is_global
);
8677 case Named_object::NAMED_OBJECT_TYPE
:
8678 if ((traverse_mask
& e_or_t
) != 0)
8679 t
= Type::traverse(p
->type_value(), traverse
);
8682 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8683 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8684 case Named_object::NAMED_OBJECT_UNKNOWN
:
8685 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8688 case Named_object::NAMED_OBJECT_SINK
:
8693 if (t
== TRAVERSE_EXIT
)
8694 return TRAVERSE_EXIT
;
8697 // If we need to traverse types, check the function declarations,
8698 // which have types. Also check any methods of a type declaration.
8699 if ((traverse_mask
& e_or_t
) != 0)
8701 for (Bindings::const_declarations_iterator p
=
8702 this->begin_declarations();
8703 p
!= this->end_declarations();
8706 if (p
->second
->is_function_declaration())
8708 if (Type::traverse(p
->second
->func_declaration_value()->type(),
8711 return TRAVERSE_EXIT
;
8713 else if (p
->second
->is_type_declaration())
8715 const std::vector
<Named_object
*>* methods
=
8716 p
->second
->type_declaration_value()->methods();
8717 for (std::vector
<Named_object
*>::const_iterator pm
=
8719 pm
!= methods
->end();
8722 Named_object
* no
= *pm
;
8724 if (no
->is_function())
8725 t
= no
->func_value()->type();
8726 else if (no
->is_function_declaration())
8727 t
= no
->func_declaration_value()->type();
8730 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
8731 return TRAVERSE_EXIT
;
8737 // Traverse function declarations when needed.
8738 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
8740 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
8741 p
!= this->end_declarations();
8744 if (p
->second
->is_function_declaration())
8746 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
8747 return TRAVERSE_EXIT
;
8752 return TRAVERSE_CONTINUE
;
8757 // Clear any references to this label.
8762 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
8763 p
!= this->refs_
.end();
8766 this->refs_
.clear();
8769 // Get the backend representation for a label.
8772 Label::get_backend_label(Translate_context
* context
)
8774 if (this->blabel_
== NULL
)
8776 Function
* function
= context
->function()->func_value();
8777 Bfunction
* bfunction
= function
->get_decl();
8778 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
8781 return this->blabel_
;
8784 // Return an expression for the address of this label.
8787 Label::get_addr(Translate_context
* context
, Location location
)
8789 Blabel
* label
= this->get_backend_label(context
);
8790 return context
->backend()->label_address(label
, location
);
8793 // Return the dummy label that represents any instance of the blank label.
8796 Label::create_dummy_label()
8798 static Label
* dummy_label
;
8799 if (dummy_label
== NULL
)
8801 dummy_label
= new Label("_");
8802 dummy_label
->set_is_used();
8807 // Class Unnamed_label.
8809 // Get the backend representation for an unnamed label.
8812 Unnamed_label::get_blabel(Translate_context
* context
)
8814 if (this->blabel_
== NULL
)
8816 Function
* function
= context
->function()->func_value();
8817 Bfunction
* bfunction
= function
->get_decl();
8818 this->blabel_
= context
->backend()->label(bfunction
, "",
8821 return this->blabel_
;
8824 // Return a statement which defines this unnamed label.
8827 Unnamed_label::get_definition(Translate_context
* context
)
8829 Blabel
* blabel
= this->get_blabel(context
);
8830 return context
->backend()->label_definition_statement(blabel
);
8833 // Return a goto statement to this unnamed label.
8836 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
8838 Blabel
* blabel
= this->get_blabel(context
);
8839 return context
->backend()->goto_statement(blabel
, location
);
8844 Package::Package(const std::string
& pkgpath
,
8845 const std::string
& pkgpath_symbol
, Location location
)
8846 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
8847 package_name_(), bindings_(new Bindings(NULL
)),
8850 go_assert(!pkgpath
.empty());
8853 // Set the package name.
8856 Package::set_package_name(const std::string
& package_name
, Location location
)
8858 go_assert(!package_name
.empty());
8859 if (this->package_name_
.empty())
8860 this->package_name_
= package_name
;
8861 else if (this->package_name_
!= package_name
)
8862 go_error_at(location
,
8863 ("saw two different packages with "
8864 "the same package path %s: %s, %s"),
8865 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
8866 package_name
.c_str());
8869 // Return the pkgpath symbol, which is a prefix for symbols defined in
8873 Package::pkgpath_symbol() const
8875 if (this->pkgpath_symbol_
.empty())
8876 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
8877 return this->pkgpath_symbol_
;
8880 // Set the package path symbol.
8883 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
8885 go_assert(!pkgpath_symbol
.empty());
8886 if (this->pkgpath_symbol_
.empty())
8887 this->pkgpath_symbol_
= pkgpath_symbol
;
8889 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
8892 // Note that symbol from this package was and qualified by ALIAS.
8895 Package::note_usage(const std::string
& alias
) const
8897 Aliases::const_iterator p
= this->aliases_
.find(alias
);
8898 go_assert(p
!= this->aliases_
.end());
8899 p
->second
->note_usage();
8902 // Forget a given usage. If forgetting this usage means this package becomes
8903 // unused, report that error.
8906 Package::forget_usage(Expression
* usage
) const
8908 if (this->fake_uses_
.empty())
8911 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
8912 go_assert(p
!= this->fake_uses_
.end());
8913 this->fake_uses_
.erase(p
);
8915 if (this->fake_uses_
.empty())
8916 go_error_at(this->location(), "imported and not used: %s",
8917 Gogo::message_name(this->package_name()).c_str());
8920 // Clear the used field for the next file. If the only usages of this package
8921 // are possibly fake, keep the fake usages for lowering.
8924 Package::clear_used()
8926 std::string dot_alias
= "." + this->package_name();
8927 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
8928 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
8929 this->fake_uses_
.clear();
8931 this->aliases_
.clear();
8935 Package::add_alias(const std::string
& alias
, Location location
)
8937 Aliases::const_iterator p
= this->aliases_
.find(alias
);
8938 if (p
== this->aliases_
.end())
8940 std::pair
<Aliases::iterator
, bool> ret
;
8941 ret
= this->aliases_
.insert(std::make_pair(alias
,
8942 new Package_alias(location
)));
8948 // Determine types of constants. Everything else in a package
8949 // (variables, function declarations) should already have a fixed
8950 // type. Constants may have abstract types.
8953 Package::determine_types()
8955 Bindings
* bindings
= this->bindings_
;
8956 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
8957 p
!= bindings
->end_definitions();
8960 if ((*p
)->is_const())
8961 (*p
)->const_value()->determine_type();
8969 Traverse::~Traverse()
8971 if (this->types_seen_
!= NULL
)
8972 delete this->types_seen_
;
8973 if (this->expressions_seen_
!= NULL
)
8974 delete this->expressions_seen_
;
8977 // Record that we are looking at a type, and return true if we have
8981 Traverse::remember_type(const Type
* type
)
8983 if (type
->is_error_type())
8985 go_assert((this->traverse_mask() & traverse_types
) != 0
8986 || (this->traverse_mask() & traverse_expressions
) != 0);
8987 // We mostly only have to remember named types. But it turns out
8988 // that an interface type can refer to itself without using a name
8989 // by relying on interface inheritance, as in
8991 // type I interface { F() interface{I} }
8993 // Similarly it is possible for array types to refer to themselves
8994 // without a name, e.g.
8996 // var x [uintptr(unsafe.Sizeof(&x))]byte
8998 if (type
->classification() != Type::TYPE_NAMED
8999 && type
->classification() != Type::TYPE_ARRAY
9000 && type
->classification() != Type::TYPE_INTERFACE
)
9002 if (this->types_seen_
== NULL
)
9003 this->types_seen_
= new Types_seen();
9004 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9008 // Record that we are looking at an expression, and return true if we
9009 // have already seen it. NB: this routine used to assert if the traverse
9010 // mask did not include expressions/types -- this is no longer the case,
9011 // since it can be useful to remember specific expressions during
9012 // walks that only cover statements.
9015 Traverse::remember_expression(const Expression
* expression
)
9017 if (this->expressions_seen_
== NULL
)
9018 this->expressions_seen_
= new Expressions_seen();
9019 std::pair
<Expressions_seen::iterator
, bool> ins
=
9020 this->expressions_seen_
->insert(expression
);
9024 // The default versions of these functions should never be called: the
9025 // traversal mask indicates which functions may be called.
9028 Traverse::variable(Named_object
*)
9034 Traverse::constant(Named_object
*, bool)
9040 Traverse::function(Named_object
*)
9046 Traverse::block(Block
*)
9052 Traverse::statement(Block
*, size_t*, Statement
*)
9058 Traverse::expression(Expression
**)
9064 Traverse::type(Type
*)
9070 Traverse::function_declaration(Named_object
*)
9075 // Class Statement_inserter.
9078 Statement_inserter::insert(Statement
* s
)
9080 if (this->statements_added_
!= NULL
)
9081 this->statements_added_
->insert(s
);
9083 if (this->block_
!= NULL
)
9085 go_assert(this->pindex_
!= NULL
);
9086 this->block_
->insert_statement_before(*this->pindex_
, s
);
9089 else if (this->var_
!= NULL
)
9090 this->var_
->add_preinit_statement(this->gogo_
, s
);
9092 go_assert(saw_errors());