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_(),
55 specific_type_functions_(),
56 specific_type_functions_are_written_(false),
57 named_types_are_converted_(false)
59 const Location loc
= Linemap::predeclared_location();
61 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
62 RUNTIME_TYPE_KIND_UINT8
);
63 this->add_named_type(uint8_type
);
64 this->add_named_type(Type::make_integer_type("uint16", true, 16,
65 RUNTIME_TYPE_KIND_UINT16
));
66 this->add_named_type(Type::make_integer_type("uint32", true, 32,
67 RUNTIME_TYPE_KIND_UINT32
));
68 this->add_named_type(Type::make_integer_type("uint64", true, 64,
69 RUNTIME_TYPE_KIND_UINT64
));
71 this->add_named_type(Type::make_integer_type("int8", false, 8,
72 RUNTIME_TYPE_KIND_INT8
));
73 this->add_named_type(Type::make_integer_type("int16", false, 16,
74 RUNTIME_TYPE_KIND_INT16
));
75 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
76 RUNTIME_TYPE_KIND_INT32
);
77 this->add_named_type(int32_type
);
78 this->add_named_type(Type::make_integer_type("int64", false, 64,
79 RUNTIME_TYPE_KIND_INT64
));
81 this->add_named_type(Type::make_float_type("float32", 32,
82 RUNTIME_TYPE_KIND_FLOAT32
));
83 this->add_named_type(Type::make_float_type("float64", 64,
84 RUNTIME_TYPE_KIND_FLOAT64
));
86 this->add_named_type(Type::make_complex_type("complex64", 64,
87 RUNTIME_TYPE_KIND_COMPLEX64
));
88 this->add_named_type(Type::make_complex_type("complex128", 128,
89 RUNTIME_TYPE_KIND_COMPLEX128
));
91 int int_type_size
= pointer_size
;
92 if (int_type_size
< 32)
94 this->add_named_type(Type::make_integer_type("uint", true,
96 RUNTIME_TYPE_KIND_UINT
));
97 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
98 RUNTIME_TYPE_KIND_INT
);
99 this->add_named_type(int_type
);
101 this->add_named_type(Type::make_integer_type("uintptr", true,
103 RUNTIME_TYPE_KIND_UINTPTR
));
105 // "byte" is an alias for "uint8".
106 uint8_type
->integer_type()->set_is_byte();
107 Named_object
* byte_type
= Named_object::make_type("byte", NULL
, uint8_type
,
109 this->add_named_type(byte_type
->type_value());
111 // "rune" is an alias for "int32".
112 int32_type
->integer_type()->set_is_rune();
113 Named_object
* rune_type
= Named_object::make_type("rune", NULL
, int32_type
,
115 this->add_named_type(rune_type
->type_value());
117 this->add_named_type(Type::make_named_bool_type());
119 this->add_named_type(Type::make_named_string_type());
121 // "error" is interface { Error() string }.
123 Typed_identifier_list
*methods
= new Typed_identifier_list
;
124 Typed_identifier_list
*results
= new Typed_identifier_list
;
125 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
126 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
127 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
128 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
129 error_iface
->finalize_methods();
130 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
131 this->add_named_type(error_type
);
134 this->globals_
->add_constant(Typed_identifier("true",
135 Type::make_boolean_type(),
138 Expression::make_boolean(true, loc
),
140 this->globals_
->add_constant(Typed_identifier("false",
141 Type::make_boolean_type(),
144 Expression::make_boolean(false, loc
),
147 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
150 Expression::make_nil(loc
),
153 Type
* abstract_int_type
= Type::make_abstract_integer_type();
154 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
157 Expression::make_iota(),
160 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
161 new_type
->set_is_varargs();
162 new_type
->set_is_builtin();
163 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
165 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
166 make_type
->set_is_varargs();
167 make_type
->set_is_builtin();
168 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
170 Typed_identifier_list
* len_result
= new Typed_identifier_list();
171 len_result
->push_back(Typed_identifier("", int_type
, loc
));
172 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
174 len_type
->set_is_builtin();
175 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
177 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
178 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
179 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
181 cap_type
->set_is_builtin();
182 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
184 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
185 print_type
->set_is_varargs();
186 print_type
->set_is_builtin();
187 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
189 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
190 print_type
->set_is_varargs();
191 print_type
->set_is_builtin();
192 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
194 Type
*empty
= Type::make_empty_interface_type(loc
);
195 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
196 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
197 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
199 panic_type
->set_is_builtin();
200 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
202 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
203 recover_result
->push_back(Typed_identifier("", empty
, loc
));
204 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
207 recover_type
->set_is_builtin();
208 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
210 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
211 close_type
->set_is_varargs();
212 close_type
->set_is_builtin();
213 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
215 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
216 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
217 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
219 copy_type
->set_is_varargs();
220 copy_type
->set_is_builtin();
221 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
223 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
224 append_type
->set_is_varargs();
225 append_type
->set_is_builtin();
226 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
228 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
229 complex_type
->set_is_varargs();
230 complex_type
->set_is_builtin();
231 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
233 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
234 real_type
->set_is_varargs();
235 real_type
->set_is_builtin();
236 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
238 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
239 imag_type
->set_is_varargs();
240 imag_type
->set_is_builtin();
241 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
243 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
244 delete_type
->set_is_varargs();
245 delete_type
->set_is_builtin();
246 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
249 // Convert a pkgpath into a string suitable for a symbol. Note that
250 // this transformation is convenient but imperfect. A -fgo-pkgpath
251 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
252 // possibly leading to link time errors.
255 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
257 std::string s
= pkgpath
;
258 for (size_t i
= 0; i
< s
.length(); ++i
)
261 if ((c
>= 'a' && c
<= 'z')
262 || (c
>= 'A' && c
<= 'Z')
263 || (c
>= '0' && c
<= '9'))
271 // Get the package path to use for type reflection data. This should
272 // ideally be unique across the entire link.
275 Gogo::pkgpath() const
277 go_assert(this->pkgpath_set_
);
278 return this->pkgpath_
;
281 // Set the package path from the -fgo-pkgpath command line option.
284 Gogo::set_pkgpath(const std::string
& arg
)
286 go_assert(!this->pkgpath_set_
);
287 this->pkgpath_
= arg
;
288 this->pkgpath_set_
= true;
289 this->pkgpath_from_option_
= true;
292 // Get the package path to use for symbol names.
295 Gogo::pkgpath_symbol() const
297 go_assert(this->pkgpath_set_
);
298 return this->pkgpath_symbol_
;
301 // Set the unique prefix to use to determine the package path, from
302 // the -fgo-prefix command line option.
305 Gogo::set_prefix(const std::string
& arg
)
307 go_assert(!this->prefix_from_option_
);
309 this->prefix_from_option_
= true;
312 // Munge name for use in an error message.
315 Gogo::message_name(const std::string
& name
)
317 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
320 // Get the package name.
323 Gogo::package_name() const
325 go_assert(this->package_
!= NULL
);
326 return this->package_
->package_name();
329 // Set the package name.
332 Gogo::set_package_name(const std::string
& package_name
,
335 if (this->package_
!= NULL
)
337 if (this->package_
->package_name() != package_name
)
338 go_error_at(location
, "expected package %<%s%>",
339 Gogo::message_name(this->package_
->package_name()).c_str());
343 // Now that we know the name of the package we are compiling, set
344 // the package path to use for reflect.Type.PkgPath and global
346 if (this->pkgpath_set_
)
347 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
350 if (!this->prefix_from_option_
&& package_name
== "main")
352 this->pkgpath_
= package_name
;
353 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
357 if (!this->prefix_from_option_
)
358 this->prefix_
= "go";
359 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
360 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
361 + Gogo::pkgpath_for_symbol(package_name
));
363 this->pkgpath_set_
= true;
366 this->package_
= this->register_package(this->pkgpath_
,
367 this->pkgpath_symbol_
, location
);
368 this->package_
->set_package_name(package_name
, location
);
370 if (this->is_main_package())
372 // Declare "main" as a function which takes no parameters and
374 Location uloc
= Linemap::unknown_location();
375 this->declare_function(Gogo::pack_hidden_name("main", false),
376 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
381 // Return whether this is the "main" package. This is not true if
382 // -fgo-pkgpath or -fgo-prefix was used.
385 Gogo::is_main_package() const
387 return (this->package_name() == "main"
388 && !this->pkgpath_from_option_
389 && !this->prefix_from_option_
);
395 Gogo::import_package(const std::string
& filename
,
396 const std::string
& local_name
,
397 bool is_local_name_exported
,
401 if (filename
.empty())
403 go_error_at(location
, "import path is empty");
407 const char *pf
= filename
.data();
408 const char *pend
= pf
+ filename
.length();
412 int adv
= Lex::fetch_char(pf
, &c
);
415 go_error_at(location
, "import path contains invalid UTF-8 sequence");
420 go_error_at(location
, "import path contains NUL");
423 if (c
< 0x20 || c
== 0x7f)
425 go_error_at(location
, "import path contains control character");
430 go_error_at(location
, "import path contains backslash; use slash");
433 if (Lex::is_unicode_space(c
))
435 go_error_at(location
, "import path contains space character");
438 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
440 go_error_at(location
,
441 "import path contains invalid character '%c'", c
);
447 if (IS_ABSOLUTE_PATH(filename
.c_str()))
449 go_error_at(location
, "import path cannot be absolute path");
453 if (local_name
== "init")
454 go_error_at(location
, "cannot import package as init");
456 if (filename
== "unsafe")
458 this->import_unsafe(local_name
, is_local_name_exported
, location
);
459 this->current_file_imported_unsafe_
= true;
463 Imports::const_iterator p
= this->imports_
.find(filename
);
464 if (p
!= this->imports_
.end())
466 Package
* package
= p
->second
;
467 package
->set_location(location
);
468 std::string ln
= local_name
;
469 bool is_ln_exported
= is_local_name_exported
;
472 ln
= package
->package_name();
473 go_assert(!ln
.empty());
474 is_ln_exported
= Lex::is_exported_name(ln
);
480 Bindings
* bindings
= package
->bindings();
481 for (Bindings::const_declarations_iterator p
=
482 bindings
->begin_declarations();
483 p
!= bindings
->end_declarations();
485 this->add_dot_import_object(p
->second
);
486 std::string dot_alias
= "." + package
->package_name();
487 package
->add_alias(dot_alias
, location
);
491 package
->add_alias(ln
, location
);
492 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
493 this->package_
->bindings()->add_package(ln
, package
);
498 Import::Stream
* stream
= Import::open_package(filename
, location
,
499 this->relative_import_path_
);
503 go_error_at(location
, "import file %qs not found", filename
.c_str());
507 Import
imp(stream
, location
);
508 imp
.register_builtin_types(this);
509 Package
* package
= imp
.import(this, local_name
, is_local_name_exported
);
512 if (package
->pkgpath() == this->pkgpath())
513 go_error_at(location
,
514 ("imported package uses same package path as package "
515 "being compiled (see -fgo-pkgpath option)"));
517 this->imports_
.insert(std::make_pair(filename
, package
));
524 Gogo::lookup_init(const std::string
& init_name
)
526 Import_init
tmp("", init_name
, -1);
527 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
528 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
531 // Add an import control function for an imported package to the list.
534 Gogo::add_import_init_fn(const std::string
& package_name
,
535 const std::string
& init_name
, int prio
)
537 for (Import_init_set::iterator p
=
538 this->imported_init_fns_
.begin();
539 p
!= this->imported_init_fns_
.end();
542 Import_init
*ii
= (*p
);
543 if (ii
->init_name() == init_name
)
545 // If a test of package P1, built as part of package P1,
546 // imports package P2, and P2 imports P1 (perhaps
547 // indirectly), then we will see the same import name with
548 // different import priorities. That is OK, so don't give
549 // an error about it.
550 if (ii
->package_name() != package_name
)
552 go_error_at(Linemap::unknown_location(),
553 "duplicate package initialization name %qs",
554 Gogo::message_name(init_name
).c_str());
555 go_inform(Linemap::unknown_location(), "used by package %qs",
556 Gogo::message_name(ii
->package_name()).c_str());
557 go_inform(Linemap::unknown_location(), " and by package %qs",
558 Gogo::message_name(package_name
).c_str());
560 ii
->set_priority(prio
);
565 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
566 this->imported_init_fns_
.insert(nii
);
569 // Return whether we are at the global binding level.
572 Gogo::in_global_scope() const
574 return this->functions_
.empty();
577 // Return the current binding contour.
580 Gogo::current_bindings()
582 if (!this->functions_
.empty())
583 return this->functions_
.back().blocks
.back()->bindings();
584 else if (this->package_
!= NULL
)
585 return this->package_
->bindings();
587 return this->globals_
;
591 Gogo::current_bindings() const
593 if (!this->functions_
.empty())
594 return this->functions_
.back().blocks
.back()->bindings();
595 else if (this->package_
!= NULL
)
596 return this->package_
->bindings();
598 return this->globals_
;
602 Gogo::update_init_priority(Import_init
* ii
,
603 std::set
<const Import_init
*>* visited
)
608 for (std::set
<std::string
>::const_iterator pci
=
609 ii
->precursors().begin();
610 pci
!= ii
->precursors().end();
613 Import_init
* succ
= this->lookup_init(*pci
);
614 if (visited
->find(succ
) == visited
->end())
615 update_init_priority(succ
, visited
);
616 succ_prior
= std::max(succ_prior
, succ
->priority());
618 if (ii
->priority() <= succ_prior
)
619 ii
->set_priority(succ_prior
+ 1);
623 Gogo::recompute_init_priorities()
625 std::set
<Import_init
*> nonroots
;
627 for (Import_init_set::const_iterator p
=
628 this->imported_init_fns_
.begin();
629 p
!= this->imported_init_fns_
.end();
632 const Import_init
*ii
= *p
;
633 for (std::set
<std::string
>::const_iterator pci
=
634 ii
->precursors().begin();
635 pci
!= ii
->precursors().end();
638 Import_init
* ii
= this->lookup_init(*pci
);
643 // Recursively update priorities starting at roots.
644 std::set
<const Import_init
*> visited
;
645 for (Import_init_set::iterator p
=
646 this->imported_init_fns_
.begin();
647 p
!= this->imported_init_fns_
.end();
650 Import_init
* ii
= *p
;
651 if (nonroots
.find(ii
) != nonroots
.end())
653 update_init_priority(ii
, &visited
);
657 // Add statements to INIT_STMTS which run the initialization
658 // functions for imported packages. This is only used for the "main"
662 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
)
664 go_assert(this->is_main_package());
666 if (this->imported_init_fns_
.empty())
669 Location unknown_loc
= Linemap::unknown_location();
670 Function_type
* func_type
=
671 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
672 Btype
* fntype
= func_type
->get_backend_fntype(this);
674 // Recompute init priorities based on a walk of the init graph.
675 recompute_init_priorities();
677 // We must call them in increasing priority order.
678 std::vector
<const Import_init
*> v
;
679 for (Import_init_set::const_iterator p
=
680 this->imported_init_fns_
.begin();
681 p
!= this->imported_init_fns_
.end();
684 std::sort(v
.begin(), v
.end(), priority_compare
);
686 // We build calls to the init functions, which take no arguments.
687 std::vector
<Bexpression
*> empty_args
;
688 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
692 const Import_init
* ii
= *p
;
693 std::string user_name
= ii
->package_name() + ".init";
694 const std::string
& init_name(ii
->init_name());
696 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
697 true, true, true, false,
699 Bexpression
* pfunc_code
=
700 this->backend()->function_code_expression(pfunc
, unknown_loc
);
701 Bexpression
* pfunc_call
=
702 this->backend()->call_expression(pfunc_code
, empty_args
,
704 init_stmts
.push_back(this->backend()->expression_statement(pfunc_call
));
708 // Register global variables with the garbage collector. We need to
709 // register all variables which can hold a pointer value. They become
710 // roots during the mark phase. We build a struct that is easy to
711 // hook into a list of roots.
713 // struct __go_gc_root_list
715 // struct __go_gc_root_list* __next;
716 // struct __go_gc_root
723 // The last entry in the roots array has a NULL decl field.
726 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
727 std::vector
<Bstatement
*>& init_stmts
)
732 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
733 Type
* uint_type
= Type::lookup_integer_type("uint");
734 Struct_type
* root_type
= Type::make_builtin_struct_type(2,
736 "__size", uint_type
);
738 Location builtin_loc
= Linemap::predeclared_location();
739 Expression
* length
= Expression::make_integer_ul(var_gc
.size(), NULL
,
742 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
743 Type
* ptdt
= Type::make_type_descriptor_ptr_type();
744 Struct_type
* root_list_type
=
745 Type::make_builtin_struct_type(2,
747 "__roots", root_array_type
);
749 // Build an initializer for the __roots array.
751 Expression_list
* roots_init
= new Expression_list();
754 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
758 Expression_list
* init
= new Expression_list();
760 Location no_loc
= (*p
)->location();
761 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
762 Expression
* decl_addr
=
763 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
764 init
->push_back(decl_addr
);
766 Expression
* decl_size
=
767 Expression::make_type_info(decl
->type(), Expression::TYPE_INFO_SIZE
);
768 init
->push_back(decl_size
);
770 Expression
* root_ctor
=
771 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
772 roots_init
->push_back(root_ctor
);
775 // The list ends with a NULL entry.
777 Expression_list
* null_init
= new Expression_list();
778 Expression
* nil
= Expression::make_nil(builtin_loc
);
779 null_init
->push_back(nil
);
781 Expression
*zero
= Expression::make_integer_ul(0, NULL
, builtin_loc
);
782 null_init
->push_back(zero
);
784 Expression
* null_root_ctor
=
785 Expression::make_struct_composite_literal(root_type
, null_init
,
787 roots_init
->push_back(null_root_ctor
);
789 // Build a constructor for the struct.
791 Expression_list
* root_list_init
= new Expression_list();
792 root_list_init
->push_back(nil
);
794 Expression
* roots_ctor
=
795 Expression::make_array_composite_literal(root_array_type
, roots_init
,
797 root_list_init
->push_back(roots_ctor
);
799 Expression
* root_list_ctor
=
800 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
803 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
805 root_addr
->unary_expression()->set_is_gc_root();
806 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
807 builtin_loc
, 1, root_addr
);
809 Translate_context
context(this, NULL
, NULL
, NULL
);
810 Bexpression
* bcall
= register_roots
->get_backend(&context
);
811 init_stmts
.push_back(this->backend()->expression_statement(bcall
));
814 // Get the name to use for the import control function. If there is a
815 // global function or variable, then we know that that name must be
816 // unique in the link, and we use it as the basis for our name.
819 Gogo::get_init_fn_name()
821 if (this->init_fn_name_
.empty())
823 go_assert(this->package_
!= NULL
);
824 if (this->is_main_package())
826 // Use a name which the runtime knows.
827 this->init_fn_name_
= "__go_init_main";
831 std::string s
= this->pkgpath_symbol();
832 s
.append("..import");
833 this->init_fn_name_
= s
;
837 return this->init_fn_name_
;
840 // Build the decl for the initialization function.
843 Gogo::initialization_function_decl()
845 std::string name
= this->get_init_fn_name();
846 Location loc
= this->package_
->location();
848 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
849 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
850 return Named_object::make_function(name
, NULL
, initfn
);
853 // Create the magic initialization function. CODE_STMT is the
854 // code that it needs to run.
857 Gogo::create_initialization_function(Named_object
* initfn
,
858 Bstatement
* code_stmt
)
860 // Make sure that we thought we needed an initialization function,
861 // as otherwise we will not have reported it in the export data.
862 go_assert(this->is_main_package() || this->need_init_fn_
);
865 initfn
= this->initialization_function_decl();
867 // Bind the initialization function code to a block.
868 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
869 Location pkg_loc
= this->package_
->location();
870 std::vector
<Bvariable
*> vars
;
871 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
873 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
875 go_assert(saw_errors());
881 // Search for references to VAR in any statements or called functions.
883 class Find_var
: public Traverse
886 // A hash table we use to avoid looping. The index is the name of a
887 // named object. We only look through objects defined in this
889 typedef Unordered_set(const void*) Seen_objects
;
891 Find_var(Named_object
* var
, Seen_objects
* seen_objects
)
892 : Traverse(traverse_expressions
),
893 var_(var
), seen_objects_(seen_objects
), found_(false)
896 // Whether the variable was found.
899 { return this->found_
; }
902 expression(Expression
**);
905 // The variable we are looking for.
907 // Names of objects we have already seen.
908 Seen_objects
* seen_objects_
;
909 // True if the variable was found.
913 // See if EXPR refers to VAR, looking through function calls and
914 // variable initializations.
917 Find_var::expression(Expression
** pexpr
)
919 Expression
* e
= *pexpr
;
921 Var_expression
* ve
= e
->var_expression();
924 Named_object
* v
= ve
->named_object();
928 return TRAVERSE_EXIT
;
931 if (v
->is_variable() && v
->package() == NULL
)
933 Expression
* init
= v
->var_value()->init();
936 std::pair
<Seen_objects::iterator
, bool> ins
=
937 this->seen_objects_
->insert(v
);
940 // This is the first time we have seen this name.
941 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
942 return TRAVERSE_EXIT
;
948 // We traverse the code of any function or bound method we see. Note that
949 // this means that we will traverse the code of a function or bound method
950 // whose address is taken even if it is not called.
951 Func_expression
* fe
= e
->func_expression();
952 Bound_method_expression
* bme
= e
->bound_method_expression();
953 if (fe
!= NULL
|| bme
!= NULL
)
955 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
956 if (f
->is_function() && f
->package() == NULL
)
958 std::pair
<Seen_objects::iterator
, bool> ins
=
959 this->seen_objects_
->insert(f
);
962 // This is the first time we have seen this name.
963 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
964 return TRAVERSE_EXIT
;
969 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
972 Temporary_statement
* ts
= tre
->statement();
973 Expression
* init
= ts
->init();
976 std::pair
<Seen_objects::iterator
, bool> ins
=
977 this->seen_objects_
->insert(ts
);
980 // This is the first time we have seen this temporary
982 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
983 return TRAVERSE_EXIT
;
988 return TRAVERSE_CONTINUE
;
991 // Return true if EXPR, PREINIT, or DEP refers to VAR.
994 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
997 Find_var::Seen_objects seen_objects
;
998 Find_var
find_var(var
, &seen_objects
);
1000 Expression::traverse(&expr
, &find_var
);
1001 if (preinit
!= NULL
)
1002 preinit
->traverse(&find_var
);
1005 Expression
* init
= dep
->var_value()->init();
1007 Expression::traverse(&init
, &find_var
);
1008 if (dep
->var_value()->has_pre_init())
1009 dep
->var_value()->preinit()->traverse(&find_var
);
1012 return find_var
.found();
1015 // Sort variable initializations. If the initialization expression
1016 // for variable A refers directly or indirectly to the initialization
1017 // expression for variable B, then we must initialize B before A.
1023 : var_(NULL
), init_(NULL
), dep_count_(0)
1026 Var_init(Named_object
* var
, Bstatement
* init
)
1027 : var_(var
), init_(init
), dep_count_(0)
1030 // Return the variable.
1033 { return this->var_
; }
1035 // Return the initialization expression.
1038 { return this->init_
; }
1040 // Return the number of remaining dependencies.
1043 { return this->dep_count_
; }
1045 // Increment the number of dependencies.
1048 { ++this->dep_count_
; }
1050 // Decrement the number of dependencies.
1053 { --this->dep_count_
; }
1056 // The variable being initialized.
1058 // The initialization statement.
1060 // The number of initializations this is dependent on. A variable
1061 // initialization should not be emitted if any of its dependencies
1062 // have not yet been resolved.
1066 // For comparing Var_init keys in a map.
1069 operator<(const Var_init
& v1
, const Var_init
& v2
)
1070 { return v1
.var()->name() < v2
.var()->name(); }
1072 typedef std::list
<Var_init
> Var_inits
;
1074 // Sort the variable initializations. The rule we follow is that we
1075 // emit them in the order they appear in the array, except that if the
1076 // initialization expression for a variable V1 depends upon another
1077 // variable V2 then we initialize V1 after V2.
1080 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1082 if (var_inits
->empty())
1085 typedef std::pair
<Named_object
*, Named_object
*> No_no
;
1086 typedef std::map
<No_no
, bool> Cache
;
1089 // A mapping from a variable initialization to a set of
1090 // variable initializations that depend on it.
1091 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1092 Init_deps init_deps
;
1093 bool init_loop
= false;
1094 for (Var_inits::iterator p1
= var_inits
->begin();
1095 p1
!= var_inits
->end();
1098 Named_object
* var
= p1
->var();
1099 Expression
* init
= var
->var_value()->init();
1100 Block
* preinit
= var
->var_value()->preinit();
1101 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1103 // Start walking through the list to see which variables VAR
1104 // needs to wait for.
1105 for (Var_inits::iterator p2
= var_inits
->begin();
1106 p2
!= var_inits
->end();
1109 if (var
== p2
->var())
1112 Named_object
* p2var
= p2
->var();
1113 No_no
key(var
, p2var
);
1114 std::pair
<Cache::iterator
, bool> ins
=
1115 cache
.insert(std::make_pair(key
, false));
1117 ins
.first
->second
= expression_requires(init
, preinit
, dep
, p2var
);
1118 if (ins
.first
->second
)
1120 // VAR depends on P2VAR.
1121 init_deps
[*p2
].insert(&(*p1
));
1122 p1
->add_dependency();
1124 // Check for cycles.
1125 key
= std::make_pair(p2var
, var
);
1126 ins
= cache
.insert(std::make_pair(key
, false));
1129 expression_requires(p2var
->var_value()->init(),
1130 p2var
->var_value()->preinit(),
1131 gogo
->var_depends_on(p2var
->var_value()),
1133 if (ins
.first
->second
)
1135 go_error_at(var
->location(),
1136 ("initialization expressions for %qs and "
1137 "%qs depend upon each other"),
1138 var
->message_name().c_str(),
1139 p2var
->message_name().c_str());
1140 go_inform(p2
->var()->location(), "%qs defined here",
1141 p2var
->message_name().c_str());
1149 // If there are no dependencies then the declaration order is sorted.
1150 if (!init_deps
.empty() && !init_loop
)
1152 // Otherwise, sort variable initializations by emitting all variables with
1153 // no dependencies in declaration order. VAR_INITS is already in
1154 // declaration order.
1156 while (!var_inits
->empty())
1158 Var_inits::iterator v1
;;
1159 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1161 if (v1
->dep_count() == 0)
1164 go_assert(v1
!= var_inits
->end());
1166 // V1 either has no dependencies or its dependencies have already
1167 // been emitted, add it to READY next. When V1 is emitted, remove
1168 // a dependency from each V that depends on V1.
1169 ready
.splice(ready
.end(), *var_inits
, v1
);
1171 Init_deps::iterator p1
= init_deps
.find(*v1
);
1172 if (p1
!= init_deps
.end())
1174 std::set
<Var_init
*> resolved
= p1
->second
;
1175 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1176 pv
!= resolved
.end();
1178 (*pv
)->remove_dependency();
1179 init_deps
.erase(p1
);
1182 var_inits
->swap(ready
);
1183 go_assert(init_deps
.empty());
1186 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1187 // check for a loop of VAR on itself. We only do this if
1188 // INIT is not NULL and there is no dependency; when INIT is
1189 // NULL, it means that PREINIT sets VAR, which we will
1190 // interpret as a loop.
1191 for (Var_inits::const_iterator p
= var_inits
->begin();
1192 p
!= var_inits
->end();
1195 Named_object
* var
= p
->var();
1196 Expression
* init
= var
->var_value()->init();
1197 Block
* preinit
= var
->var_value()->preinit();
1198 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1199 if (init
!= NULL
&& dep
== NULL
1200 && expression_requires(init
, preinit
, NULL
, var
))
1201 go_error_at(var
->location(),
1202 "initialization expression for %qs depends upon itself",
1203 var
->message_name().c_str());
1207 // Write out the global definitions.
1210 Gogo::write_globals()
1212 this->build_interface_method_tables();
1214 Bindings
* bindings
= this->current_bindings();
1216 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1217 p
!= bindings
->end_declarations();
1220 // If any function declarations needed a descriptor, make sure
1222 Named_object
* no
= p
->second
;
1223 if (no
->is_function_declaration())
1224 no
->func_declaration_value()->build_backend_descriptor(this);
1227 // Lists of globally declared types, variables, constants, and functions
1228 // that must be defined.
1229 std::vector
<Btype
*> type_decls
;
1230 std::vector
<Bvariable
*> var_decls
;
1231 std::vector
<Bexpression
*> const_decls
;
1232 std::vector
<Bfunction
*> func_decls
;
1234 // The init function declaration, if necessary.
1235 Named_object
* init_fndecl
= NULL
;
1237 std::vector
<Bstatement
*> init_stmts
;
1238 std::vector
<Bstatement
*> var_init_stmts
;
1240 if (this->is_main_package())
1241 this->init_imports(init_stmts
);
1243 // A list of variable initializations.
1244 Var_inits var_inits
;
1246 // A list of variables which need to be registered with the garbage
1248 size_t count_definitions
= bindings
->size_definitions();
1249 std::vector
<Named_object
*> var_gc
;
1250 var_gc
.reserve(count_definitions
);
1252 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1253 p
!= bindings
->end_definitions();
1256 Named_object
* no
= *p
;
1257 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1259 // There is nothing to do for a package.
1260 if (no
->is_package())
1263 // There is nothing to do for an object which was imported from
1264 // a different package into the global scope.
1265 if (no
->package() != NULL
)
1268 // Skip blank named functions and constants.
1269 if ((no
->is_function() && no
->func_value()->is_sink())
1270 || (no
->is_const() && no
->const_value()->is_sink()))
1273 // There is nothing useful we can output for constants which
1274 // have ideal or non-integral type.
1277 Type
* type
= no
->const_value()->type();
1279 type
= no
->const_value()->expr()->type();
1280 if (type
->is_abstract() || !type
->is_numeric_type())
1284 if (!no
->is_variable())
1285 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1288 Variable
* var
= no
->var_value();
1289 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1290 var_decls
.push_back(bvar
);
1292 // Check for a sink variable, which may be used to run an
1293 // initializer purely for its side effects.
1294 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1296 Bstatement
* var_init_stmt
= NULL
;
1297 if (!var
->has_pre_init())
1299 // If the backend representation of the variable initializer is
1300 // constant, we can just set the initial value using
1301 // global_var_set_init instead of during the init() function.
1302 // The initializer is constant if it is the zero-value of the
1303 // variable's type or if the initial value is an immutable value
1304 // that is not copied to the heap.
1305 bool is_static_initializer
= false;
1306 if (var
->init() == NULL
)
1307 is_static_initializer
= true;
1310 Type
* var_type
= var
->type();
1311 Expression
* init
= var
->init();
1312 Expression
* init_cast
=
1313 Expression::make_cast(var_type
, init
, var
->location());
1314 is_static_initializer
= init_cast
->is_static_initializer();
1317 // Non-constant variable initializations might need to create
1318 // temporary variables, which will need the initialization
1319 // function as context.
1320 Named_object
* var_init_fn
;
1321 if (is_static_initializer
)
1325 if (init_fndecl
== NULL
)
1326 init_fndecl
= this->initialization_function_decl();
1327 var_init_fn
= init_fndecl
;
1329 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1331 if (var_binit
== NULL
)
1333 else if (is_static_initializer
)
1335 if (expression_requires(var
->init(), NULL
,
1336 this->var_depends_on(var
), no
))
1337 go_error_at(no
->location(),
1338 "initialization expression for %qs depends "
1340 no
->message_name().c_str());
1341 this->backend()->global_variable_set_init(bvar
, var_binit
);
1345 this->backend()->expression_statement(var_binit
);
1348 Location loc
= var
->location();
1349 Bexpression
* var_expr
=
1350 this->backend()->var_expression(bvar
, loc
);
1352 this->backend()->assignment_statement(var_expr
, var_binit
,
1358 // We are going to create temporary variables which
1359 // means that we need an fndecl.
1360 if (init_fndecl
== NULL
)
1361 init_fndecl
= this->initialization_function_decl();
1363 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1364 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1367 if (var_init_stmt
!= NULL
)
1369 if (var
->init() == NULL
&& !var
->has_pre_init())
1370 var_init_stmts
.push_back(var_init_stmt
);
1372 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1374 else if (this->var_depends_on(var
) != NULL
)
1376 // This variable is initialized from something that is
1377 // not in its init or preinit. This variable needs to
1378 // participate in dependency analysis sorting, in case
1379 // some other variable depends on this one.
1380 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1381 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1382 Bstatement
* zero_stmt
=
1383 this->backend()->expression_statement(zero
);
1384 var_inits
.push_back(Var_init(no
, zero_stmt
));
1387 if (!is_sink
&& var
->type()->has_pointer())
1388 var_gc
.push_back(no
);
1392 // Register global variables with the garbage collector.
1393 this->register_gc_vars(var_gc
, init_stmts
);
1395 // Simple variable initializations, after all variables are
1397 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1399 // Complete variable initializations, first sorting them into a
1401 if (!var_inits
.empty())
1403 sort_var_inits(this, &var_inits
);
1404 for (Var_inits::const_iterator p
= var_inits
.begin();
1405 p
!= var_inits
.end();
1407 init_stmts
.push_back(p
->init());
1410 // After all the variables are initialized, call the init
1411 // functions if there are any. Init functions take no arguments, so
1412 // we pass in EMPTY_ARGS to call them.
1413 std::vector
<Bexpression
*> empty_args
;
1414 for (std::vector
<Named_object
*>::const_iterator p
=
1415 this->init_functions_
.begin();
1416 p
!= this->init_functions_
.end();
1419 Location func_loc
= (*p
)->location();
1420 Function
* func
= (*p
)->func_value();
1421 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1422 Bexpression
* func_code
=
1423 this->backend()->function_code_expression(initfn
, func_loc
);
1424 Bexpression
* call
= this->backend()->call_expression(func_code
,
1427 init_stmts
.push_back(this->backend()->expression_statement(call
));
1430 // Set up a magic function to do all the initialization actions.
1431 // This will be called if this package is imported.
1432 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1433 if (this->need_init_fn_
|| this->is_main_package())
1436 this->create_initialization_function(init_fndecl
, init_fncode
);
1437 if (init_fndecl
!= NULL
)
1438 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1441 // We should not have seen any new bindings created during the conversion.
1442 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1444 // Define all globally declared values.
1446 this->backend()->write_global_definitions(type_decls
, const_decls
,
1447 func_decls
, var_decls
);
1450 // Return the current block.
1453 Gogo::current_block()
1455 if (this->functions_
.empty())
1458 return this->functions_
.back().blocks
.back();
1461 // Look up a name in the current binding contour. If PFUNCTION is not
1462 // NULL, set it to the function in which the name is defined, or NULL
1463 // if the name is defined in global scope.
1466 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1468 if (pfunction
!= NULL
)
1471 if (Gogo::is_sink_name(name
))
1472 return Named_object::make_sink();
1474 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1475 p
!= this->functions_
.rend();
1478 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1481 if (pfunction
!= NULL
)
1482 *pfunction
= p
->function
;
1487 if (this->package_
!= NULL
)
1489 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1492 if (ret
->package() != NULL
)
1494 std::string dot_alias
= "." + ret
->package()->package_name();
1495 ret
->package()->note_usage(dot_alias
);
1501 // We do not look in the global namespace. If we did, the global
1502 // namespace would effectively hide names which were defined in
1503 // package scope which we have not yet seen. Instead,
1504 // define_global_names is called after parsing is over to connect
1505 // undefined names at package scope with names defined at global
1511 // Look up a name in the current block, without searching enclosing
1515 Gogo::lookup_in_block(const std::string
& name
) const
1517 go_assert(!this->functions_
.empty());
1518 go_assert(!this->functions_
.back().blocks
.empty());
1519 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1522 // Look up a name in the global namespace.
1525 Gogo::lookup_global(const char* name
) const
1527 return this->globals_
->lookup(name
);
1530 // Add an imported package.
1533 Gogo::add_imported_package(const std::string
& real_name
,
1534 const std::string
& alias_arg
,
1535 bool is_alias_exported
,
1536 const std::string
& pkgpath
,
1537 const std::string
& pkgpath_symbol
,
1539 bool* padd_to_globals
)
1541 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1542 ret
->set_package_name(real_name
, location
);
1544 *padd_to_globals
= false;
1546 if (alias_arg
== "_")
1548 else if (alias_arg
== ".")
1550 *padd_to_globals
= true;
1551 std::string dot_alias
= "." + real_name
;
1552 ret
->add_alias(dot_alias
, location
);
1556 std::string alias
= alias_arg
;
1560 is_alias_exported
= Lex::is_exported_name(alias
);
1562 ret
->add_alias(alias
, location
);
1563 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1564 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1565 if (!no
->is_package())
1572 // Register a package. This package may or may not be imported. This
1573 // returns the Package structure for the package, creating if it
1574 // necessary. LOCATION is the location of the import statement that
1575 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1576 // for names in the package; it may be the empty string, in which case
1577 // we either get it later or make a guess when we need it.
1580 Gogo::register_package(const std::string
& pkgpath
,
1581 const std::string
& pkgpath_symbol
, Location location
)
1583 Package
* package
= NULL
;
1584 std::pair
<Packages::iterator
, bool> ins
=
1585 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1588 // We have seen this package name before.
1589 package
= ins
.first
->second
;
1590 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1591 if (!pkgpath_symbol
.empty())
1592 package
->set_pkgpath_symbol(pkgpath_symbol
);
1593 if (Linemap::is_unknown_location(package
->location()))
1594 package
->set_location(location
);
1598 // First time we have seen this package name.
1599 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1600 go_assert(ins
.first
->second
== NULL
);
1601 ins
.first
->second
= package
;
1607 // Start compiling a function.
1610 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1611 bool add_method_to_type
, Location location
)
1613 bool at_top_level
= this->functions_
.empty();
1615 Block
* block
= new Block(NULL
, location
);
1617 Named_object
* enclosing
= (at_top_level
1619 : this->functions_
.back().function
);
1621 Function
* function
= new Function(type
, enclosing
, block
, location
);
1623 if (type
->is_method())
1625 const Typed_identifier
* receiver
= type
->receiver();
1626 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1627 true, true, location
);
1628 std::string rname
= receiver
->name();
1629 if (rname
.empty() || Gogo::is_sink_name(rname
))
1631 // We need to give receivers a name since they wind up in
1632 // DECL_ARGUMENTS. FIXME.
1633 static unsigned int count
;
1635 snprintf(buf
, sizeof buf
, "r.%u", count
);
1639 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1642 const Typed_identifier_list
* parameters
= type
->parameters();
1643 bool is_varargs
= type
->is_varargs();
1644 if (parameters
!= NULL
)
1646 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
1647 p
!= parameters
->end();
1650 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
1652 if (is_varargs
&& p
+ 1 == parameters
->end())
1653 param
->set_is_varargs_parameter();
1655 std::string pname
= p
->name();
1656 if (pname
.empty() || Gogo::is_sink_name(pname
))
1658 // We need to give parameters a name since they wind up
1659 // in DECL_ARGUMENTS. FIXME.
1660 static unsigned int count
;
1662 snprintf(buf
, sizeof buf
, "p.%u", count
);
1666 block
->bindings()->add_variable(pname
, NULL
, param
);
1670 function
->create_result_variables(this);
1672 const std::string
* pname
;
1673 std::string nested_name
;
1674 bool is_init
= false;
1675 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
1677 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
1678 || (type
->results() != NULL
&& !type
->results()->empty()))
1679 go_error_at(location
,
1680 "func init must have no arguments and no return values");
1681 // There can be multiple "init" functions, so give them each a
1683 static int init_count
;
1685 snprintf(buf
, sizeof buf
, ".$init%d", init_count
);
1688 pname
= &nested_name
;
1691 else if (!name
.empty())
1695 // Invent a name for a nested function.
1696 static int nested_count
;
1698 snprintf(buf
, sizeof buf
, ".$nested%d", nested_count
);
1701 pname
= &nested_name
;
1705 if (Gogo::is_sink_name(*pname
))
1707 static int sink_count
;
1709 snprintf(buf
, sizeof buf
, ".$sink%d", sink_count
);
1711 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1712 ret
->func_value()->set_is_sink();
1714 else if (!type
->is_method())
1716 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
1717 if (!ret
->is_function() || ret
->func_value() != function
)
1719 // Redefinition error. Invent a name to avoid knockon
1721 static int redefinition_count
;
1723 snprintf(buf
, sizeof buf
, ".$redefined%d", redefinition_count
);
1724 ++redefinition_count
;
1725 ret
= this->package_
->bindings()->add_function(buf
, NULL
, function
);
1730 if (!add_method_to_type
)
1731 ret
= Named_object::make_function(name
, NULL
, function
);
1734 go_assert(at_top_level
);
1735 Type
* rtype
= type
->receiver()->type();
1737 // We want to look through the pointer created by the
1738 // parser, without getting an error if the type is not yet
1740 if (rtype
->classification() == Type::TYPE_POINTER
)
1741 rtype
= rtype
->points_to();
1743 if (rtype
->is_error_type())
1744 ret
= Named_object::make_function(name
, NULL
, function
);
1745 else if (rtype
->named_type() != NULL
)
1747 ret
= rtype
->named_type()->add_method(name
, function
);
1748 if (!ret
->is_function())
1750 // Redefinition error.
1751 ret
= Named_object::make_function(name
, NULL
, function
);
1754 else if (rtype
->forward_declaration_type() != NULL
)
1756 Named_object
* type_no
=
1757 rtype
->forward_declaration_type()->named_object();
1758 if (type_no
->is_unknown())
1760 // If we are seeing methods it really must be a
1761 // type. Declare it as such. An alternative would
1762 // be to support lists of methods for unknown
1763 // expressions. Either way the error messages if
1764 // this is not a type are going to get confusing.
1765 Named_object
* declared
=
1766 this->declare_package_type(type_no
->name(),
1767 type_no
->location());
1769 == type_no
->unknown_value()->real_named_object());
1771 ret
= rtype
->forward_declaration_type()->add_method(name
,
1776 go_error_at(type
->receiver()->location(),
1777 ("invalid receiver type (receiver must "
1778 "be a named type)"));
1779 ret
= Named_object::make_function(name
, NULL
, function
);
1782 this->package_
->bindings()->add_method(ret
);
1785 this->functions_
.resize(this->functions_
.size() + 1);
1786 Open_function
& of(this->functions_
.back());
1788 of
.blocks
.push_back(block
);
1792 this->init_functions_
.push_back(ret
);
1793 this->need_init_fn_
= true;
1799 // Finish compiling a function.
1802 Gogo::finish_function(Location location
)
1804 this->finish_block(location
);
1805 go_assert(this->functions_
.back().blocks
.empty());
1806 this->functions_
.pop_back();
1809 // Return the current function.
1812 Gogo::current_function() const
1814 go_assert(!this->functions_
.empty());
1815 return this->functions_
.back().function
;
1818 // Start a new block.
1821 Gogo::start_block(Location location
)
1823 go_assert(!this->functions_
.empty());
1824 Block
* block
= new Block(this->current_block(), location
);
1825 this->functions_
.back().blocks
.push_back(block
);
1831 Gogo::finish_block(Location location
)
1833 go_assert(!this->functions_
.empty());
1834 go_assert(!this->functions_
.back().blocks
.empty());
1835 Block
* block
= this->functions_
.back().blocks
.back();
1836 this->functions_
.back().blocks
.pop_back();
1837 block
->set_end_location(location
);
1841 // Add an erroneous name.
1844 Gogo::add_erroneous_name(const std::string
& name
)
1846 return this->package_
->bindings()->add_erroneous_name(name
);
1849 // Add an unknown name.
1852 Gogo::add_unknown_name(const std::string
& name
, Location location
)
1854 return this->package_
->bindings()->add_unknown_name(name
, location
);
1857 // Declare a function.
1860 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
1863 if (!type
->is_method())
1864 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
1868 // We don't bother to add this to the list of global
1870 Type
* rtype
= type
->receiver()->type();
1872 // We want to look through the pointer created by the
1873 // parser, without getting an error if the type is not yet
1875 if (rtype
->classification() == Type::TYPE_POINTER
)
1876 rtype
= rtype
->points_to();
1878 if (rtype
->is_error_type())
1880 else if (rtype
->named_type() != NULL
)
1881 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
1883 else if (rtype
->forward_declaration_type() != NULL
)
1885 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
1886 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
1890 go_error_at(type
->receiver()->location(),
1891 "invalid receiver type (receiver must be a named type)");
1892 return Named_object::make_erroneous_name(name
);
1897 // Add a label definition.
1900 Gogo::add_label_definition(const std::string
& label_name
,
1903 go_assert(!this->functions_
.empty());
1904 Function
* func
= this->functions_
.back().function
->func_value();
1905 Label
* label
= func
->add_label_definition(this, label_name
, location
);
1906 this->add_statement(Statement::make_label_statement(label
, location
));
1910 // Add a label reference.
1913 Gogo::add_label_reference(const std::string
& label_name
,
1914 Location location
, bool issue_goto_errors
)
1916 go_assert(!this->functions_
.empty());
1917 Function
* func
= this->functions_
.back().function
->func_value();
1918 return func
->add_label_reference(this, label_name
, location
,
1922 // Return the current binding state.
1925 Gogo::bindings_snapshot(Location location
)
1927 return new Bindings_snapshot(this->current_block(), location
);
1933 Gogo::add_statement(Statement
* statement
)
1935 go_assert(!this->functions_
.empty()
1936 && !this->functions_
.back().blocks
.empty());
1937 this->functions_
.back().blocks
.back()->add_statement(statement
);
1943 Gogo::add_block(Block
* block
, Location location
)
1945 go_assert(!this->functions_
.empty()
1946 && !this->functions_
.back().blocks
.empty());
1947 Statement
* statement
= Statement::make_block_statement(block
, location
);
1948 this->functions_
.back().blocks
.back()->add_statement(statement
);
1954 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
1957 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
1963 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
1965 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
1967 if (!this->in_global_scope() && no
->is_type())
1969 Named_object
* f
= this->functions_
.back().function
;
1971 if (f
->is_function())
1972 index
= f
->func_value()->new_local_type_index();
1975 no
->type_value()->set_in_function(f
, index
);
1979 // Add a named type.
1982 Gogo::add_named_type(Named_type
* type
)
1984 go_assert(this->in_global_scope());
1985 this->current_bindings()->add_named_type(type
);
1991 Gogo::declare_type(const std::string
& name
, Location location
)
1993 Bindings
* bindings
= this->current_bindings();
1994 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
1995 if (!this->in_global_scope() && no
->is_type_declaration())
1997 Named_object
* f
= this->functions_
.back().function
;
1999 if (f
->is_function())
2000 index
= f
->func_value()->new_local_type_index();
2003 no
->type_declaration_value()->set_in_function(f
, index
);
2008 // Declare a type at the package level.
2011 Gogo::declare_package_type(const std::string
& name
, Location location
)
2013 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2016 // Declare a function at the package level.
2019 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2022 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2026 // Define a type which was already declared.
2029 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2031 this->current_bindings()->define_type(no
, type
);
2037 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2039 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2042 // In a function the middle-end wants to see a DECL_EXPR node.
2044 && no
->is_variable()
2045 && !no
->var_value()->is_parameter()
2046 && !this->functions_
.empty())
2047 this->add_statement(Statement::make_variable_declaration(no
));
2052 // Add a sink--a reference to the blank identifier _.
2057 return Named_object::make_sink();
2060 // Add a named object for a dot import.
2063 Gogo::add_dot_import_object(Named_object
* no
)
2065 // If the name already exists, then it was defined in some file seen
2066 // earlier. If the earlier name is just a declaration, don't add
2067 // this name, because that will cause the previous declaration to
2068 // merge to this imported name, which should not happen. Just add
2069 // this name to the list of file block names to get appropriate
2070 // errors if we see a later definition.
2071 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2072 if (e
!= NULL
&& e
->package() == NULL
)
2074 if (e
->is_unknown())
2076 if (e
->package() == NULL
2077 && (e
->is_type_declaration()
2078 || e
->is_function_declaration()
2079 || e
->is_unknown()))
2081 this->add_file_block_name(no
->name(), no
->location());
2086 this->current_bindings()->add_named_object(no
);
2089 // Add a linkname. This implements the go:linkname compiler directive.
2090 // We only support this for functions and function declarations.
2093 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2094 const std::string
& ext_name
, Location loc
)
2097 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2100 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2101 else if (no
->is_function())
2102 no
->func_value()->set_asm_name(ext_name
);
2103 else if (no
->is_function_declaration())
2104 no
->func_declaration_value()->set_asm_name(ext_name
);
2107 ("%s is not a function; "
2108 "//go:linkname is only supported for functions"),
2112 // Mark all local variables used. This is used when some types of
2113 // parse error occur.
2116 Gogo::mark_locals_used()
2118 for (Open_functions::iterator pf
= this->functions_
.begin();
2119 pf
!= this->functions_
.end();
2122 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2123 pb
!= pf
->blocks
.end();
2125 (*pb
)->bindings()->mark_locals_used();
2129 // Record that we've seen an interface type.
2132 Gogo::record_interface_type(Interface_type
* itype
)
2134 this->interface_types_
.push_back(itype
);
2137 // Return an erroneous name that indicates that an error has already
2141 Gogo::erroneous_name()
2143 static int erroneous_count
;
2145 snprintf(name
, sizeof name
, "$erroneous%d", erroneous_count
);
2150 // Return whether a name is an erroneous name.
2153 Gogo::is_erroneous_name(const std::string
& name
)
2155 return name
.compare(0, 10, "$erroneous") == 0;
2158 // Return a name for a thunk object.
2163 static int thunk_count
;
2164 char thunk_name
[50];
2165 snprintf(thunk_name
, sizeof thunk_name
, "$thunk%d", thunk_count
);
2170 // Return whether a function is a thunk.
2173 Gogo::is_thunk(const Named_object
* no
)
2175 return no
->name().compare(0, 6, "$thunk") == 0;
2178 // Define the global names. We do this only after parsing all the
2179 // input files, because the program might define the global names
2183 Gogo::define_global_names()
2185 if (this->is_main_package())
2187 // Every Go program has to import the runtime package, so that
2188 // it is properly initialized.
2189 this->import_package("runtime", "_", false, false,
2190 Linemap::predeclared_location());
2193 for (Bindings::const_declarations_iterator p
=
2194 this->globals_
->begin_declarations();
2195 p
!= this->globals_
->end_declarations();
2198 Named_object
* global_no
= p
->second
;
2199 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2200 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2204 if (no
->is_type_declaration())
2206 if (global_no
->is_type())
2208 if (no
->type_declaration_value()->has_methods())
2209 go_error_at(no
->location(),
2210 "may not define methods for global type");
2211 no
->set_type_value(global_no
->type_value());
2215 go_error_at(no
->location(), "expected type");
2216 Type
* errtype
= Type::make_error_type();
2218 Named_object::make_type("erroneous_type", NULL
, errtype
,
2219 Linemap::predeclared_location());
2220 no
->set_type_value(err
->type_value());
2223 else if (no
->is_unknown())
2224 no
->unknown_value()->set_real_named_object(global_no
);
2227 // Give an error if any name is defined in both the package block
2228 // and the file block. For example, this can happen if one file
2229 // imports "fmt" and another file defines a global variable fmt.
2230 for (Bindings::const_declarations_iterator p
=
2231 this->package_
->bindings()->begin_declarations();
2232 p
!= this->package_
->bindings()->end_declarations();
2235 if (p
->second
->is_unknown()
2236 && p
->second
->unknown_value()->real_named_object() == NULL
)
2238 // No point in warning about an undefined name, as we will
2239 // get other errors later anyhow.
2242 File_block_names::const_iterator pf
=
2243 this->file_block_names_
.find(p
->second
->name());
2244 if (pf
!= this->file_block_names_
.end())
2246 std::string n
= p
->second
->message_name();
2247 go_error_at(p
->second
->location(),
2248 "%qs defined as both imported name and global name",
2250 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2253 // No package scope identifier may be named "init".
2254 if (!p
->second
->is_function()
2255 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2257 go_error_at(p
->second
->location(),
2258 "cannot declare init - must be func");
2263 // Clear out names in file scope.
2266 Gogo::clear_file_scope()
2268 this->package_
->bindings()->clear_file_scope(this);
2270 // Warn about packages which were imported but not used.
2271 bool quiet
= saw_errors();
2272 for (Packages::iterator p
= this->packages_
.begin();
2273 p
!= this->packages_
.end();
2276 Package
* package
= p
->second
;
2277 if (package
!= this->package_
&& !quiet
)
2279 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2280 p1
!= package
->aliases().end();
2283 if (!p1
->second
->used())
2285 // Give a more refined error message if the alias name is known.
2286 std::string pkg_name
= package
->package_name();
2287 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2289 go_error_at(p1
->second
->location(),
2290 "imported and not used: %s as %s",
2291 Gogo::message_name(pkg_name
).c_str(),
2292 Gogo::message_name(p1
->first
).c_str());
2295 go_error_at(p1
->second
->location(),
2296 "imported and not used: %s",
2297 Gogo::message_name(pkg_name
).c_str());
2301 package
->clear_used();
2304 this->current_file_imported_unsafe_
= false;
2307 // Queue up a type specific function for later writing. These are
2308 // written out in write_specific_type_functions, called after the
2309 // parse tree is lowered.
2312 Gogo::queue_specific_type_function(Type
* type
, Named_type
* name
,
2313 const std::string
& hash_name
,
2314 Function_type
* hash_fntype
,
2315 const std::string
& equal_name
,
2316 Function_type
* equal_fntype
)
2318 go_assert(!this->specific_type_functions_are_written_
);
2319 go_assert(!this->in_global_scope());
2320 Specific_type_function
* tsf
= new Specific_type_function(type
, name
,
2325 this->specific_type_functions_
.push_back(tsf
);
2328 // Look for types which need specific hash or equality functions.
2330 class Specific_type_functions
: public Traverse
2333 Specific_type_functions(Gogo
* gogo
)
2334 : Traverse(traverse_types
),
2346 Specific_type_functions::type(Type
* t
)
2348 Named_object
* hash_fn
;
2349 Named_object
* equal_fn
;
2350 switch (t
->classification())
2352 case Type::TYPE_NAMED
:
2354 Named_type
* nt
= t
->named_type();
2355 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2356 t
->type_functions(this->gogo_
, nt
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2358 // If this is a struct type, we don't want to make functions
2359 // for the unnamed struct.
2360 Type
* rt
= nt
->real_type();
2361 if (rt
->struct_type() == NULL
)
2363 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2364 return TRAVERSE_EXIT
;
2368 // If this type is defined in another package, then we don't
2369 // need to worry about the unexported fields.
2370 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2371 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2372 for (Struct_field_list::const_iterator p
= fields
->begin();
2376 if (is_defined_elsewhere
2377 && Gogo::is_hidden_name(p
->field_name()))
2379 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2380 return TRAVERSE_EXIT
;
2384 return TRAVERSE_SKIP_COMPONENTS
;
2387 case Type::TYPE_STRUCT
:
2388 case Type::TYPE_ARRAY
:
2389 if (!t
->compare_is_identity(this->gogo_
) && t
->is_comparable())
2390 t
->type_functions(this->gogo_
, NULL
, NULL
, NULL
, &hash_fn
, &equal_fn
);
2397 return TRAVERSE_CONTINUE
;
2400 // Write out type specific functions.
2403 Gogo::write_specific_type_functions()
2405 Specific_type_functions
stf(this);
2406 this->traverse(&stf
);
2408 while (!this->specific_type_functions_
.empty())
2410 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2411 this->specific_type_functions_
.pop_back();
2412 tsf
->type
->write_specific_type_functions(this, tsf
->name
,
2419 this->specific_type_functions_are_written_
= true;
2422 // Traverse the tree.
2425 Gogo::traverse(Traverse
* traverse
)
2427 // Traverse the current package first for consistency. The other
2428 // packages will only contain imported types, constants, and
2430 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2432 for (Packages::const_iterator p
= this->packages_
.begin();
2433 p
!= this->packages_
.end();
2436 if (p
->second
!= this->package_
)
2438 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2444 // Add a type to verify. This is used for types of sink variables, in
2445 // order to give appropriate error messages.
2448 Gogo::add_type_to_verify(Type
* type
)
2450 this->verify_types_
.push_back(type
);
2453 // Traversal class used to verify types.
2455 class Verify_types
: public Traverse
2459 : Traverse(traverse_types
)
2466 // Verify that a type is correct.
2469 Verify_types::type(Type
* t
)
2472 return TRAVERSE_SKIP_COMPONENTS
;
2473 return TRAVERSE_CONTINUE
;
2476 // Verify that all types are correct.
2479 Gogo::verify_types()
2481 Verify_types traverse
;
2482 this->traverse(&traverse
);
2484 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2485 p
!= this->verify_types_
.end();
2488 this->verify_types_
.clear();
2491 // Traversal class used to lower parse tree.
2493 class Lower_parse_tree
: public Traverse
2496 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2497 : Traverse(traverse_variables
2498 | traverse_constants
2499 | traverse_functions
2500 | traverse_statements
2501 | traverse_expressions
),
2502 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2506 set_inserter(const Statement_inserter
* inserter
)
2507 { this->inserter_
= *inserter
; }
2510 variable(Named_object
*);
2513 constant(Named_object
*, bool);
2516 function(Named_object
*);
2519 statement(Block
*, size_t* pindex
, Statement
*);
2522 expression(Expression
**);
2527 // The function we are traversing.
2528 Named_object
* function_
;
2529 // Value to use for the predeclared constant iota.
2531 // Current statement inserter for use by expressions.
2532 Statement_inserter inserter_
;
2538 Lower_parse_tree::variable(Named_object
* no
)
2540 if (!no
->is_variable())
2541 return TRAVERSE_CONTINUE
;
2543 if (no
->is_variable() && no
->var_value()->is_global())
2545 // Global variables can have loops in their initialization
2546 // expressions. This is handled in lower_init_expression.
2547 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2549 return TRAVERSE_CONTINUE
;
2552 // This is a local variable. We are going to return
2553 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2554 // initialization expression when we reach the variable declaration
2555 // statement. However, that means that we need to traverse the type
2557 if (no
->var_value()->has_type())
2559 Type
* type
= no
->var_value()->type();
2562 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2563 return TRAVERSE_EXIT
;
2566 go_assert(!no
->var_value()->has_pre_init());
2568 return TRAVERSE_SKIP_COMPONENTS
;
2571 // Lower constants. We handle constants specially so that we can set
2572 // the right value for the predeclared constant iota. This works in
2573 // conjunction with the way we lower Const_expression objects.
2576 Lower_parse_tree::constant(Named_object
* no
, bool)
2578 Named_constant
* nc
= no
->const_value();
2580 // Don't get into trouble if the constant's initializer expression
2581 // refers to the constant itself.
2583 return TRAVERSE_CONTINUE
;
2586 go_assert(this->iota_value_
== -1);
2587 this->iota_value_
= nc
->iota_value();
2588 nc
->traverse_expression(this);
2589 this->iota_value_
= -1;
2591 nc
->clear_lowering();
2593 // We will traverse the expression a second time, but that will be
2596 return TRAVERSE_CONTINUE
;
2599 // Lower the body of a function, and set the closure type. Record the
2600 // function while lowering it, so that we can pass it down when
2601 // lowering an expression.
2604 Lower_parse_tree::function(Named_object
* no
)
2606 no
->func_value()->set_closure_type();
2608 go_assert(this->function_
== NULL
);
2609 this->function_
= no
;
2610 int t
= no
->func_value()->traverse(this);
2611 this->function_
= NULL
;
2613 if (t
== TRAVERSE_EXIT
)
2615 return TRAVERSE_SKIP_COMPONENTS
;
2618 // Lower statement parse trees.
2621 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
2623 // Because we explicitly traverse the statement's contents
2624 // ourselves, we want to skip block statements here. There is
2625 // nothing to lower in a block statement.
2626 if (sorig
->is_block_statement())
2627 return TRAVERSE_CONTINUE
;
2629 Statement_inserter
hold_inserter(this->inserter_
);
2630 this->inserter_
= Statement_inserter(block
, pindex
);
2632 // Lower the expressions first.
2633 int t
= sorig
->traverse_contents(this);
2634 if (t
== TRAVERSE_EXIT
)
2636 this->inserter_
= hold_inserter
;
2640 // Keep lowering until nothing changes.
2641 Statement
* s
= sorig
;
2644 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
2649 t
= s
->traverse_contents(this);
2650 if (t
== TRAVERSE_EXIT
)
2652 this->inserter_
= hold_inserter
;
2658 block
->replace_statement(*pindex
, s
);
2660 this->inserter_
= hold_inserter
;
2661 return TRAVERSE_SKIP_COMPONENTS
;
2664 // Lower expression parse trees.
2667 Lower_parse_tree::expression(Expression
** pexpr
)
2669 // We have to lower all subexpressions first, so that we can get
2670 // their type if necessary. This is awkward, because we don't have
2671 // a postorder traversal pass.
2672 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2673 return TRAVERSE_EXIT
;
2674 // Keep lowering until nothing changes.
2677 Expression
* e
= *pexpr
;
2678 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
2679 &this->inserter_
, this->iota_value_
);
2682 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
2683 return TRAVERSE_EXIT
;
2686 return TRAVERSE_SKIP_COMPONENTS
;
2689 // Lower the parse tree. This is called after the parse is complete,
2690 // when all names should be resolved.
2693 Gogo::lower_parse_tree()
2695 Lower_parse_tree
lower_parse_tree(this, NULL
);
2696 this->traverse(&lower_parse_tree
);
2698 // There might be type definitions that involve expressions such as the
2699 // array length. Make sure to lower these expressions as well. Otherwise,
2700 // errors hidden within a type can introduce unexpected errors into later
2702 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2703 p
!= this->verify_types_
.end();
2705 Type::traverse(*p
, &lower_parse_tree
);
2711 Gogo::lower_block(Named_object
* function
, Block
* block
)
2713 Lower_parse_tree
lower_parse_tree(this, function
);
2714 block
->traverse(&lower_parse_tree
);
2717 // Lower an expression. INSERTER may be NULL, in which case the
2718 // expression had better not need to create any temporaries.
2721 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
2724 Lower_parse_tree
lower_parse_tree(this, function
);
2725 if (inserter
!= NULL
)
2726 lower_parse_tree
.set_inserter(inserter
);
2727 lower_parse_tree
.expression(pexpr
);
2730 // Lower a constant. This is called when lowering a reference to a
2731 // constant. We have to make sure that the constant has already been
2735 Gogo::lower_constant(Named_object
* no
)
2737 go_assert(no
->is_const());
2738 Lower_parse_tree
lower(this, NULL
);
2739 lower
.constant(no
, false);
2742 // Traverse the tree to create function descriptors as needed.
2744 class Create_function_descriptors
: public Traverse
2747 Create_function_descriptors(Gogo
* gogo
)
2748 : Traverse(traverse_functions
| traverse_expressions
),
2753 function(Named_object
*);
2756 expression(Expression
**);
2762 // Create a descriptor for every top-level exported function.
2765 Create_function_descriptors::function(Named_object
* no
)
2767 if (no
->is_function()
2768 && no
->func_value()->enclosing() == NULL
2769 && !no
->func_value()->is_method()
2770 && !Gogo::is_hidden_name(no
->name())
2771 && !Gogo::is_thunk(no
))
2772 no
->func_value()->descriptor(this->gogo_
, no
);
2774 return TRAVERSE_CONTINUE
;
2777 // If we see a function referenced in any way other than calling it,
2778 // create a descriptor for it.
2781 Create_function_descriptors::expression(Expression
** pexpr
)
2783 Expression
* expr
= *pexpr
;
2785 Func_expression
* fe
= expr
->func_expression();
2788 // We would not get here for a call to this function, so this is
2789 // a reference to a function other than calling it. We need a
2791 if (fe
->closure() != NULL
)
2792 return TRAVERSE_CONTINUE
;
2793 Named_object
* no
= fe
->named_object();
2794 if (no
->is_function() && !no
->func_value()->is_method())
2795 no
->func_value()->descriptor(this->gogo_
, no
);
2796 else if (no
->is_function_declaration()
2797 && !no
->func_declaration_value()->type()->is_method()
2798 && !Linemap::is_predeclared_location(no
->location()))
2799 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
2800 return TRAVERSE_CONTINUE
;
2803 Bound_method_expression
* bme
= expr
->bound_method_expression();
2806 // We would not get here for a call to this method, so this is a
2807 // method value. We need to create a thunk.
2808 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
2810 return TRAVERSE_CONTINUE
;
2813 Interface_field_reference_expression
* ifre
=
2814 expr
->interface_field_reference_expression();
2817 // We would not get here for a call to this interface method, so
2818 // this is a method value. We need to create a thunk.
2819 Interface_type
* type
= ifre
->expr()->type()->interface_type();
2821 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
2823 return TRAVERSE_CONTINUE
;
2826 Call_expression
* ce
= expr
->call_expression();
2829 Expression
* fn
= ce
->fn();
2830 if (fn
->func_expression() != NULL
2831 || fn
->bound_method_expression() != NULL
2832 || fn
->interface_field_reference_expression() != NULL
)
2834 // Traverse the arguments but not the function.
2835 Expression_list
* args
= ce
->args();
2838 if (args
->traverse(this) == TRAVERSE_EXIT
)
2839 return TRAVERSE_EXIT
;
2841 return TRAVERSE_SKIP_COMPONENTS
;
2845 return TRAVERSE_CONTINUE
;
2848 // Create function descriptors as needed. We need a function
2849 // descriptor for all exported functions and for all functions that
2850 // are referenced without being called.
2853 Gogo::create_function_descriptors()
2855 // Create a function descriptor for any exported function that is
2856 // declared in this package. This is so that we have a descriptor
2857 // for functions written in assembly. Gather the descriptors first
2858 // so that we don't add declarations while looping over them.
2859 std::vector
<Named_object
*> fndecls
;
2860 Bindings
* b
= this->package_
->bindings();
2861 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
2862 p
!= b
->end_declarations();
2865 Named_object
* no
= p
->second
;
2866 if (no
->is_function_declaration()
2867 && !no
->func_declaration_value()->type()->is_method()
2868 && !Linemap::is_predeclared_location(no
->location())
2869 && !Gogo::is_hidden_name(no
->name()))
2870 fndecls
.push_back(no
);
2872 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
2875 (*p
)->func_declaration_value()->descriptor(this, *p
);
2878 Create_function_descriptors
cfd(this);
2879 this->traverse(&cfd
);
2882 // Look for interface types to finalize methods of inherited
2885 class Finalize_methods
: public Traverse
2888 Finalize_methods(Gogo
* gogo
)
2889 : Traverse(traverse_types
),
2900 // Finalize the methods of an interface type.
2903 Finalize_methods::type(Type
* t
)
2905 // Check the classification so that we don't finalize the methods
2906 // twice for a named interface type.
2907 switch (t
->classification())
2909 case Type::TYPE_INTERFACE
:
2910 t
->interface_type()->finalize_methods();
2913 case Type::TYPE_NAMED
:
2915 // We have to finalize the methods of the real type first.
2916 // But if the real type is a struct type, then we only want to
2917 // finalize the methods of the field types, not of the struct
2918 // type itself. We don't want to add methods to the struct,
2919 // since it has a name.
2920 Named_type
* nt
= t
->named_type();
2921 Type
* rt
= nt
->real_type();
2922 if (rt
->classification() != Type::TYPE_STRUCT
)
2924 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2925 return TRAVERSE_EXIT
;
2929 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2930 return TRAVERSE_EXIT
;
2933 nt
->finalize_methods(this->gogo_
);
2935 // If this type is defined in a different package, then finalize the
2936 // types of all the methods, since we won't see them otherwise.
2937 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
2939 const Methods
* methods
= nt
->methods();
2940 for (Methods::const_iterator p
= methods
->begin();
2941 p
!= methods
->end();
2944 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
2945 return TRAVERSE_EXIT
;
2949 // Finalize the types of all methods that are declared but not
2950 // defined, since we won't see the declarations otherwise.
2951 if (nt
->named_object()->package() == NULL
2952 && nt
->local_methods() != NULL
)
2954 const Bindings
* methods
= nt
->local_methods();
2955 for (Bindings::const_declarations_iterator p
=
2956 methods
->begin_declarations();
2957 p
!= methods
->end_declarations();
2960 if (p
->second
->is_function_declaration())
2962 Type
* mt
= p
->second
->func_declaration_value()->type();
2963 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
2964 return TRAVERSE_EXIT
;
2969 return TRAVERSE_SKIP_COMPONENTS
;
2972 case Type::TYPE_STRUCT
:
2973 // Traverse the field types first in case there is an embedded
2974 // field with methods that the struct should inherit.
2975 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
2976 return TRAVERSE_EXIT
;
2977 t
->struct_type()->finalize_methods(this->gogo_
);
2978 return TRAVERSE_SKIP_COMPONENTS
;
2984 return TRAVERSE_CONTINUE
;
2987 // Finalize method lists and build stub methods for types.
2990 Gogo::finalize_methods()
2992 Finalize_methods
finalize(this);
2993 this->traverse(&finalize
);
2996 // Set types for unspecified variables and constants.
2999 Gogo::determine_types()
3001 Bindings
* bindings
= this->current_bindings();
3002 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3003 p
!= bindings
->end_definitions();
3006 if ((*p
)->is_function())
3007 (*p
)->func_value()->determine_types();
3008 else if ((*p
)->is_variable())
3009 (*p
)->var_value()->determine_type();
3010 else if ((*p
)->is_const())
3011 (*p
)->const_value()->determine_type();
3013 // See if a variable requires us to build an initialization
3014 // function. We know that we will see all global variables
3016 if (!this->need_init_fn_
&& (*p
)->is_variable())
3018 Variable
* variable
= (*p
)->var_value();
3020 // If this is a global variable which requires runtime
3021 // initialization, we need an initialization function.
3022 if (!variable
->is_global())
3024 else if (variable
->init() == NULL
)
3026 else if (variable
->type()->interface_type() != NULL
)
3027 this->need_init_fn_
= true;
3028 else if (variable
->init()->is_constant())
3030 else if (!variable
->init()->is_composite_literal())
3031 this->need_init_fn_
= true;
3032 else if (variable
->init()->is_nonconstant_composite_literal())
3033 this->need_init_fn_
= true;
3035 // If this is a global variable which holds a pointer value,
3036 // then we need an initialization function to register it as a
3038 if (variable
->is_global() && variable
->type()->has_pointer())
3039 this->need_init_fn_
= true;
3043 // Determine the types of constants in packages.
3044 for (Packages::const_iterator p
= this->packages_
.begin();
3045 p
!= this->packages_
.end();
3047 p
->second
->determine_types();
3050 // Traversal class used for type checking.
3052 class Check_types_traverse
: public Traverse
3055 Check_types_traverse(Gogo
* gogo
)
3056 : Traverse(traverse_variables
3057 | traverse_constants
3058 | traverse_functions
3059 | traverse_statements
3060 | traverse_expressions
),
3065 variable(Named_object
*);
3068 constant(Named_object
*, bool);
3071 function(Named_object
*);
3074 statement(Block
*, size_t* pindex
, Statement
*);
3077 expression(Expression
**);
3084 // Check that a variable initializer has the right type.
3087 Check_types_traverse::variable(Named_object
* named_object
)
3089 if (named_object
->is_variable())
3091 Variable
* var
= named_object
->var_value();
3093 // Give error if variable type is not defined.
3094 var
->type()->base();
3096 Expression
* init
= var
->init();
3099 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3102 go_error_at(var
->location(), "incompatible type in initialization");
3104 go_error_at(var
->location(),
3105 "incompatible type in initialization (%s)",
3107 init
= Expression::make_error(named_object
->location());
3110 else if (init
!= NULL
3111 && init
->func_expression() != NULL
)
3113 Named_object
* no
= init
->func_expression()->named_object();
3114 Function_type
* fntype
;
3115 if (no
->is_function())
3116 fntype
= no
->func_value()->type();
3117 else if (no
->is_function_declaration())
3118 fntype
= no
->func_declaration_value()->type();
3122 // Builtin functions cannot be used as function values for variable
3124 if (fntype
->is_builtin())
3126 go_error_at(init
->location(),
3127 "invalid use of special builtin function %qs; "
3129 no
->message_name().c_str());
3133 && !var
->is_global()
3134 && !var
->is_parameter()
3135 && !var
->is_receiver()
3136 && !var
->type()->is_error()
3137 && (init
== NULL
|| !init
->is_error_expression())
3138 && !Lex::is_invalid_identifier(named_object
->name()))
3139 go_error_at(var
->location(), "%qs declared and not used",
3140 named_object
->message_name().c_str());
3142 return TRAVERSE_CONTINUE
;
3145 // Check that a constant initializer has the right type.
3148 Check_types_traverse::constant(Named_object
* named_object
, bool)
3150 Named_constant
* constant
= named_object
->const_value();
3151 Type
* ctype
= constant
->type();
3152 if (ctype
->integer_type() == NULL
3153 && ctype
->float_type() == NULL
3154 && ctype
->complex_type() == NULL
3155 && !ctype
->is_boolean_type()
3156 && !ctype
->is_string_type())
3158 if (ctype
->is_nil_type())
3159 go_error_at(constant
->location(), "const initializer cannot be nil");
3160 else if (!ctype
->is_error())
3161 go_error_at(constant
->location(), "invalid constant type");
3162 constant
->set_error();
3164 else if (!constant
->expr()->is_constant())
3166 go_error_at(constant
->expr()->location(), "expression is not constant");
3167 constant
->set_error();
3169 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3172 go_error_at(constant
->location(),
3173 "initialization expression has wrong type");
3174 constant
->set_error();
3176 return TRAVERSE_CONTINUE
;
3179 // There are no types to check in a function, but this is where we
3180 // issue warnings about labels which are defined but not referenced.
3183 Check_types_traverse::function(Named_object
* no
)
3185 no
->func_value()->check_labels();
3186 return TRAVERSE_CONTINUE
;
3189 // Check that types are valid in a statement.
3192 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3194 s
->check_types(this->gogo_
);
3195 return TRAVERSE_CONTINUE
;
3198 // Check that types are valid in an expression.
3201 Check_types_traverse::expression(Expression
** expr
)
3203 (*expr
)->check_types(this->gogo_
);
3204 return TRAVERSE_CONTINUE
;
3207 // Check that types are valid.
3212 Check_types_traverse
traverse(this);
3213 this->traverse(&traverse
);
3215 Bindings
* bindings
= this->current_bindings();
3216 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3217 p
!= bindings
->end_declarations();
3220 // Also check the types in a function declaration's signature.
3221 Named_object
* no
= p
->second
;
3222 if (no
->is_function_declaration())
3223 no
->func_declaration_value()->check_types();
3227 // Check the types in a single block.
3230 Gogo::check_types_in_block(Block
* block
)
3232 Check_types_traverse
traverse(this);
3233 block
->traverse(&traverse
);
3236 // A traversal class used to find a single shortcut operator within an
3239 class Find_shortcut
: public Traverse
3243 : Traverse(traverse_blocks
3244 | traverse_statements
3245 | traverse_expressions
),
3249 // A pointer to the expression which was found, or NULL if none was
3253 { return this->found_
; }
3258 { return TRAVERSE_SKIP_COMPONENTS
; }
3261 statement(Block
*, size_t*, Statement
*)
3262 { return TRAVERSE_SKIP_COMPONENTS
; }
3265 expression(Expression
**);
3268 Expression
** found_
;
3271 // Find a shortcut expression.
3274 Find_shortcut::expression(Expression
** pexpr
)
3276 Expression
* expr
= *pexpr
;
3277 Binary_expression
* be
= expr
->binary_expression();
3279 return TRAVERSE_CONTINUE
;
3280 Operator op
= be
->op();
3281 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
3282 return TRAVERSE_CONTINUE
;
3283 go_assert(this->found_
== NULL
);
3284 this->found_
= pexpr
;
3285 return TRAVERSE_EXIT
;
3288 // A traversal class used to turn shortcut operators into explicit if
3291 class Shortcuts
: public Traverse
3294 Shortcuts(Gogo
* gogo
)
3295 : Traverse(traverse_variables
3296 | traverse_statements
),
3302 variable(Named_object
*);
3305 statement(Block
*, size_t*, Statement
*);
3308 // Convert a shortcut operator.
3310 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
3316 // Remove shortcut operators in a single statement.
3319 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3321 // FIXME: This approach doesn't work for switch statements, because
3322 // we add the new statements before the whole switch when we need to
3323 // instead add them just before the switch expression. The right
3324 // fix is probably to lower switch statements with nonconstant cases
3325 // to a series of conditionals.
3326 if (s
->switch_statement() != NULL
)
3327 return TRAVERSE_CONTINUE
;
3331 Find_shortcut find_shortcut
;
3333 // If S is a variable declaration, then ordinary traversal won't
3334 // do anything. We want to explicitly traverse the
3335 // initialization expression if there is one.
3336 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3337 Expression
* init
= NULL
;
3339 s
->traverse_contents(&find_shortcut
);
3342 init
= vds
->var()->var_value()->init();
3344 return TRAVERSE_CONTINUE
;
3345 init
->traverse(&init
, &find_shortcut
);
3347 Expression
** pshortcut
= find_shortcut
.found();
3348 if (pshortcut
== NULL
)
3349 return TRAVERSE_CONTINUE
;
3351 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
3352 block
->insert_statement_before(*pindex
, snew
);
3355 if (pshortcut
== &init
)
3356 vds
->var()->var_value()->set_init(init
);
3360 // Remove shortcut operators in the initializer of a global variable.
3363 Shortcuts::variable(Named_object
* no
)
3365 if (no
->is_result_variable())
3366 return TRAVERSE_CONTINUE
;
3367 Variable
* var
= no
->var_value();
3368 Expression
* init
= var
->init();
3369 if (!var
->is_global() || init
== NULL
)
3370 return TRAVERSE_CONTINUE
;
3374 Find_shortcut find_shortcut
;
3375 init
->traverse(&init
, &find_shortcut
);
3376 Expression
** pshortcut
= find_shortcut
.found();
3377 if (pshortcut
== NULL
)
3378 return TRAVERSE_CONTINUE
;
3380 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
3381 var
->add_preinit_statement(this->gogo_
, snew
);
3382 if (pshortcut
== &init
)
3383 var
->set_init(init
);
3387 // Given an expression which uses a shortcut operator, return a
3388 // statement which implements it, and update *PSHORTCUT accordingly.
3391 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
3393 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
3394 Expression
* left
= shortcut
->left();
3395 Expression
* right
= shortcut
->right();
3396 Location loc
= shortcut
->location();
3398 Block
* retblock
= new Block(enclosing
, loc
);
3399 retblock
->set_end_location(loc
);
3401 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
3403 retblock
->add_statement(ts
);
3405 Block
* block
= new Block(retblock
, loc
);
3406 block
->set_end_location(loc
);
3407 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
3408 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
3409 block
->add_statement(assign
);
3411 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
3412 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
3413 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
3415 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
3417 retblock
->add_statement(if_statement
);
3419 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
3423 // Now convert any shortcut operators in LEFT and RIGHT.
3424 Shortcuts
shortcuts(this->gogo_
);
3425 retblock
->traverse(&shortcuts
);
3427 return Statement::make_block_statement(retblock
, loc
);
3430 // Turn shortcut operators into explicit if statements. Doing this
3431 // considerably simplifies the order of evaluation rules.
3434 Gogo::remove_shortcuts()
3436 Shortcuts
shortcuts(this);
3437 this->traverse(&shortcuts
);
3440 // A traversal class which finds all the expressions which must be
3441 // evaluated in order within a statement or larger expression. This
3442 // is used to implement the rules about order of evaluation.
3444 class Find_eval_ordering
: public Traverse
3447 typedef std::vector
<Expression
**> Expression_pointers
;
3450 Find_eval_ordering()
3451 : Traverse(traverse_blocks
3452 | traverse_statements
3453 | traverse_expressions
),
3459 { return this->exprs_
.size(); }
3461 typedef Expression_pointers::const_iterator const_iterator
;
3465 { return this->exprs_
.begin(); }
3469 { return this->exprs_
.end(); }
3474 { return TRAVERSE_SKIP_COMPONENTS
; }
3477 statement(Block
*, size_t*, Statement
*)
3478 { return TRAVERSE_SKIP_COMPONENTS
; }
3481 expression(Expression
**);
3484 // A list of pointers to expressions with side-effects.
3485 Expression_pointers exprs_
;
3488 // If an expression must be evaluated in order, put it on the list.
3491 Find_eval_ordering::expression(Expression
** expression_pointer
)
3493 // We have to look at subexpressions before this one.
3494 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3495 return TRAVERSE_EXIT
;
3496 if ((*expression_pointer
)->must_eval_in_order())
3497 this->exprs_
.push_back(expression_pointer
);
3498 return TRAVERSE_SKIP_COMPONENTS
;
3501 // A traversal class for ordering evaluations.
3503 class Order_eval
: public Traverse
3506 Order_eval(Gogo
* gogo
)
3507 : Traverse(traverse_variables
3508 | traverse_statements
),
3513 variable(Named_object
*);
3516 statement(Block
*, size_t*, Statement
*);
3523 // Implement the order of evaluation rules for a statement.
3526 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* s
)
3528 // FIXME: This approach doesn't work for switch statements, because
3529 // we add the new statements before the whole switch when we need to
3530 // instead add them just before the switch expression. The right
3531 // fix is probably to lower switch statements with nonconstant cases
3532 // to a series of conditionals.
3533 if (s
->switch_statement() != NULL
)
3534 return TRAVERSE_CONTINUE
;
3536 Find_eval_ordering find_eval_ordering
;
3538 // If S is a variable declaration, then ordinary traversal won't do
3539 // anything. We want to explicitly traverse the initialization
3540 // expression if there is one.
3541 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
3542 Expression
* init
= NULL
;
3543 Expression
* orig_init
= NULL
;
3545 s
->traverse_contents(&find_eval_ordering
);
3548 init
= vds
->var()->var_value()->init();
3550 return TRAVERSE_CONTINUE
;
3553 // It might seem that this could be
3554 // init->traverse_subexpressions. Unfortunately that can fail
3557 // newvar, err := call(arg())
3558 // Here newvar will have an init of call result 0 of
3559 // call(arg()). If we only traverse subexpressions, we will
3560 // only find arg(), and we won't bother to move anything out.
3561 // Then we get to the assignment to err, we will traverse the
3562 // whole statement, and this time we will find both call() and
3563 // arg(), and so we will move them out. This will cause them to
3564 // be put into temporary variables before the assignment to err
3565 // but after the declaration of newvar. To avoid that problem,
3566 // we traverse the entire expression here.
3567 Expression::traverse(&init
, &find_eval_ordering
);
3570 size_t c
= find_eval_ordering
.size();
3572 return TRAVERSE_CONTINUE
;
3574 // If there is only one expression with a side-effect, we can
3575 // usually leave it in place.
3578 switch (s
->classification())
3580 case Statement::STATEMENT_ASSIGNMENT
:
3581 // For an assignment statement, we need to evaluate an
3582 // expression on the right hand side before we evaluate any
3583 // index expression on the left hand side, so for that case
3584 // we always move the expression. Otherwise we mishandle
3585 // m[0] = len(m) where m is a map.
3588 case Statement::STATEMENT_EXPRESSION
:
3590 // If this is a call statement that doesn't return any
3591 // values, it will not have been counted as a value to
3592 // move. We need to move any subexpressions in case they
3593 // are themselves call statements that require passing a
3595 Expression
* expr
= s
->expression_statement()->expr();
3596 if (expr
->call_expression() != NULL
3597 && expr
->call_expression()->result_count() == 0)
3599 return TRAVERSE_CONTINUE
;
3603 // We can leave the expression in place.
3604 return TRAVERSE_CONTINUE
;
3608 bool is_thunk
= s
->thunk_statement() != NULL
;
3609 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3610 p
!= find_eval_ordering
.end();
3613 Expression
** pexpr
= *p
;
3615 // The last expression in a thunk will be the call passed to go
3616 // or defer, which we must not evaluate early.
3617 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
3620 Location loc
= (*pexpr
)->location();
3622 if ((*pexpr
)->call_expression() == NULL
3623 || (*pexpr
)->call_expression()->result_count() < 2)
3625 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3628 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3632 // A call expression which returns multiple results needs to
3633 // be handled specially. We can't create a temporary
3634 // because there is no type to give it. Any actual uses of
3635 // the values will be done via Call_result_expressions.
3637 // Since a given call expression can be shared by multiple
3638 // Call_result_expressions, avoid hoisting the call the
3639 // second time we see it here.
3640 if (this->remember_expression(*pexpr
))
3643 s
= Statement::make_statement(*pexpr
, true);
3648 block
->insert_statement_before(*pindex
, s
);
3653 if (init
!= orig_init
)
3654 vds
->var()->var_value()->set_init(init
);
3656 return TRAVERSE_CONTINUE
;
3659 // Implement the order of evaluation rules for the initializer of a
3663 Order_eval::variable(Named_object
* no
)
3665 if (no
->is_result_variable())
3666 return TRAVERSE_CONTINUE
;
3667 Variable
* var
= no
->var_value();
3668 Expression
* init
= var
->init();
3669 if (!var
->is_global() || init
== NULL
)
3670 return TRAVERSE_CONTINUE
;
3672 Find_eval_ordering find_eval_ordering
;
3673 Expression::traverse(&init
, &find_eval_ordering
);
3675 if (find_eval_ordering
.size() <= 1)
3677 // If there is only one expression with a side-effect, we can
3678 // leave it in place.
3679 return TRAVERSE_SKIP_COMPONENTS
;
3682 Expression
* orig_init
= init
;
3684 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
3685 p
!= find_eval_ordering
.end();
3688 Expression
** pexpr
= *p
;
3689 Location loc
= (*pexpr
)->location();
3691 if ((*pexpr
)->call_expression() == NULL
3692 || (*pexpr
)->call_expression()->result_count() < 2)
3694 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
3697 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
3701 // A call expression which returns multiple results needs to
3702 // be handled specially.
3703 s
= Statement::make_statement(*pexpr
, true);
3705 var
->add_preinit_statement(this->gogo_
, s
);
3708 if (init
!= orig_init
)
3709 var
->set_init(init
);
3711 return TRAVERSE_SKIP_COMPONENTS
;
3714 // Use temporary variables to implement the order of evaluation rules.
3717 Gogo::order_evaluations()
3719 Order_eval
order_eval(this);
3720 this->traverse(&order_eval
);
3723 // Traversal to flatten parse tree after order of evaluation rules are applied.
3725 class Flatten
: public Traverse
3728 Flatten(Gogo
* gogo
, Named_object
* function
)
3729 : Traverse(traverse_variables
3730 | traverse_functions
3731 | traverse_statements
3732 | traverse_expressions
),
3733 gogo_(gogo
), function_(function
), inserter_()
3737 set_inserter(const Statement_inserter
* inserter
)
3738 { this->inserter_
= *inserter
; }
3741 variable(Named_object
*);
3744 function(Named_object
*);
3747 statement(Block
*, size_t* pindex
, Statement
*);
3750 expression(Expression
**);
3755 // The function we are traversing.
3756 Named_object
* function_
;
3757 // Current statement inserter for use by expressions.
3758 Statement_inserter inserter_
;
3761 // Flatten variables.
3764 Flatten::variable(Named_object
* no
)
3766 if (!no
->is_variable())
3767 return TRAVERSE_CONTINUE
;
3769 if (no
->is_variable() && no
->var_value()->is_global())
3771 // Global variables can have loops in their initialization
3772 // expressions. This is handled in flatten_init_expression.
3773 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
3775 return TRAVERSE_CONTINUE
;
3778 go_assert(!no
->var_value()->has_pre_init());
3780 return TRAVERSE_SKIP_COMPONENTS
;
3783 // Flatten the body of a function. Record the function while flattening it,
3784 // so that we can pass it down when flattening an expression.
3787 Flatten::function(Named_object
* no
)
3789 go_assert(this->function_
== NULL
);
3790 this->function_
= no
;
3791 int t
= no
->func_value()->traverse(this);
3792 this->function_
= NULL
;
3794 if (t
== TRAVERSE_EXIT
)
3796 return TRAVERSE_SKIP_COMPONENTS
;
3799 // Flatten statement parse trees.
3802 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3804 // Because we explicitly traverse the statement's contents
3805 // ourselves, we want to skip block statements here. There is
3806 // nothing to flatten in a block statement.
3807 if (sorig
->is_block_statement())
3808 return TRAVERSE_CONTINUE
;
3810 Statement_inserter
hold_inserter(this->inserter_
);
3811 this->inserter_
= Statement_inserter(block
, pindex
);
3813 // Flatten the expressions first.
3814 int t
= sorig
->traverse_contents(this);
3815 if (t
== TRAVERSE_EXIT
)
3817 this->inserter_
= hold_inserter
;
3821 // Keep flattening until nothing changes.
3822 Statement
* s
= sorig
;
3825 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
3830 t
= s
->traverse_contents(this);
3831 if (t
== TRAVERSE_EXIT
)
3833 this->inserter_
= hold_inserter
;
3839 block
->replace_statement(*pindex
, s
);
3841 this->inserter_
= hold_inserter
;
3842 return TRAVERSE_SKIP_COMPONENTS
;
3845 // Flatten expression parse trees.
3848 Flatten::expression(Expression
** pexpr
)
3850 // Keep flattening until nothing changes.
3853 Expression
* e
= *pexpr
;
3854 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3855 return TRAVERSE_EXIT
;
3857 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
3863 return TRAVERSE_SKIP_COMPONENTS
;
3869 Gogo::flatten_block(Named_object
* function
, Block
* block
)
3871 Flatten
flatten(this, function
);
3872 block
->traverse(&flatten
);
3875 // Flatten an expression. INSERTER may be NULL, in which case the
3876 // expression had better not need to create any temporaries.
3879 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
3882 Flatten
flatten(this, function
);
3883 if (inserter
!= NULL
)
3884 flatten
.set_inserter(inserter
);
3885 flatten
.expression(pexpr
);
3891 Flatten
flatten(this, NULL
);
3892 this->traverse(&flatten
);
3895 // Traversal to convert calls to the predeclared recover function to
3896 // pass in an argument indicating whether it can recover from a panic
3899 class Convert_recover
: public Traverse
3902 Convert_recover(Named_object
* arg
)
3903 : Traverse(traverse_expressions
),
3909 expression(Expression
**);
3912 // The argument to pass to the function.
3916 // Convert calls to recover.
3919 Convert_recover::expression(Expression
** pp
)
3921 Call_expression
* ce
= (*pp
)->call_expression();
3922 if (ce
!= NULL
&& ce
->is_recover_call())
3923 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
3925 return TRAVERSE_CONTINUE
;
3928 // Traversal for build_recover_thunks.
3930 class Build_recover_thunks
: public Traverse
3933 Build_recover_thunks(Gogo
* gogo
)
3934 : Traverse(traverse_functions
),
3939 function(Named_object
*);
3943 can_recover_arg(Location
);
3949 // If this function calls recover, turn it into a thunk.
3952 Build_recover_thunks::function(Named_object
* orig_no
)
3954 Function
* orig_func
= orig_no
->func_value();
3955 if (!orig_func
->calls_recover()
3956 || orig_func
->is_recover_thunk()
3957 || orig_func
->has_recover_thunk())
3958 return TRAVERSE_CONTINUE
;
3960 Gogo
* gogo
= this->gogo_
;
3961 Location location
= orig_func
->location();
3966 Function_type
* orig_fntype
= orig_func
->type();
3967 Typed_identifier_list
* new_params
= new Typed_identifier_list();
3968 std::string receiver_name
;
3969 if (orig_fntype
->is_method())
3971 const Typed_identifier
* receiver
= orig_fntype
->receiver();
3972 snprintf(buf
, sizeof buf
, "rt.%u", count
);
3974 receiver_name
= buf
;
3975 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
3976 receiver
->location()));
3978 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
3979 if (orig_params
!= NULL
&& !orig_params
->empty())
3981 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
3982 p
!= orig_params
->end();
3985 snprintf(buf
, sizeof buf
, "pt.%u", count
);
3987 new_params
->push_back(Typed_identifier(buf
, p
->type(),
3991 snprintf(buf
, sizeof buf
, "pr.%u", count
);
3993 std::string can_recover_name
= buf
;
3994 new_params
->push_back(Typed_identifier(can_recover_name
,
3995 Type::lookup_bool_type(),
3996 orig_fntype
->location()));
3998 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
3999 Typed_identifier_list
* new_results
;
4000 if (orig_results
== NULL
|| orig_results
->empty())
4004 new_results
= new Typed_identifier_list();
4005 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4006 p
!= orig_results
->end();
4008 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4011 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4013 orig_fntype
->location());
4014 if (orig_fntype
->is_varargs())
4015 new_fntype
->set_is_varargs();
4017 std::string name
= orig_no
->name();
4018 if (orig_fntype
->is_method())
4019 name
+= "$" + orig_fntype
->receiver()->type()->mangled_name(gogo
);
4021 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4023 Function
*new_func
= new_no
->func_value();
4024 if (orig_func
->enclosing() != NULL
)
4025 new_func
->set_enclosing(orig_func
->enclosing());
4027 // We build the code for the original function attached to the new
4028 // function, and then swap the original and new function bodies.
4029 // This means that existing references to the original function will
4030 // then refer to the new function. That makes this code a little
4031 // confusing, in that the reference to NEW_NO really refers to the
4032 // other function, not the one we are building.
4034 Expression
* closure
= NULL
;
4035 if (orig_func
->needs_closure())
4037 // For the new function we are creating, declare a new parameter
4038 // variable NEW_CLOSURE_NO and set it to be the closure variable
4039 // of the function. This will be set to the closure value
4040 // passed in by the caller. Then pass a reference to this
4041 // variable as the closure value when calling the original
4042 // function. In other words, simply pass the closure value
4043 // through the thunk we are creating.
4044 Named_object
* orig_closure_no
= orig_func
->closure_var();
4045 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4046 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4047 false, false, location
);
4048 new_var
->set_is_closure();
4049 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4051 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4053 new_func
->set_closure_var(new_closure_no
);
4054 closure
= Expression::make_var_reference(new_closure_no
, location
);
4057 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4059 Expression_list
* args
= new Expression_list();
4060 if (new_params
!= NULL
)
4062 // Note that we skip the last parameter, which is the boolean
4063 // indicating whether recover can succed.
4064 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4065 p
+ 1 != new_params
->end();
4068 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4069 go_assert(p_no
!= NULL
4070 && p_no
->is_variable()
4071 && p_no
->var_value()->is_parameter());
4072 args
->push_back(Expression::make_var_reference(p_no
, location
));
4075 args
->push_back(this->can_recover_arg(location
));
4077 gogo
->start_block(location
);
4079 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4081 // Any varargs call has already been lowered.
4082 call
->set_varargs_are_lowered();
4084 Statement
* s
= Statement::make_return_from_call(call
, location
);
4085 s
->determine_types();
4086 gogo
->add_statement(s
);
4088 Block
* b
= gogo
->finish_block(location
);
4090 gogo
->add_block(b
, location
);
4092 // Lower the call in case it returns multiple results.
4093 gogo
->lower_block(new_no
, b
);
4095 gogo
->finish_function(location
);
4097 // Swap the function bodies and types.
4098 new_func
->swap_for_recover(orig_func
);
4099 orig_func
->set_is_recover_thunk();
4100 new_func
->set_calls_recover();
4101 new_func
->set_has_recover_thunk();
4103 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4104 Bindings
* new_bindings
= new_func
->block()->bindings();
4105 if (orig_fntype
->is_method())
4107 // We changed the receiver to be a regular parameter. We have
4108 // to update the binding accordingly in both functions.
4109 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4110 go_assert(orig_rec_no
!= NULL
4111 && orig_rec_no
->is_variable()
4112 && !orig_rec_no
->var_value()->is_receiver());
4113 orig_rec_no
->var_value()->set_is_receiver();
4115 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4116 if (new_receiver_name
.empty())
4118 // Find the receiver. It was named "r.NNN" in
4119 // Gogo::start_function.
4120 for (Bindings::const_definitions_iterator p
=
4121 new_bindings
->begin_definitions();
4122 p
!= new_bindings
->end_definitions();
4125 const std::string
& pname((*p
)->name());
4126 if (pname
[0] == 'r' && pname
[1] == '.')
4128 new_receiver_name
= pname
;
4132 go_assert(!new_receiver_name
.empty());
4134 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4135 if (new_rec_no
== NULL
)
4136 go_assert(saw_errors());
4139 go_assert(new_rec_no
->is_variable()
4140 && new_rec_no
->var_value()->is_receiver());
4141 new_rec_no
->var_value()->set_is_not_receiver();
4145 // Because we flipped blocks but not types, the can_recover
4146 // parameter appears in the (now) old bindings as a parameter.
4147 // Change it to a local variable, whereupon it will be discarded.
4148 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4149 go_assert(can_recover_no
!= NULL
4150 && can_recover_no
->is_variable()
4151 && can_recover_no
->var_value()->is_parameter());
4152 orig_bindings
->remove_binding(can_recover_no
);
4154 // Add the can_recover argument to the (now) new bindings, and
4155 // attach it to any recover statements.
4156 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4157 false, true, false, location
);
4158 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4160 Convert_recover
convert_recover(can_recover_no
);
4161 new_func
->traverse(&convert_recover
);
4163 // Update the function pointers in any named results.
4164 new_func
->update_result_variables();
4165 orig_func
->update_result_variables();
4167 return TRAVERSE_CONTINUE
;
4170 // Return the expression to pass for the .can_recover parameter to the
4171 // new function. This indicates whether a call to recover may return
4172 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4175 Build_recover_thunks::can_recover_arg(Location location
)
4177 static Named_object
* builtin_return_address
;
4178 if (builtin_return_address
== NULL
)
4179 builtin_return_address
=
4180 Gogo::declare_builtin_rf_address("__builtin_return_address");
4182 static Named_object
* can_recover
;
4183 if (can_recover
== NULL
)
4185 const Location bloc
= Linemap::predeclared_location();
4186 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4187 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4188 param_types
->push_back(Typed_identifier("a", voidptr_type
, bloc
));
4189 Type
* boolean_type
= Type::lookup_bool_type();
4190 Typed_identifier_list
* results
= new Typed_identifier_list();
4191 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4192 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4195 Named_object::make_function_declaration("runtime_canrecover",
4196 NULL
, fntype
, bloc
);
4197 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4200 Expression
* fn
= Expression::make_func_reference(builtin_return_address
,
4203 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4204 Expression_list
*args
= new Expression_list();
4205 args
->push_back(zexpr
);
4207 Expression
* call
= Expression::make_call(fn
, args
, false, location
);
4209 args
= new Expression_list();
4210 args
->push_back(call
);
4212 fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4213 return Expression::make_call(fn
, args
, false, location
);
4216 // Build thunks for functions which call recover. We build a new
4217 // function with an extra parameter, which is whether a call to
4218 // recover can succeed. We then move the body of this function to
4219 // that one. We then turn this function into a thunk which calls the
4220 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4221 // The function will be marked as not splitting the stack. This will
4222 // cooperate with the implementation of defer to make recover do the
4226 Gogo::build_recover_thunks()
4228 Build_recover_thunks
build_recover_thunks(this);
4229 this->traverse(&build_recover_thunks
);
4232 // Return a declaration for __builtin_return_address or
4233 // __builtin_frame_address.
4236 Gogo::declare_builtin_rf_address(const char* name
)
4238 const Location bloc
= Linemap::predeclared_location();
4240 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4241 Type
* uint32_type
= Type::lookup_integer_type("uint32");
4242 param_types
->push_back(Typed_identifier("l", uint32_type
, bloc
));
4244 Typed_identifier_list
* return_types
= new Typed_identifier_list();
4245 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4246 return_types
->push_back(Typed_identifier("", voidptr_type
, bloc
));
4248 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4249 return_types
, bloc
);
4250 Named_object
* ret
= Named_object::make_function_declaration(name
, NULL
,
4252 ret
->func_declaration_value()->set_asm_name(name
);
4256 // Build a call to the runtime error function.
4259 Gogo::runtime_error(int code
, Location location
)
4261 Type
* int32_type
= Type::lookup_integer_type("int32");
4262 Expression
* code_expr
= Expression::make_integer_ul(code
, int32_type
,
4264 return Runtime::make_call(Runtime::RUNTIME_ERROR
, location
, 1, code_expr
);
4267 // Look for named types to see whether we need to create an interface
4270 class Build_method_tables
: public Traverse
4273 Build_method_tables(Gogo
* gogo
,
4274 const std::vector
<Interface_type
*>& interfaces
)
4275 : Traverse(traverse_types
),
4276 gogo_(gogo
), interfaces_(interfaces
)
4285 // A list of locally defined interfaces which have hidden methods.
4286 const std::vector
<Interface_type
*>& interfaces_
;
4289 // Build all required interface method tables for types. We need to
4290 // ensure that we have an interface method table for every interface
4291 // which has a hidden method, for every named type which implements
4292 // that interface. Normally we can just build interface method tables
4293 // as we need them. However, in some cases we can require an
4294 // interface method table for an interface defined in a different
4295 // package for a type defined in that package. If that interface and
4296 // type both use a hidden method, that is OK. However, we will not be
4297 // able to build that interface method table when we need it, because
4298 // the type's hidden method will be static. So we have to build it
4299 // here, and just refer it from other packages as needed.
4302 Gogo::build_interface_method_tables()
4307 std::vector
<Interface_type
*> hidden_interfaces
;
4308 hidden_interfaces
.reserve(this->interface_types_
.size());
4309 for (std::vector
<Interface_type
*>::const_iterator pi
=
4310 this->interface_types_
.begin();
4311 pi
!= this->interface_types_
.end();
4314 const Typed_identifier_list
* methods
= (*pi
)->methods();
4315 if (methods
== NULL
)
4317 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4318 pm
!= methods
->end();
4321 if (Gogo::is_hidden_name(pm
->name()))
4323 hidden_interfaces
.push_back(*pi
);
4329 if (!hidden_interfaces
.empty())
4331 // Now traverse the tree looking for all named types.
4332 Build_method_tables
bmt(this, hidden_interfaces
);
4333 this->traverse(&bmt
);
4336 // We no longer need the list of interfaces.
4338 this->interface_types_
.clear();
4341 // This is called for each type. For a named type, for each of the
4342 // interfaces with hidden methods that it implements, create the
4346 Build_method_tables::type(Type
* type
)
4348 Named_type
* nt
= type
->named_type();
4349 Struct_type
* st
= type
->struct_type();
4350 if (nt
!= NULL
|| st
!= NULL
)
4352 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4353 for (std::vector
<Interface_type
*>::const_iterator p
=
4354 this->interfaces_
.begin();
4355 p
!= this->interfaces_
.end();
4358 // We ask whether a pointer to the named type implements the
4359 // interface, because a pointer can implement more methods
4363 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4366 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4367 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4372 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
4375 st
->interface_method_table(*p
, false)->get_backend(&context
);
4376 st
->interface_method_table(*p
, true)->get_backend(&context
);
4381 return TRAVERSE_CONTINUE
;
4384 // Return an expression which allocates memory to hold values of type TYPE.
4387 Gogo::allocate_memory(Type
* type
, Location location
)
4389 Expression
* td
= Expression::make_type_descriptor(type
, location
);
4391 Expression::make_type_info(type
, Expression::TYPE_INFO_SIZE
);
4392 return Runtime::make_call(Runtime::NEW
, location
, 2, td
, size
);
4395 // Traversal class used to check for return statements.
4397 class Check_return_statements_traverse
: public Traverse
4400 Check_return_statements_traverse()
4401 : Traverse(traverse_functions
)
4405 function(Named_object
*);
4408 // Check that a function has a return statement if it needs one.
4411 Check_return_statements_traverse::function(Named_object
* no
)
4413 Function
* func
= no
->func_value();
4414 const Function_type
* fntype
= func
->type();
4415 const Typed_identifier_list
* results
= fntype
->results();
4417 // We only need a return statement if there is a return value.
4418 if (results
== NULL
|| results
->empty())
4419 return TRAVERSE_CONTINUE
;
4421 if (func
->block()->may_fall_through())
4422 go_error_at(func
->block()->end_location(),
4423 "missing return at end of function");
4425 return TRAVERSE_CONTINUE
;
4428 // Check return statements.
4431 Gogo::check_return_statements()
4433 Check_return_statements_traverse traverse
;
4434 this->traverse(&traverse
);
4437 // Export identifiers as requested.
4442 // For now we always stream to a section. Later we may want to
4443 // support streaming to a separate file.
4444 Stream_to_section stream
;
4446 // Write out either the prefix or pkgpath depending on how we were
4449 std::string pkgpath
;
4450 if (this->pkgpath_from_option_
)
4451 pkgpath
= this->pkgpath_
;
4452 else if (this->prefix_from_option_
)
4453 prefix
= this->prefix_
;
4454 else if (this->is_main_package())
4459 Export
exp(&stream
);
4460 exp
.register_builtin_types(this);
4461 exp
.export_globals(this->package_name(),
4466 (this->need_init_fn_
&& !this->is_main_package()
4467 ? this->get_init_fn_name()
4469 this->imported_init_fns_
,
4470 this->package_
->bindings());
4472 if (!this->c_header_
.empty() && !saw_errors())
4473 this->write_c_header();
4476 // Write the top level named struct types in C format to a C header
4477 // file. This is used when building the runtime package, to share
4478 // struct definitions between C and Go.
4481 Gogo::write_c_header()
4484 out
.open(this->c_header_
.c_str());
4487 go_error_at(Linemap::unknown_location(),
4488 "cannot open %s: %m", this->c_header_
.c_str());
4492 std::list
<Named_object
*> types
;
4493 Bindings
* top
= this->package_
->bindings();
4494 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
4495 p
!= top
->end_definitions();
4498 Named_object
* no
= *p
;
4500 // Skip names that start with underscore followed by something
4501 // other than an uppercase letter, as when compiling the runtime
4502 // package they are mostly types defined by mkrsysinfo.sh based
4503 // on the C system header files. We don't need to translate
4504 // types to C and back to Go. But do accept the special cases
4505 // _defer and _panic.
4506 std::string name
= Gogo::unpack_hidden_name(no
->name());
4508 && (name
[1] < 'A' || name
[1] > 'Z')
4509 && (name
!= "_defer" && name
!= "_panic"))
4512 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
4513 types
.push_back(no
);
4514 if (no
->is_const() && no
->const_value()->type()->integer_type() != NULL
)
4516 Numeric_constant nc
;
4518 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
4519 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
4521 out
<< "#define " << no
->message_name() << ' ' << val
4527 std::vector
<const Named_object
*> written
;
4529 while (!types
.empty())
4531 Named_object
* no
= types
.front();
4534 std::vector
<const Named_object
*> requires
;
4535 std::vector
<const Named_object
*> declare
;
4536 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
4541 for (std::vector
<const Named_object
*>::const_iterator pr
4543 pr
!= requires
.end() && ok
;
4546 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
4547 pt
!= types
.end() && ok
;
4557 // This should be impossible since the code parsed and
4562 types
.push_back(no
);
4566 for (std::vector
<const Named_object
*>::const_iterator pd
4568 pd
!= declare
.end();
4574 std::vector
<const Named_object
*> drequires
;
4575 std::vector
<const Named_object
*> ddeclare
;
4576 if (!(*pd
)->type_value()->struct_type()->
4577 can_write_to_c_header(&drequires
, &ddeclare
))
4581 for (std::vector
<const Named_object
*>::const_iterator pw
4583 pw
!= written
.end();
4595 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
4596 written
.push_back(*pd
);
4601 out
<< "struct " << no
->message_name() << " {" << std::endl
;
4602 no
->type_value()->struct_type()->write_to_c_header(out
);
4603 out
<< "};" << std::endl
;
4604 written
.push_back(no
);
4609 go_error_at(Linemap::unknown_location(),
4610 "error writing to %s: %m", this->c_header_
.c_str());
4613 // Find the blocks in order to convert named types defined in blocks.
4615 class Convert_named_types
: public Traverse
4618 Convert_named_types(Gogo
* gogo
)
4619 : Traverse(traverse_blocks
),
4625 block(Block
* block
);
4632 Convert_named_types::block(Block
* block
)
4634 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
4635 return TRAVERSE_CONTINUE
;
4638 // Convert all named types to the backend representation. Since named
4639 // types can refer to other types, this needs to be done in the right
4640 // sequence, which is handled by Named_type::convert. Here we arrange
4641 // to call that for each named type.
4644 Gogo::convert_named_types()
4646 this->convert_named_types_in_bindings(this->globals_
);
4647 for (Packages::iterator p
= this->packages_
.begin();
4648 p
!= this->packages_
.end();
4651 Package
* package
= p
->second
;
4652 this->convert_named_types_in_bindings(package
->bindings());
4655 Convert_named_types
cnt(this);
4656 this->traverse(&cnt
);
4658 // Make all the builtin named types used for type descriptors, and
4659 // then convert them. They will only be written out if they are
4661 Type::make_type_descriptor_type();
4662 Type::make_type_descriptor_ptr_type();
4663 Function_type::make_function_type_descriptor_type();
4664 Pointer_type::make_pointer_type_descriptor_type();
4665 Struct_type::make_struct_type_descriptor_type();
4666 Array_type::make_array_type_descriptor_type();
4667 Array_type::make_slice_type_descriptor_type();
4668 Map_type::make_map_type_descriptor_type();
4669 Channel_type::make_chan_type_descriptor_type();
4670 Interface_type::make_interface_type_descriptor_type();
4671 Expression::make_func_descriptor_type();
4672 Type::convert_builtin_named_types(this);
4674 Runtime::convert_types(this);
4676 this->named_types_are_converted_
= true;
4679 // Convert all names types in a set of bindings.
4682 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
4684 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
4685 p
!= bindings
->end_definitions();
4688 if ((*p
)->is_type())
4689 (*p
)->type_value()->convert(this);
4695 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
4697 : type_(type
), enclosing_(enclosing
), results_(NULL
),
4698 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
4699 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
4700 pragmas_(0), is_sink_(false), results_are_named_(false),
4701 is_unnamed_type_stub_method_(false), calls_recover_(false),
4702 is_recover_thunk_(false), has_recover_thunk_(false),
4703 calls_defer_retaddr_(false), is_type_specific_function_(false),
4704 in_unique_section_(false)
4708 // Create the named result variables.
4711 Function::create_result_variables(Gogo
* gogo
)
4713 const Typed_identifier_list
* results
= this->type_
->results();
4714 if (results
== NULL
|| results
->empty())
4717 if (!results
->front().name().empty())
4718 this->results_are_named_
= true;
4720 this->results_
= new Results();
4721 this->results_
->reserve(results
->size());
4723 Block
* block
= this->block_
;
4725 for (Typed_identifier_list::const_iterator p
= results
->begin();
4726 p
!= results
->end();
4729 std::string name
= p
->name();
4730 if (name
.empty() || Gogo::is_sink_name(name
))
4732 static int result_counter
;
4734 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
4736 name
= gogo
->pack_hidden_name(buf
, false);
4738 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
4740 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
4741 if (no
->is_result_variable())
4742 this->results_
->push_back(no
);
4745 static int dummy_result_count
;
4747 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
4748 ++dummy_result_count
;
4749 name
= gogo
->pack_hidden_name(buf
, false);
4750 no
= block
->bindings()->add_result_variable(name
, result
);
4751 go_assert(no
->is_result_variable());
4752 this->results_
->push_back(no
);
4757 // Update the named result variables when cloning a function which
4761 Function::update_result_variables()
4763 if (this->results_
== NULL
)
4766 for (Results::iterator p
= this->results_
->begin();
4767 p
!= this->results_
->end();
4769 (*p
)->result_var_value()->set_function(this);
4772 // Whether this method should not be included in the type descriptor.
4775 Function::nointerface() const
4777 go_assert(this->is_method());
4778 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
4781 // Record that this method should not be included in the type
4785 Function::set_nointerface()
4787 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
4790 // Return the closure variable, creating it if necessary.
4793 Function::closure_var()
4795 if (this->closure_var_
== NULL
)
4797 go_assert(this->descriptor_
== NULL
);
4798 // We don't know the type of the variable yet. We add fields as
4800 Location loc
= this->type_
->location();
4801 Struct_field_list
* sfl
= new Struct_field_list
;
4802 Type
* struct_type
= Type::make_struct_type(sfl
, loc
);
4803 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
4804 NULL
, false, false, false, loc
);
4806 var
->set_is_closure();
4807 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
4808 // Note that the new variable is not in any binding contour.
4810 return this->closure_var_
;
4813 // Set the type of the closure variable.
4816 Function::set_closure_type()
4818 if (this->closure_var_
== NULL
)
4820 Named_object
* closure
= this->closure_var_
;
4821 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
4823 // The first field of a closure is always a pointer to the function
4825 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
4826 st
->push_field(Struct_field(Typed_identifier(".$f", voidptr_type
,
4829 unsigned int index
= 1;
4830 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
4831 p
!= this->closure_fields_
.end();
4834 Named_object
* no
= p
->first
;
4836 snprintf(buf
, sizeof buf
, "%u", index
);
4837 std::string n
= no
->name() + buf
;
4839 if (no
->is_variable())
4840 var_type
= no
->var_value()->type();
4842 var_type
= no
->result_var_value()->type();
4843 Type
* field_type
= Type::make_pointer_type(var_type
);
4844 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
4848 // Return whether this function is a method.
4851 Function::is_method() const
4853 return this->type_
->is_method();
4856 // Add a label definition.
4859 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
4862 Label
* lnull
= NULL
;
4863 std::pair
<Labels::iterator
, bool> ins
=
4864 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4866 if (label_name
== "_")
4868 label
= Label::create_dummy_label();
4870 ins
.first
->second
= label
;
4872 else if (ins
.second
)
4874 // This is a new label.
4875 label
= new Label(label_name
);
4876 ins
.first
->second
= label
;
4880 // The label was already in the hash table.
4881 label
= ins
.first
->second
;
4882 if (label
->is_defined())
4884 go_error_at(location
, "label %qs already defined",
4885 Gogo::message_name(label_name
).c_str());
4886 go_inform(label
->location(), "previous definition of %qs was here",
4887 Gogo::message_name(label_name
).c_str());
4888 return new Label(label_name
);
4892 label
->define(location
, gogo
->bindings_snapshot(location
));
4894 // Issue any errors appropriate for any previous goto's to this
4896 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
4897 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
4900 (*p
)->check_goto_to(gogo
->current_block());
4901 label
->clear_refs();
4906 // Add a reference to a label.
4909 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
4910 Location location
, bool issue_goto_errors
)
4912 Label
* lnull
= NULL
;
4913 std::pair
<Labels::iterator
, bool> ins
=
4914 this->labels_
.insert(std::make_pair(label_name
, lnull
));
4918 // The label was already in the hash table.
4919 label
= ins
.first
->second
;
4923 go_assert(ins
.first
->second
== NULL
);
4924 label
= new Label(label_name
);
4925 ins
.first
->second
= label
;
4928 label
->set_is_used();
4930 if (issue_goto_errors
)
4932 Bindings_snapshot
* snapshot
= label
->snapshot();
4933 if (snapshot
!= NULL
)
4934 snapshot
->check_goto_from(gogo
->current_block(), location
);
4936 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
4942 // Warn about labels that are defined but not used.
4945 Function::check_labels() const
4947 for (Labels::const_iterator p
= this->labels_
.begin();
4948 p
!= this->labels_
.end();
4951 Label
* label
= p
->second
;
4952 if (!label
->is_used())
4953 go_error_at(label
->location(), "label %qs defined and not used",
4954 Gogo::message_name(label
->name()).c_str());
4958 // Swap one function with another. This is used when building the
4959 // thunk we use to call a function which calls recover. It may not
4960 // work for any other case.
4963 Function::swap_for_recover(Function
*x
)
4965 go_assert(this->enclosing_
== x
->enclosing_
);
4966 std::swap(this->results_
, x
->results_
);
4967 std::swap(this->closure_var_
, x
->closure_var_
);
4968 std::swap(this->block_
, x
->block_
);
4969 go_assert(this->location_
== x
->location_
);
4970 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
4971 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
4974 // Traverse the tree.
4977 Function::traverse(Traverse
* traverse
)
4979 unsigned int traverse_mask
= traverse
->traverse_mask();
4982 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
4985 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
4986 return TRAVERSE_EXIT
;
4989 // FIXME: We should check traverse_functions here if nested
4990 // functions are stored in block bindings.
4991 if (this->block_
!= NULL
4993 & (Traverse::traverse_variables
4994 | Traverse::traverse_constants
4995 | Traverse::traverse_blocks
4996 | Traverse::traverse_statements
4997 | Traverse::traverse_expressions
4998 | Traverse::traverse_types
)) != 0)
5000 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5001 return TRAVERSE_EXIT
;
5004 return TRAVERSE_CONTINUE
;
5007 // Work out types for unspecified variables and constants.
5010 Function::determine_types()
5012 if (this->block_
!= NULL
)
5013 this->block_
->determine_types();
5016 // Return the function descriptor, the value you get when you refer to
5017 // the function in Go code without calling it.
5020 Function::descriptor(Gogo
*, Named_object
* no
)
5022 go_assert(!this->is_method());
5023 go_assert(this->closure_var_
== NULL
);
5024 if (this->descriptor_
== NULL
)
5025 this->descriptor_
= Expression::make_func_descriptor(no
);
5026 return this->descriptor_
;
5029 // Get a pointer to the variable representing the defer stack for this
5030 // function, making it if necessary. The value of the variable is set
5031 // by the runtime routines to true if the function is returning,
5032 // rather than panicing through. A pointer to this variable is used
5033 // as a marker for the functions on the defer stack associated with
5034 // this function. A function-specific variable permits inlining a
5035 // function which uses defer.
5038 Function::defer_stack(Location location
)
5040 if (this->defer_stack_
== NULL
)
5042 Type
* t
= Type::lookup_bool_type();
5043 Expression
* n
= Expression::make_boolean(false, location
);
5044 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5045 this->defer_stack_
->set_is_address_taken();
5047 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5049 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5052 // Export the function.
5055 Function::export_func(Export
* exp
, const std::string
& name
) const
5057 Function::export_func_with_type(exp
, name
, this->type_
);
5060 // Export a function with a type.
5063 Function::export_func_with_type(Export
* exp
, const std::string
& name
,
5064 const Function_type
* fntype
)
5066 exp
->write_c_string("func ");
5068 if (fntype
->is_method())
5070 exp
->write_c_string("(");
5071 const Typed_identifier
* receiver
= fntype
->receiver();
5072 exp
->write_name(receiver
->name());
5073 exp
->write_escape(receiver
->note());
5074 exp
->write_c_string(" ");
5075 exp
->write_type(receiver
->type());
5076 exp
->write_c_string(") ");
5079 exp
->write_string(name
);
5081 exp
->write_c_string(" (");
5082 const Typed_identifier_list
* parameters
= fntype
->parameters();
5083 if (parameters
!= NULL
)
5086 bool is_varargs
= fntype
->is_varargs();
5088 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5089 p
!= parameters
->end();
5095 exp
->write_c_string(", ");
5096 exp
->write_name(p
->name());
5097 exp
->write_escape(p
->note());
5098 exp
->write_c_string(" ");
5099 if (!is_varargs
|| p
+ 1 != parameters
->end())
5100 exp
->write_type(p
->type());
5103 exp
->write_c_string("...");
5104 exp
->write_type(p
->type()->array_type()->element_type());
5108 exp
->write_c_string(")");
5110 const Typed_identifier_list
* results
= fntype
->results();
5111 if (results
!= NULL
)
5113 if (results
->size() == 1 && results
->begin()->name().empty())
5115 exp
->write_c_string(" ");
5116 exp
->write_type(results
->begin()->type());
5120 exp
->write_c_string(" (");
5122 for (Typed_identifier_list::const_iterator p
= results
->begin();
5123 p
!= results
->end();
5129 exp
->write_c_string(", ");
5130 exp
->write_name(p
->name());
5131 exp
->write_escape(p
->note());
5132 exp
->write_c_string(" ");
5133 exp
->write_type(p
->type());
5135 exp
->write_c_string(")");
5138 exp
->write_c_string(";\n");
5141 // Import a function.
5144 Function::import_func(Import
* imp
, std::string
* pname
,
5145 Typed_identifier
** preceiver
,
5146 Typed_identifier_list
** pparameters
,
5147 Typed_identifier_list
** presults
,
5150 imp
->require_c_string("func ");
5153 if (imp
->peek_char() == '(')
5155 imp
->require_c_string("(");
5156 std::string name
= imp
->read_name();
5157 std::string escape_note
= imp
->read_escape();
5158 imp
->require_c_string(" ");
5159 Type
* rtype
= imp
->read_type();
5160 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
5161 (*preceiver
)->set_note(escape_note
);
5162 imp
->require_c_string(") ");
5165 *pname
= imp
->read_identifier();
5167 Typed_identifier_list
* parameters
;
5168 *is_varargs
= false;
5169 imp
->require_c_string(" (");
5170 if (imp
->peek_char() == ')')
5174 parameters
= new Typed_identifier_list();
5177 std::string name
= imp
->read_name();
5178 std::string escape_note
= imp
->read_escape();
5179 imp
->require_c_string(" ");
5181 if (imp
->match_c_string("..."))
5187 Type
* ptype
= imp
->read_type();
5189 ptype
= Type::make_array_type(ptype
, NULL
);
5190 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
5191 t
.set_note(escape_note
);
5192 parameters
->push_back(t
);
5193 if (imp
->peek_char() != ',')
5195 go_assert(!*is_varargs
);
5196 imp
->require_c_string(", ");
5199 imp
->require_c_string(")");
5200 *pparameters
= parameters
;
5202 Typed_identifier_list
* results
;
5203 if (imp
->peek_char() != ' ')
5207 results
= new Typed_identifier_list();
5208 imp
->require_c_string(" ");
5209 if (imp
->peek_char() != '(')
5211 Type
* rtype
= imp
->read_type();
5212 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
5216 imp
->require_c_string("(");
5219 std::string name
= imp
->read_name();
5220 std::string note
= imp
->read_escape();
5221 imp
->require_c_string(" ");
5222 Type
* rtype
= imp
->read_type();
5223 Typed_identifier t
= Typed_identifier(name
, rtype
,
5226 results
->push_back(t
);
5227 if (imp
->peek_char() != ',')
5229 imp
->require_c_string(", ");
5231 imp
->require_c_string(")");
5234 imp
->require_c_string(";\n");
5235 *presults
= results
;
5238 // Get the backend representation.
5241 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5243 if (this->fndecl_
== NULL
)
5245 std::string asm_name
;
5246 bool is_visible
= false;
5247 if (no
->package() != NULL
)
5249 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
5251 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
5252 && !this->type_
->is_method())
5254 else if (no
->name() == gogo
->get_init_fn_name())
5257 asm_name
= no
->name();
5259 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
5260 && gogo
->is_main_package())
5262 // Methods have to be public even if they are hidden because
5263 // they can be pulled into type descriptors when using
5264 // anonymous fields.
5265 else if (!Gogo::is_hidden_name(no
->name())
5266 || this->type_
->is_method())
5268 if (!this->is_unnamed_type_stub_method_
)
5270 std::string pkgpath
= gogo
->pkgpath_symbol();
5271 if (this->type_
->is_method()
5272 && Gogo::is_hidden_name(no
->name())
5273 && Gogo::hidden_name_pkgpath(no
->name()) != gogo
->pkgpath())
5275 // This is a method we created for an unexported
5276 // method of an imported embedded type. We need to
5277 // use the pkgpath of the imported package to avoid
5278 // a possible name collision. See bug478 for a test
5280 pkgpath
= Gogo::hidden_name_pkgpath(no
->name());
5281 pkgpath
= Gogo::pkgpath_for_symbol(pkgpath
);
5285 asm_name
.append(1, '.');
5286 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5287 if (this->type_
->is_method())
5289 asm_name
.append(1, '.');
5290 Type
* rtype
= this->type_
->receiver()->type();
5291 asm_name
.append(rtype
->mangled_name(gogo
));
5295 if (!this->asm_name_
.empty())
5297 asm_name
= this->asm_name_
;
5301 // If a function calls the predeclared recover function, we
5302 // can't inline it, because recover behaves differently in a
5303 // function passed directly to defer. If this is a recover
5304 // thunk that we built to test whether a function can be
5305 // recovered, we can't inline it, because that will mess up
5306 // our return address comparison.
5307 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
5309 // If a function calls __go_set_defer_retaddr, then mark it as
5310 // uninlinable. This prevents the GCC backend from splitting
5311 // the function; splitting the function is a bad idea because we
5312 // want the return address label to be in the same function as
5314 if (this->calls_defer_retaddr_
)
5315 is_inlinable
= false;
5317 // Check the //go:noinline compiler directive.
5318 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
5319 is_inlinable
= false;
5321 // If this is a thunk created to call a function which calls
5322 // the predeclared recover function, we need to disable
5323 // stack splitting for the thunk.
5324 bool disable_split_stack
= this->is_recover_thunk_
;
5326 // Check the //go:nosplit compiler directive.
5327 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
5328 disable_split_stack
= true;
5330 // Encode name if asm_name not already set at this point
5331 if (asm_name
.empty() && go_id_needs_encoding(no
->get_id(gogo
)))
5332 asm_name
= go_encode_id(no
->get_id(gogo
));
5334 // This should go into a unique section if that has been
5335 // requested elsewhere, or if this is a nointerface function.
5336 // We want to put a nointerface function into a unique section
5337 // because there is a good chance that the linker garbage
5338 // collection can discard it.
5339 bool in_unique_section
= (this->in_unique_section_
5340 || (this->is_method() && this->nointerface()));
5342 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
5344 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5345 is_visible
, false, is_inlinable
,
5346 disable_split_stack
, in_unique_section
,
5349 return this->fndecl_
;
5352 // Get the backend representation.
5355 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
5357 if (this->fndecl_
== NULL
)
5359 // Let Go code use an asm declaration to pick up a builtin
5361 if (!this->asm_name_
.empty())
5363 Bfunction
* builtin_decl
=
5364 gogo
->backend()->lookup_builtin(this->asm_name_
);
5365 if (builtin_decl
!= NULL
)
5367 this->fndecl_
= builtin_decl
;
5368 return this->fndecl_
;
5372 std::string asm_name
;
5373 if (this->asm_name_
.empty())
5375 asm_name
= (no
->package() == NULL
5376 ? gogo
->pkgpath_symbol()
5377 : no
->package()->pkgpath_symbol());
5378 asm_name
.append(1, '.');
5379 asm_name
.append(Gogo::unpack_hidden_name(no
->name()));
5380 if (this->fntype_
->is_method())
5382 asm_name
.append(1, '.');
5383 Type
* rtype
= this->fntype_
->receiver()->type();
5384 asm_name
.append(rtype
->mangled_name(gogo
));
5387 else if (go_id_needs_encoding(no
->get_id(gogo
)))
5388 asm_name
= go_encode_id(no
->get_id(gogo
));
5390 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
5392 gogo
->backend()->function(functype
, no
->get_id(gogo
), asm_name
,
5393 true, true, true, false, false,
5397 return this->fndecl_
;
5400 // Build the descriptor for a function declaration. This won't
5401 // necessarily happen if the package has just a declaration for the
5402 // function and no other reference to it, but we may still need the
5403 // descriptor for references from other packages.
5405 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
5407 if (this->descriptor_
!= NULL
)
5409 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5410 this->descriptor_
->get_backend(&context
);
5414 // Check that the types used in this declaration's signature are defined.
5415 // Reports errors for any undefined type.
5418 Function_declaration::check_types() const
5420 // Calling Type::base will give errors for any undefined types.
5421 Function_type
* fntype
= this->type();
5422 if (fntype
->receiver() != NULL
)
5423 fntype
->receiver()->type()->base();
5424 if (fntype
->parameters() != NULL
)
5426 const Typed_identifier_list
* params
= fntype
->parameters();
5427 for (Typed_identifier_list::const_iterator p
= params
->begin();
5434 // Return the function's decl after it has been built.
5437 Function::get_decl() const
5439 go_assert(this->fndecl_
!= NULL
);
5440 return this->fndecl_
;
5443 // Build the backend representation for the function code.
5446 Function::build(Gogo
* gogo
, Named_object
* named_function
)
5448 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5450 // A list of parameter variables for this function.
5451 std::vector
<Bvariable
*> param_vars
;
5453 // Variables that need to be declared for this function and their
5455 std::vector
<Bvariable
*> vars
;
5456 std::vector
<Bexpression
*> var_inits
;
5457 for (Bindings::const_definitions_iterator p
=
5458 this->block_
->bindings()->begin_definitions();
5459 p
!= this->block_
->bindings()->end_definitions();
5462 Location loc
= (*p
)->location();
5463 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
5465 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5466 Bvariable
* parm_bvar
= bvar
;
5468 // We always pass the receiver to a method as a pointer. If
5469 // the receiver is declared as a non-pointer type, then we
5470 // copy the value into a local variable.
5471 if ((*p
)->var_value()->is_receiver()
5472 && (*p
)->var_value()->type()->points_to() == NULL
)
5474 std::string name
= (*p
)->name() + ".pointer";
5475 Type
* var_type
= (*p
)->var_value()->type();
5476 Variable
* parm_var
=
5477 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
5479 Named_object
* parm_no
=
5480 Named_object::make_variable(name
, NULL
, parm_var
);
5481 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5483 vars
.push_back(bvar
);
5484 Expression
* parm_ref
=
5485 Expression::make_var_reference(parm_no
, loc
);
5486 parm_ref
= Expression::make_unary(OPERATOR_MULT
, parm_ref
, loc
);
5487 if ((*p
)->var_value()->is_in_heap())
5488 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
5489 var_inits
.push_back(parm_ref
->get_backend(&context
));
5491 else if ((*p
)->var_value()->is_in_heap())
5493 // If we take the address of a parameter, then we need
5494 // to copy it into the heap.
5495 std::string parm_name
= (*p
)->name() + ".param";
5496 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
5497 false, true, false, loc
);
5498 Named_object
* parm_no
=
5499 Named_object::make_variable(parm_name
, NULL
, parm_var
);
5500 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
5502 vars
.push_back(bvar
);
5503 Expression
* var_ref
=
5504 Expression::make_var_reference(parm_no
, loc
);
5505 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
5506 var_inits
.push_back(var_ref
->get_backend(&context
));
5508 param_vars
.push_back(parm_bvar
);
5510 else if ((*p
)->is_result_variable())
5512 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
5514 Type
* type
= (*p
)->result_var_value()->type();
5516 if (!(*p
)->result_var_value()->is_in_heap())
5518 Btype
* btype
= type
->get_backend(gogo
);
5519 init
= gogo
->backend()->zero_expression(btype
);
5522 init
= Expression::make_allocation(type
,
5523 loc
)->get_backend(&context
);
5525 vars
.push_back(bvar
);
5526 var_inits
.push_back(init
);
5529 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
5531 go_assert(saw_errors());
5535 // If we need a closure variable, make sure to create it.
5536 // It gets installed in the function as a side effect of creation.
5537 if (this->closure_var_
!= NULL
)
5539 go_assert(this->closure_var_
->var_value()->is_closure());
5540 this->closure_var_
->get_backend_variable(gogo
, named_function
);
5543 if (this->block_
!= NULL
)
5545 // Declare variables if necessary.
5546 Bblock
* var_decls
= NULL
;
5548 Bstatement
* defer_init
= NULL
;
5549 if (!vars
.empty() || this->defer_stack_
!= NULL
)
5552 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
5553 this->block_
->start_location(),
5554 this->block_
->end_location());
5556 if (this->defer_stack_
!= NULL
)
5558 Translate_context
dcontext(gogo
, named_function
, this->block_
,
5560 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
5564 // Build the backend representation for all the statements in the
5566 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5567 Bblock
* code_block
= this->block_
->get_backend(&context
);
5569 // Initialize variables if necessary.
5570 std::vector
<Bstatement
*> init
;
5571 go_assert(vars
.size() == var_inits
.size());
5572 for (size_t i
= 0; i
< vars
.size(); ++i
)
5574 Bstatement
* init_stmt
=
5575 gogo
->backend()->init_statement(vars
[i
], var_inits
[i
]);
5576 init
.push_back(init_stmt
);
5578 if (defer_init
!= NULL
)
5579 init
.push_back(defer_init
);
5580 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
5582 // Initialize all variables before executing this code block.
5583 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
5584 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
5586 // If we have a defer stack, initialize it at the start of a
5588 Bstatement
* except
= NULL
;
5589 Bstatement
* fini
= NULL
;
5590 if (defer_init
!= NULL
)
5592 // Clean up the defer stack when we leave the function.
5593 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
5595 // Wrap the code for this function in an exception handler to handle
5598 gogo
->backend()->exception_handler_statement(code_stmt
,
5603 // Stick the code into the block we built for the receiver, if
5605 if (var_decls
!= NULL
)
5607 std::vector
<Bstatement
*> code_stmt_list(1, code_stmt
);
5608 gogo
->backend()->block_add_statements(var_decls
, code_stmt_list
);
5609 code_stmt
= gogo
->backend()->block_statement(var_decls
);
5612 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
5614 go_assert(saw_errors());
5619 // If we created a descriptor for the function, make sure we emit it.
5620 if (this->descriptor_
!= NULL
)
5622 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
5623 this->descriptor_
->get_backend(&context
);
5627 // Build the wrappers around function code needed if the function has
5628 // any defer statements. This sets *EXCEPT to an exception handler
5629 // and *FINI to a finally handler.
5632 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
5633 Bstatement
** except
, Bstatement
** fini
)
5635 Location end_loc
= this->block_
->end_location();
5637 // Add an exception handler. This is used if a panic occurs. Its
5638 // purpose is to stop the stack unwinding if a deferred function
5639 // calls recover. There are more details in
5640 // libgo/runtime/go-unwind.c.
5642 std::vector
<Bstatement
*> stmts
;
5643 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
5644 this->defer_stack(end_loc
));
5645 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
5646 Bexpression
* defer
= call
->get_backend(&context
);
5647 stmts
.push_back(gogo
->backend()->expression_statement(defer
));
5649 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5650 if (ret_bstmt
!= NULL
)
5651 stmts
.push_back(ret_bstmt
);
5653 go_assert(*except
== NULL
);
5654 *except
= gogo
->backend()->statement_list(stmts
);
5656 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
5657 this->defer_stack(end_loc
));
5658 defer
= call
->get_backend(&context
);
5660 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
5661 this->defer_stack(end_loc
));
5662 Bexpression
* undefer
= call
->get_backend(&context
);
5663 Bstatement
* function_defer
=
5664 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
5666 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
5667 if (this->type_
->results() != NULL
5668 && !this->type_
->results()->empty()
5669 && !this->type_
->results()->front().name().empty())
5671 // If the result variables are named, and we are returning from
5672 // this function rather than panicing through it, we need to
5673 // return them again, because they might have been changed by a
5674 // defer function. The runtime routines set the defer_stack
5675 // variable to true if we are returning from this function.
5677 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
5678 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
5680 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
5682 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
5683 Bexpression
* bref
= ref
->get_backend(&context
);
5684 ret
= gogo
->backend()->conditional_expression(NULL
, bref
, ret
, NULL
,
5686 stmts
.push_back(gogo
->backend()->expression_statement(ret
));
5689 go_assert(*fini
== NULL
);
5690 *fini
= gogo
->backend()->statement_list(stmts
);
5693 // Return the statement that assigns values to this function's result struct.
5696 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
5697 Location location
) const
5699 const Typed_identifier_list
* results
= this->type_
->results();
5700 if (results
== NULL
|| results
->empty())
5703 go_assert(this->results_
!= NULL
);
5704 if (this->results_
->size() != results
->size())
5706 go_assert(saw_errors());
5707 return gogo
->backend()->error_statement();
5710 std::vector
<Bexpression
*> vals(results
->size());
5711 for (size_t i
= 0; i
< vals
.size(); ++i
)
5713 Named_object
* no
= (*this->results_
)[i
];
5714 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
5715 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
5716 if (no
->result_var_value()->is_in_heap())
5718 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
5719 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
5723 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
5728 Block::Block(Block
* enclosing
, Location location
)
5729 : enclosing_(enclosing
), statements_(),
5730 bindings_(new Bindings(enclosing
== NULL
5732 : enclosing
->bindings())),
5733 start_location_(location
),
5734 end_location_(Linemap::unknown_location())
5738 // Add a statement to a block.
5741 Block::add_statement(Statement
* statement
)
5743 this->statements_
.push_back(statement
);
5746 // Add a statement to the front of a block. This is slow but is only
5747 // used for reference counts of parameters.
5750 Block::add_statement_at_front(Statement
* statement
)
5752 this->statements_
.insert(this->statements_
.begin(), statement
);
5755 // Replace a statement in a block.
5758 Block::replace_statement(size_t index
, Statement
* s
)
5760 go_assert(index
< this->statements_
.size());
5761 this->statements_
[index
] = s
;
5764 // Add a statement before another statement.
5767 Block::insert_statement_before(size_t index
, Statement
* s
)
5769 go_assert(index
< this->statements_
.size());
5770 this->statements_
.insert(this->statements_
.begin() + index
, s
);
5773 // Add a statement after another statement.
5776 Block::insert_statement_after(size_t index
, Statement
* s
)
5778 go_assert(index
< this->statements_
.size());
5779 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
5782 // Traverse the tree.
5785 Block::traverse(Traverse
* traverse
)
5787 unsigned int traverse_mask
= traverse
->traverse_mask();
5789 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
5791 int t
= traverse
->block(this);
5792 if (t
== TRAVERSE_EXIT
)
5793 return TRAVERSE_EXIT
;
5794 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
5795 return TRAVERSE_CONTINUE
;
5799 & (Traverse::traverse_variables
5800 | Traverse::traverse_constants
5801 | Traverse::traverse_expressions
5802 | Traverse::traverse_types
)) != 0)
5804 const unsigned int e_or_t
= (Traverse::traverse_expressions
5805 | Traverse::traverse_types
);
5806 const unsigned int e_or_t_or_s
= (e_or_t
5807 | Traverse::traverse_statements
);
5808 for (Bindings::const_definitions_iterator pb
=
5809 this->bindings_
->begin_definitions();
5810 pb
!= this->bindings_
->end_definitions();
5813 int t
= TRAVERSE_CONTINUE
;
5814 switch ((*pb
)->classification())
5816 case Named_object::NAMED_OBJECT_CONST
:
5817 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
5818 t
= traverse
->constant(*pb
, false);
5819 if (t
== TRAVERSE_CONTINUE
5820 && (traverse_mask
& e_or_t
) != 0)
5822 Type
* tc
= (*pb
)->const_value()->type();
5824 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
5825 return TRAVERSE_EXIT
;
5826 t
= (*pb
)->const_value()->traverse_expression(traverse
);
5830 case Named_object::NAMED_OBJECT_VAR
:
5831 case Named_object::NAMED_OBJECT_RESULT_VAR
:
5832 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
5833 t
= traverse
->variable(*pb
);
5834 if (t
== TRAVERSE_CONTINUE
5835 && (traverse_mask
& e_or_t
) != 0)
5837 if ((*pb
)->is_result_variable()
5838 || (*pb
)->var_value()->has_type())
5840 Type
* tv
= ((*pb
)->is_variable()
5841 ? (*pb
)->var_value()->type()
5842 : (*pb
)->result_var_value()->type());
5844 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
5845 return TRAVERSE_EXIT
;
5848 if (t
== TRAVERSE_CONTINUE
5849 && (traverse_mask
& e_or_t_or_s
) != 0
5850 && (*pb
)->is_variable())
5851 t
= (*pb
)->var_value()->traverse_expression(traverse
,
5855 case Named_object::NAMED_OBJECT_FUNC
:
5856 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
5859 case Named_object::NAMED_OBJECT_TYPE
:
5860 if ((traverse_mask
& e_or_t
) != 0)
5861 t
= Type::traverse((*pb
)->type_value(), traverse
);
5864 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
5865 case Named_object::NAMED_OBJECT_UNKNOWN
:
5866 case Named_object::NAMED_OBJECT_ERRONEOUS
:
5869 case Named_object::NAMED_OBJECT_PACKAGE
:
5870 case Named_object::NAMED_OBJECT_SINK
:
5877 if (t
== TRAVERSE_EXIT
)
5878 return TRAVERSE_EXIT
;
5882 // No point in checking traverse_mask here--if we got here we always
5883 // want to walk the statements. The traversal can insert new
5884 // statements before or after the current statement. Inserting
5885 // statements before the current statement requires updating I via
5886 // the pointer; those statements will not be traversed. Any new
5887 // statements inserted after the current statement will be traversed
5889 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
5891 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
5892 return TRAVERSE_EXIT
;
5895 return TRAVERSE_CONTINUE
;
5898 // Work out types for unspecified variables and constants.
5901 Block::determine_types()
5903 for (Bindings::const_definitions_iterator pb
=
5904 this->bindings_
->begin_definitions();
5905 pb
!= this->bindings_
->end_definitions();
5908 if ((*pb
)->is_variable())
5909 (*pb
)->var_value()->determine_type();
5910 else if ((*pb
)->is_const())
5911 (*pb
)->const_value()->determine_type();
5914 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
5915 ps
!= this->statements_
.end();
5917 (*ps
)->determine_types();
5920 // Return true if the statements in this block may fall through.
5923 Block::may_fall_through() const
5925 if (this->statements_
.empty())
5927 return this->statements_
.back()->may_fall_through();
5930 // Convert a block to the backend representation.
5933 Block::get_backend(Translate_context
* context
)
5935 Gogo
* gogo
= context
->gogo();
5936 Named_object
* function
= context
->function();
5937 std::vector
<Bvariable
*> vars
;
5938 vars
.reserve(this->bindings_
->size_definitions());
5939 for (Bindings::const_definitions_iterator pv
=
5940 this->bindings_
->begin_definitions();
5941 pv
!= this->bindings_
->end_definitions();
5944 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
5945 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
5948 go_assert(function
!= NULL
);
5949 Bfunction
* bfunction
=
5950 function
->func_value()->get_or_make_decl(gogo
, function
);
5951 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
5952 vars
, this->start_location_
,
5953 this->end_location_
);
5955 Translate_context
subcontext(gogo
, function
, this, ret
);
5956 std::vector
<Bstatement
*> bstatements
;
5957 bstatements
.reserve(this->statements_
.size());
5958 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
5959 p
!= this->statements_
.end();
5961 bstatements
.push_back((*p
)->get_backend(&subcontext
));
5963 context
->backend()->block_add_statements(ret
, bstatements
);
5968 // Class Bindings_snapshot.
5970 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
5971 : block_(b
), counts_(), location_(location
)
5975 this->counts_
.push_back(b
->bindings()->size_definitions());
5980 // Report errors appropriate for a goto from B to this.
5983 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
5986 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
5988 this->check_goto_defs(loc
, this->block_
,
5989 this->block_
->bindings()->size_definitions(),
5993 // Report errors appropriate for a goto from this to B.
5996 Bindings_snapshot::check_goto_to(const Block
* b
)
5999 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
6001 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
6002 b
->bindings()->size_definitions());
6005 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6006 // Return true if all is well, false if we reported an error. If this
6007 // returns true, it sets *PINDEX to the number of blocks BTO is above
6011 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
6012 const Block
* bto
, size_t* pindex
)
6014 // It is an error if BTO is not either BFROM or above BFROM.
6016 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
6020 go_error_at(loc
, "goto jumps into block");
6021 go_inform(bto
->start_location(), "goto target block starts here");
6029 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6030 // CFROM is the number of names defined at the point of the goto and
6031 // CTO is the number of names defined at the point of the label.
6034 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
6035 size_t cfrom
, size_t cto
)
6039 Bindings::const_definitions_iterator p
=
6040 block
->bindings()->begin_definitions();
6041 for (size_t i
= 0; i
< cfrom
; ++i
)
6043 go_assert(p
!= block
->bindings()->end_definitions());
6046 go_assert(p
!= block
->bindings()->end_definitions());
6048 std::string n
= (*p
)->message_name();
6049 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
6050 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
6054 // Class Function_declaration.
6056 // Return the function descriptor.
6059 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
6061 go_assert(!this->fntype_
->is_method());
6062 if (this->descriptor_
== NULL
)
6063 this->descriptor_
= Expression::make_func_descriptor(no
);
6064 return this->descriptor_
;
6069 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
6070 bool is_parameter
, bool is_receiver
,
6072 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
6073 backend_(NULL
), is_global_(is_global
), is_parameter_(is_parameter
),
6074 is_closure_(false), is_receiver_(is_receiver
),
6075 is_varargs_parameter_(false), is_used_(false),
6076 is_address_taken_(false), is_non_escaping_address_taken_(false),
6077 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6078 type_from_init_tuple_(false), type_from_range_index_(false),
6079 type_from_range_value_(false), type_from_chan_element_(false),
6080 is_type_switch_var_(false), determined_type_(false),
6081 in_unique_section_(false), escapes_(true)
6083 go_assert(type
!= NULL
|| init
!= NULL
);
6084 go_assert(!is_parameter
|| init
== NULL
);
6087 // Traverse the initializer expression.
6090 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
6092 if (this->preinit_
!= NULL
)
6094 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
6095 return TRAVERSE_EXIT
;
6097 if (this->init_
!= NULL
6099 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
6102 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
6103 return TRAVERSE_EXIT
;
6105 return TRAVERSE_CONTINUE
;
6108 // Lower the initialization expression after parsing is complete.
6111 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
6112 Statement_inserter
* inserter
)
6114 Named_object
* dep
= gogo
->var_depends_on(this);
6115 if (dep
!= NULL
&& dep
->is_variable())
6116 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
6118 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
6122 // We will give an error elsewhere, this is just to prevent
6123 // an infinite loop.
6128 Statement_inserter global_inserter
;
6129 if (this->is_global_
)
6131 global_inserter
= Statement_inserter(gogo
, this);
6132 inserter
= &global_inserter
;
6135 gogo
->lower_expression(function
, inserter
, &this->init_
);
6137 this->seen_
= false;
6139 this->init_is_lowered_
= true;
6143 // Flatten the initialization expression after ordering evaluations.
6146 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
6147 Statement_inserter
* inserter
)
6149 Named_object
* dep
= gogo
->var_depends_on(this);
6150 if (dep
!= NULL
&& dep
->is_variable())
6151 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
6153 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
6157 // We will give an error elsewhere, this is just to prevent
6158 // an infinite loop.
6163 Statement_inserter global_inserter
;
6164 if (this->is_global_
)
6166 global_inserter
= Statement_inserter(gogo
, this);
6167 inserter
= &global_inserter
;
6170 gogo
->flatten_expression(function
, inserter
, &this->init_
);
6172 // If an interface conversion is needed, we need a temporary
6174 if (this->type_
!= NULL
6175 && !Type::are_identical(this->type_
, this->init_
->type(), false,
6177 && this->init_
->type()->interface_type() != NULL
6178 && !this->init_
->is_variable())
6180 Temporary_statement
* temp
=
6181 Statement::make_temporary(NULL
, this->init_
, this->location_
);
6182 inserter
->insert(temp
);
6183 this->init_
= Expression::make_temporary_reference(temp
,
6187 this->seen_
= false;
6188 this->init_is_flattened_
= true;
6192 // Get the preinit block.
6195 Variable::preinit_block(Gogo
* gogo
)
6197 go_assert(this->is_global_
);
6198 if (this->preinit_
== NULL
)
6199 this->preinit_
= new Block(NULL
, this->location());
6201 // If a global variable has a preinitialization statement, then we
6202 // need to have an initialization function.
6203 gogo
->set_need_init_fn();
6205 return this->preinit_
;
6208 // Add a statement to be run before the initialization expression.
6211 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
6213 Block
* b
= this->preinit_block(gogo
);
6214 b
->add_statement(s
);
6215 b
->set_end_location(s
->location());
6218 // Whether this variable has a type.
6221 Variable::has_type() const
6223 if (this->type_
== NULL
)
6226 // A variable created in a type switch case nil does not actually
6227 // have a type yet. It will be changed to use the initializer's
6228 // type in determine_type.
6229 if (this->is_type_switch_var_
6230 && this->type_
->is_nil_constant_as_type())
6236 // In an assignment which sets a variable to a tuple of EXPR, return
6237 // the type of the first element of the tuple.
6240 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
6242 if (expr
->map_index_expression() != NULL
)
6244 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
6246 return Type::make_error_type();
6247 return mt
->val_type();
6249 else if (expr
->receive_expression() != NULL
)
6251 Expression
* channel
= expr
->receive_expression()->channel();
6252 Type
* channel_type
= channel
->type();
6253 if (channel_type
->channel_type() == NULL
)
6254 return Type::make_error_type();
6255 return channel_type
->channel_type()->element_type();
6260 go_error_at(this->location(), "invalid tuple definition");
6261 return Type::make_error_type();
6265 // Given EXPR used in a range clause, return either the index type or
6266 // the value type of the range, depending upon GET_INDEX_TYPE.
6269 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
6270 bool report_error
) const
6272 Type
* t
= expr
->type();
6273 if (t
->array_type() != NULL
6274 || (t
->points_to() != NULL
6275 && t
->points_to()->array_type() != NULL
6276 && !t
->points_to()->is_slice_type()))
6279 return Type::lookup_integer_type("int");
6281 return t
->deref()->array_type()->element_type();
6283 else if (t
->is_string_type())
6286 return Type::lookup_integer_type("int");
6288 return Type::lookup_integer_type("int32");
6290 else if (t
->map_type() != NULL
)
6293 return t
->map_type()->key_type();
6295 return t
->map_type()->val_type();
6297 else if (t
->channel_type() != NULL
)
6300 return t
->channel_type()->element_type();
6304 go_error_at(this->location(),
6305 ("invalid definition of value variable "
6306 "for channel range"));
6307 return Type::make_error_type();
6313 go_error_at(this->location(), "invalid type for range clause");
6314 return Type::make_error_type();
6318 // EXPR should be a channel. Return the channel's element type.
6321 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
6323 Type
* t
= expr
->type();
6324 if (t
->channel_type() != NULL
)
6325 return t
->channel_type()->element_type();
6329 go_error_at(this->location(), "expected channel");
6330 return Type::make_error_type();
6334 // Return the type of the Variable. This may be called before
6335 // Variable::determine_type is called, which means that we may need to
6336 // get the type from the initializer. FIXME: If we combine lowering
6337 // with type determination, then this should be unnecessary.
6342 // A variable in a type switch with a nil case will have the wrong
6343 // type here. This gets fixed up in determine_type, below.
6344 Type
* type
= this->type_
;
6345 Expression
* init
= this->init_
;
6346 if (this->is_type_switch_var_
6348 && this->type_
->is_nil_constant_as_type())
6350 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6351 go_assert(tge
!= NULL
);
6358 if (this->type_
== NULL
|| !this->type_
->is_error_type())
6360 go_error_at(this->location_
, "variable initializer refers to itself");
6361 this->type_
= Type::make_error_type();
6370 else if (this->type_from_init_tuple_
)
6371 type
= this->type_from_tuple(init
, false);
6372 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6373 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
6374 else if (this->type_from_chan_element_
)
6375 type
= this->type_from_chan_element(init
, false);
6378 go_assert(init
!= NULL
);
6379 type
= init
->type();
6380 go_assert(type
!= NULL
);
6382 // Variables should not have abstract types.
6383 if (type
->is_abstract())
6384 type
= type
->make_non_abstract_type();
6386 if (type
->is_void_type())
6387 type
= Type::make_error_type();
6390 this->seen_
= false;
6395 // Fetch the type from a const pointer, in which case it should have
6396 // been set already.
6399 Variable::type() const
6401 go_assert(this->type_
!= NULL
);
6405 // Set the type if necessary.
6408 Variable::determine_type()
6410 if (this->determined_type_
)
6412 this->determined_type_
= true;
6414 if (this->preinit_
!= NULL
)
6415 this->preinit_
->determine_types();
6417 // A variable in a type switch with a nil case will have the wrong
6418 // type here. It will have an initializer which is a type guard.
6419 // We want to initialize it to the value without the type guard, and
6420 // use the type of that value as well.
6421 if (this->is_type_switch_var_
6422 && this->type_
!= NULL
6423 && this->type_
->is_nil_constant_as_type())
6425 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
6426 go_assert(tge
!= NULL
);
6428 this->init_
= tge
->expr();
6431 if (this->init_
== NULL
)
6432 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
6433 else if (this->type_from_init_tuple_
)
6435 Expression
*init
= this->init_
;
6436 init
->determine_type_no_context();
6437 this->type_
= this->type_from_tuple(init
, true);
6440 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
6442 Expression
* init
= this->init_
;
6443 init
->determine_type_no_context();
6444 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
6448 else if (this->type_from_chan_element_
)
6450 Expression
* init
= this->init_
;
6451 init
->determine_type_no_context();
6452 this->type_
= this->type_from_chan_element(init
, true);
6457 Type_context
context(this->type_
, false);
6458 this->init_
->determine_type(&context
);
6459 if (this->type_
== NULL
)
6461 Type
* type
= this->init_
->type();
6462 go_assert(type
!= NULL
);
6463 if (type
->is_abstract())
6464 type
= type
->make_non_abstract_type();
6466 if (type
->is_void_type())
6468 go_error_at(this->location_
, "variable has no type");
6469 type
= Type::make_error_type();
6471 else if (type
->is_nil_type())
6473 go_error_at(this->location_
, "variable defined to nil type");
6474 type
= Type::make_error_type();
6476 else if (type
->is_call_multiple_result_type())
6478 go_error_at(this->location_
,
6479 "single variable set to multiple-value function call");
6480 type
= Type::make_error_type();
6488 // Get the initial value of a variable. This does not
6489 // consider whether the variable is in the heap--it returns the
6490 // initial value as though it were always stored in the stack.
6493 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
6495 go_assert(this->preinit_
== NULL
);
6496 Location loc
= this->location();
6497 if (this->init_
== NULL
)
6499 go_assert(!this->is_parameter_
);
6500 if (this->is_global_
|| this->is_in_heap())
6502 Btype
* btype
= this->type()->get_backend(gogo
);
6503 return gogo
->backend()->zero_expression(btype
);
6507 Translate_context
context(gogo
, function
, NULL
, NULL
);
6508 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
6509 return init
->get_backend(&context
);
6513 // Get the initial value of a variable when a block is required.
6514 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6517 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
6518 Bvariable
* var_decl
)
6520 go_assert(this->preinit_
!= NULL
);
6522 // We want to add the variable assignment to the end of the preinit
6525 Translate_context
context(gogo
, function
, NULL
, NULL
);
6526 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
6528 // It's possible to have pre-init statements without an initializer
6529 // if the pre-init statements set the variable.
6530 Bstatement
* decl_init
= NULL
;
6531 if (this->init_
!= NULL
)
6533 if (var_decl
== NULL
)
6535 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
6536 decl_init
= gogo
->backend()->expression_statement(init_bexpr
);
6540 Location loc
= this->location();
6541 Expression
* val_expr
=
6542 Expression::make_cast(this->type(), this->init_
, loc
);
6543 Bexpression
* val
= val_expr
->get_backend(&context
);
6544 Bexpression
* var_ref
= gogo
->backend()->var_expression(var_decl
, loc
);
6545 decl_init
= gogo
->backend()->assignment_statement(var_ref
, val
, loc
);
6548 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
6549 if (decl_init
!= NULL
)
6550 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
6554 // Export the variable
6557 Variable::export_var(Export
* exp
, const std::string
& name
) const
6559 go_assert(this->is_global_
);
6560 exp
->write_c_string("var ");
6561 exp
->write_string(name
);
6562 exp
->write_c_string(" ");
6563 exp
->write_type(this->type());
6564 exp
->write_c_string(";\n");
6567 // Import a variable.
6570 Variable::import_var(Import
* imp
, std::string
* pname
, Type
** ptype
)
6572 imp
->require_c_string("var ");
6573 *pname
= imp
->read_identifier();
6574 imp
->require_c_string(" ");
6575 *ptype
= imp
->read_type();
6576 imp
->require_c_string(";\n");
6579 // Convert a variable to the backend representation.
6582 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6583 const Package
* package
, const std::string
& name
)
6585 if (this->backend_
== NULL
)
6587 Backend
* backend
= gogo
->backend();
6588 Type
* type
= this->type_
;
6589 if (type
->is_error_type()
6590 || (type
->is_undefined()
6591 && (!this->is_global_
|| package
== NULL
)))
6592 this->backend_
= backend
->error_variable();
6595 bool is_parameter
= this->is_parameter_
;
6596 if (this->is_receiver_
&& type
->points_to() == NULL
)
6597 is_parameter
= false;
6598 if (this->is_in_heap())
6600 is_parameter
= false;
6601 type
= Type::make_pointer_type(type
);
6604 const std::string n
= Gogo::unpack_hidden_name(name
);
6605 Btype
* btype
= type
->get_backend(gogo
);
6608 if (Map_type::is_zero_value(this))
6609 bvar
= Map_type::backend_zero_value(gogo
);
6610 else if (this->is_global_
)
6612 std::string
var_name(package
!= NULL
6613 ? package
->package_name()
6614 : gogo
->package_name());
6615 var_name
.push_back('.');
6617 std::string asm_name
;
6618 if (Gogo::is_hidden_name(name
))
6619 asm_name
= var_name
;
6622 asm_name
= package
!= NULL
6623 ? package
->pkgpath_symbol()
6624 : gogo
->pkgpath_symbol();
6625 asm_name
.push_back('.');
6628 asm_name
= go_encode_id(asm_name
);
6629 bvar
= backend
->global_variable(var_name
,
6633 Gogo::is_hidden_name(name
),
6634 this->in_unique_section_
,
6637 else if (function
== NULL
)
6639 go_assert(saw_errors());
6640 bvar
= backend
->error_variable();
6644 Bfunction
* bfunction
= function
->func_value()->get_decl();
6645 bool is_address_taken
= (this->is_non_escaping_address_taken_
6646 && !this->is_in_heap());
6647 if (this->is_closure())
6648 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
6650 else if (is_parameter
)
6651 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
6655 bvar
= backend
->local_variable(bfunction
, n
, btype
,
6659 this->backend_
= bvar
;
6662 return this->backend_
;
6665 // Class Result_variable.
6667 // Convert a result variable to the backend representation.
6670 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
6671 const std::string
& name
)
6673 if (this->backend_
== NULL
)
6675 Backend
* backend
= gogo
->backend();
6676 Type
* type
= this->type_
;
6677 if (type
->is_error())
6678 this->backend_
= backend
->error_variable();
6681 if (this->is_in_heap())
6682 type
= Type::make_pointer_type(type
);
6683 Btype
* btype
= type
->get_backend(gogo
);
6684 Bfunction
* bfunction
= function
->func_value()->get_decl();
6685 std::string n
= Gogo::unpack_hidden_name(name
);
6686 bool is_address_taken
= (this->is_non_escaping_address_taken_
6687 && !this->is_in_heap());
6688 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
6693 return this->backend_
;
6696 // Class Named_constant.
6698 // Traverse the initializer expression.
6701 Named_constant::traverse_expression(Traverse
* traverse
)
6703 return Expression::traverse(&this->expr_
, traverse
);
6706 // Determine the type of the constant.
6709 Named_constant::determine_type()
6711 if (this->type_
!= NULL
)
6713 Type_context
context(this->type_
, false);
6714 this->expr_
->determine_type(&context
);
6718 // A constant may have an abstract type.
6719 Type_context
context(NULL
, true);
6720 this->expr_
->determine_type(&context
);
6721 this->type_
= this->expr_
->type();
6722 go_assert(this->type_
!= NULL
);
6726 // Indicate that we found and reported an error for this constant.
6729 Named_constant::set_error()
6731 this->type_
= Type::make_error_type();
6732 this->expr_
= Expression::make_error(this->location_
);
6735 // Export a constant.
6738 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
6740 exp
->write_c_string("const ");
6741 exp
->write_string(name
);
6742 exp
->write_c_string(" ");
6743 if (!this->type_
->is_abstract())
6745 exp
->write_type(this->type_
);
6746 exp
->write_c_string(" ");
6748 exp
->write_c_string("= ");
6749 this->expr()->export_expression(exp
);
6750 exp
->write_c_string(";\n");
6753 // Import a constant.
6756 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
6759 imp
->require_c_string("const ");
6760 *pname
= imp
->read_identifier();
6761 imp
->require_c_string(" ");
6762 if (imp
->peek_char() == '=')
6766 *ptype
= imp
->read_type();
6767 imp
->require_c_string(" ");
6769 imp
->require_c_string("= ");
6770 *pexpr
= Expression::import_expression(imp
);
6771 imp
->require_c_string(";\n");
6774 // Get the backend representation.
6777 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
6779 if (this->bconst_
== NULL
)
6781 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
6782 Type
* type
= this->type();
6783 Location loc
= this->location();
6785 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
6786 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
6787 if (type
!= NULL
&& type
->is_numeric_type())
6789 Btype
* btype
= type
->get_backend(gogo
);
6790 std::string name
= const_no
->get_id(gogo
);
6792 gogo
->backend()->named_constant_expression(btype
, name
,
6795 this->bconst_
= const_decl
;
6797 return this->bconst_
;
6803 Type_declaration::add_method(const std::string
& name
, Function
* function
)
6805 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
6806 this->methods_
.push_back(ret
);
6810 // Add a method declaration.
6813 Type_declaration::add_method_declaration(const std::string
& name
,
6815 Function_type
* type
,
6818 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
6820 this->methods_
.push_back(ret
);
6824 // Return whether any methods ere defined.
6827 Type_declaration::has_methods() const
6829 return !this->methods_
.empty();
6832 // Define methods for the real type.
6835 Type_declaration::define_methods(Named_type
* nt
)
6837 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
6838 p
!= this->methods_
.end();
6840 nt
->add_existing_method(*p
);
6843 // We are using the type. Return true if we should issue a warning.
6846 Type_declaration::using_type()
6848 bool ret
= !this->issued_warning_
;
6849 this->issued_warning_
= true;
6853 // Class Unknown_name.
6855 // Set the real named object.
6858 Unknown_name::set_real_named_object(Named_object
* no
)
6860 go_assert(this->real_named_object_
== NULL
);
6861 go_assert(!no
->is_unknown());
6862 this->real_named_object_
= no
;
6865 // Class Named_object.
6867 Named_object::Named_object(const std::string
& name
,
6868 const Package
* package
,
6869 Classification classification
)
6870 : name_(name
), package_(package
), classification_(classification
),
6871 is_redefinition_(false)
6873 if (Gogo::is_sink_name(name
))
6874 go_assert(classification
== NAMED_OBJECT_SINK
);
6877 // Make an unknown name. This is used by the parser. The name must
6878 // be resolved later. Unknown names are only added in the current
6882 Named_object::make_unknown_name(const std::string
& name
,
6885 Named_object
* named_object
= new Named_object(name
, NULL
,
6886 NAMED_OBJECT_UNKNOWN
);
6887 Unknown_name
* value
= new Unknown_name(location
);
6888 named_object
->u_
.unknown_value
= value
;
6889 return named_object
;
6895 Named_object::make_constant(const Typed_identifier
& tid
,
6896 const Package
* package
, Expression
* expr
,
6899 Named_object
* named_object
= new Named_object(tid
.name(), package
,
6900 NAMED_OBJECT_CONST
);
6901 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
6904 named_object
->u_
.const_value
= named_constant
;
6905 return named_object
;
6908 // Make a named type.
6911 Named_object::make_type(const std::string
& name
, const Package
* package
,
6912 Type
* type
, Location location
)
6914 Named_object
* named_object
= new Named_object(name
, package
,
6916 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
6917 named_object
->u_
.type_value
= named_type
;
6918 return named_object
;
6921 // Make a type declaration.
6924 Named_object::make_type_declaration(const std::string
& name
,
6925 const Package
* package
,
6928 Named_object
* named_object
= new Named_object(name
, package
,
6929 NAMED_OBJECT_TYPE_DECLARATION
);
6930 Type_declaration
* type_declaration
= new Type_declaration(location
);
6931 named_object
->u_
.type_declaration
= type_declaration
;
6932 return named_object
;
6938 Named_object::make_variable(const std::string
& name
, const Package
* package
,
6941 Named_object
* named_object
= new Named_object(name
, package
,
6943 named_object
->u_
.var_value
= variable
;
6944 return named_object
;
6947 // Make a result variable.
6950 Named_object::make_result_variable(const std::string
& name
,
6951 Result_variable
* result
)
6953 Named_object
* named_object
= new Named_object(name
, NULL
,
6954 NAMED_OBJECT_RESULT_VAR
);
6955 named_object
->u_
.result_var_value
= result
;
6956 return named_object
;
6959 // Make a sink. This is used for the special blank identifier _.
6962 Named_object::make_sink()
6964 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
6967 // Make a named function.
6970 Named_object::make_function(const std::string
& name
, const Package
* package
,
6973 Named_object
* named_object
= new Named_object(name
, package
,
6975 named_object
->u_
.func_value
= function
;
6976 return named_object
;
6979 // Make a function declaration.
6982 Named_object::make_function_declaration(const std::string
& name
,
6983 const Package
* package
,
6984 Function_type
* fntype
,
6987 Named_object
* named_object
= new Named_object(name
, package
,
6988 NAMED_OBJECT_FUNC_DECLARATION
);
6989 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
6990 named_object
->u_
.func_declaration_value
= func_decl
;
6991 return named_object
;
6997 Named_object::make_package(const std::string
& alias
, Package
* package
)
6999 Named_object
* named_object
= new Named_object(alias
, NULL
,
7000 NAMED_OBJECT_PACKAGE
);
7001 named_object
->u_
.package_value
= package
;
7002 return named_object
;
7005 // Return the name to use in an error message.
7008 Named_object::message_name() const
7010 if (this->package_
== NULL
)
7011 return Gogo::message_name(this->name_
);
7013 if (this->package_
->has_package_name())
7014 ret
= this->package_
->package_name();
7016 ret
= this->package_
->pkgpath();
7017 ret
= Gogo::message_name(ret
);
7019 ret
+= Gogo::message_name(this->name_
);
7023 // Set the type when a declaration is defined.
7026 Named_object::set_type_value(Named_type
* named_type
)
7028 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
7029 Type_declaration
* td
= this->u_
.type_declaration
;
7030 td
->define_methods(named_type
);
7032 Named_object
* in_function
= td
->in_function(&index
);
7033 if (in_function
!= NULL
)
7034 named_type
->set_in_function(in_function
, index
);
7036 this->classification_
= NAMED_OBJECT_TYPE
;
7037 this->u_
.type_value
= named_type
;
7040 // Define a function which was previously declared.
7043 Named_object::set_function_value(Function
* function
)
7045 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
7046 if (this->func_declaration_value()->has_descriptor())
7048 Expression
* descriptor
=
7049 this->func_declaration_value()->descriptor(NULL
, NULL
);
7050 function
->set_descriptor(descriptor
);
7052 this->classification_
= NAMED_OBJECT_FUNC
;
7053 // FIXME: We should free the old value.
7054 this->u_
.func_value
= function
;
7057 // Declare an unknown object as a type declaration.
7060 Named_object::declare_as_type()
7062 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
7063 Unknown_name
* unk
= this->u_
.unknown_value
;
7064 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
7065 this->u_
.type_declaration
= new Type_declaration(unk
->location());
7069 // Return the location of a named object.
7072 Named_object::location() const
7074 switch (this->classification_
)
7077 case NAMED_OBJECT_UNINITIALIZED
:
7080 case NAMED_OBJECT_ERRONEOUS
:
7081 return Linemap::unknown_location();
7083 case NAMED_OBJECT_UNKNOWN
:
7084 return this->unknown_value()->location();
7086 case NAMED_OBJECT_CONST
:
7087 return this->const_value()->location();
7089 case NAMED_OBJECT_TYPE
:
7090 return this->type_value()->location();
7092 case NAMED_OBJECT_TYPE_DECLARATION
:
7093 return this->type_declaration_value()->location();
7095 case NAMED_OBJECT_VAR
:
7096 return this->var_value()->location();
7098 case NAMED_OBJECT_RESULT_VAR
:
7099 return this->result_var_value()->location();
7101 case NAMED_OBJECT_SINK
:
7104 case NAMED_OBJECT_FUNC
:
7105 return this->func_value()->location();
7107 case NAMED_OBJECT_FUNC_DECLARATION
:
7108 return this->func_declaration_value()->location();
7110 case NAMED_OBJECT_PACKAGE
:
7111 return this->package_value()->location();
7115 // Export a named object.
7118 Named_object::export_named_object(Export
* exp
) const
7120 switch (this->classification_
)
7123 case NAMED_OBJECT_UNINITIALIZED
:
7124 case NAMED_OBJECT_UNKNOWN
:
7127 case NAMED_OBJECT_ERRONEOUS
:
7130 case NAMED_OBJECT_CONST
:
7131 this->const_value()->export_const(exp
, this->name_
);
7134 case NAMED_OBJECT_TYPE
:
7135 this->type_value()->export_named_type(exp
, this->name_
);
7138 case NAMED_OBJECT_TYPE_DECLARATION
:
7139 go_error_at(this->type_declaration_value()->location(),
7140 "attempt to export %<%s%> which was declared but not defined",
7141 this->message_name().c_str());
7144 case NAMED_OBJECT_FUNC_DECLARATION
:
7145 this->func_declaration_value()->export_func(exp
, this->name_
);
7148 case NAMED_OBJECT_VAR
:
7149 this->var_value()->export_var(exp
, this->name_
);
7152 case NAMED_OBJECT_RESULT_VAR
:
7153 case NAMED_OBJECT_SINK
:
7156 case NAMED_OBJECT_FUNC
:
7157 this->func_value()->export_func(exp
, this->name_
);
7162 // Convert a variable to the backend representation.
7165 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
7167 if (this->classification_
== NAMED_OBJECT_VAR
)
7168 return this->var_value()->get_backend_variable(gogo
, function
,
7169 this->package_
, this->name_
);
7170 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
7171 return this->result_var_value()->get_backend_variable(gogo
, function
,
7178 // Return the external identifier for this object.
7181 Named_object::get_id(Gogo
* gogo
)
7183 go_assert(!this->is_variable() && !this->is_result_variable());
7184 std::string decl_name
;
7185 if (this->is_function_declaration()
7186 && !this->func_declaration_value()->asm_name().empty())
7187 decl_name
= this->func_declaration_value()->asm_name();
7188 else if (this->is_type()
7189 && Linemap::is_predeclared_location(this->type_value()->location()))
7191 // We don't need the package name for builtin types.
7192 decl_name
= Gogo::unpack_hidden_name(this->name_
);
7196 std::string package_name
;
7197 if (this->package_
== NULL
)
7198 package_name
= gogo
->package_name();
7200 package_name
= this->package_
->package_name();
7202 // Note that this will be misleading if this is an unexported
7203 // method generated for an embedded imported type. In that case
7204 // the unexported method should have the package name of the
7205 // package from which it is imported, but we are going to give
7206 // it our package name. Fixing this would require knowing the
7207 // package name, but we only know the package path. It might be
7208 // better to use package paths here anyhow. This doesn't affect
7209 // the assembler code, because we always set that name in
7210 // Function::get_or_make_decl anyhow. FIXME.
7212 decl_name
= package_name
+ '.' + Gogo::unpack_hidden_name(this->name_
);
7214 Function_type
* fntype
;
7215 if (this->is_function())
7216 fntype
= this->func_value()->type();
7217 else if (this->is_function_declaration())
7218 fntype
= this->func_declaration_value()->type();
7221 if (fntype
!= NULL
&& fntype
->is_method())
7223 decl_name
.push_back('.');
7224 decl_name
.append(fntype
->receiver()->type()->mangled_name(gogo
));
7227 if (this->is_type())
7230 const Named_object
* in_function
= this->type_value()->in_function(&index
);
7231 if (in_function
!= NULL
)
7233 decl_name
+= '$' + Gogo::unpack_hidden_name(in_function
->name());
7237 snprintf(buf
, sizeof buf
, "%u", index
);
7246 // Get the backend representation for this named object.
7249 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
7250 std::vector
<Btype
*>& type_decls
,
7251 std::vector
<Bfunction
*>& func_decls
)
7253 // If this is a definition, avoid trying to get the backend
7254 // representation, as that can crash.
7255 if (this->is_redefinition_
)
7257 go_assert(saw_errors());
7261 switch (this->classification_
)
7263 case NAMED_OBJECT_CONST
:
7264 if (!Gogo::is_erroneous_name(this->name_
))
7265 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
7268 case NAMED_OBJECT_TYPE
:
7270 Named_type
* named_type
= this->u_
.type_value
;
7271 if (!Gogo::is_erroneous_name(this->name_
))
7272 type_decls
.push_back(named_type
->get_backend(gogo
));
7274 // We need to produce a type descriptor for every named
7275 // type, and for a pointer to every named type, since
7276 // other files or packages might refer to them. We need
7277 // to do this even for hidden types, because they might
7278 // still be returned by some function. Simply calling the
7279 // type_descriptor method is enough to create the type
7280 // descriptor, even though we don't do anything with it.
7281 if (this->package_
== NULL
&& !saw_errors())
7284 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7285 named_type
->gc_symbol_pointer(gogo
);
7286 Type
* pn
= Type::make_pointer_type(named_type
);
7287 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
7288 pn
->gc_symbol_pointer(gogo
);
7293 case NAMED_OBJECT_TYPE_DECLARATION
:
7294 go_error_at(Linemap::unknown_location(),
7295 "reference to undefined type %qs",
7296 this->message_name().c_str());
7299 case NAMED_OBJECT_VAR
:
7300 case NAMED_OBJECT_RESULT_VAR
:
7301 case NAMED_OBJECT_SINK
:
7304 case NAMED_OBJECT_FUNC
:
7306 Function
* func
= this->u_
.func_value
;
7307 if (!Gogo::is_erroneous_name(this->name_
))
7308 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
7310 if (func
->block() != NULL
)
7311 func
->build(gogo
, this);
7315 case NAMED_OBJECT_ERRONEOUS
:
7325 Bindings::Bindings(Bindings
* enclosing
)
7326 : enclosing_(enclosing
), named_objects_(), bindings_()
7333 Bindings::clear_file_scope(Gogo
* gogo
)
7335 Contour::iterator p
= this->bindings_
.begin();
7336 while (p
!= this->bindings_
.end())
7339 if (p
->second
->package() != NULL
)
7341 else if (p
->second
->is_package())
7343 else if (p
->second
->is_function()
7344 && !p
->second
->func_value()->type()->is_method()
7345 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
7354 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
7355 p
= this->bindings_
.erase(p
);
7360 // Look up a symbol.
7363 Bindings::lookup(const std::string
& name
) const
7365 Contour::const_iterator p
= this->bindings_
.find(name
);
7366 if (p
!= this->bindings_
.end())
7367 return p
->second
->resolve();
7368 else if (this->enclosing_
!= NULL
)
7369 return this->enclosing_
->lookup(name
);
7374 // Look up a symbol locally.
7377 Bindings::lookup_local(const std::string
& name
) const
7379 Contour::const_iterator p
= this->bindings_
.find(name
);
7380 if (p
== this->bindings_
.end())
7385 // Remove an object from a set of bindings. This is used for a
7386 // special case in thunks for functions which call recover.
7389 Bindings::remove_binding(Named_object
* no
)
7391 Contour::iterator pb
= this->bindings_
.find(no
->name());
7392 go_assert(pb
!= this->bindings_
.end());
7393 this->bindings_
.erase(pb
);
7394 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
7395 pn
!= this->named_objects_
.end();
7400 this->named_objects_
.erase(pn
);
7407 // Add a method to the list of objects. This is not added to the
7408 // lookup table. This is so that we have a single list of objects
7409 // declared at the top level, which we walk through when it's time to
7410 // convert to trees.
7413 Bindings::add_method(Named_object
* method
)
7415 this->named_objects_
.push_back(method
);
7418 // Add a generic Named_object to a Contour.
7421 Bindings::add_named_object_to_contour(Contour
* contour
,
7422 Named_object
* named_object
)
7424 go_assert(named_object
== named_object
->resolve());
7425 const std::string
& name(named_object
->name());
7426 go_assert(!Gogo::is_sink_name(name
));
7428 std::pair
<Contour::iterator
, bool> ins
=
7429 contour
->insert(std::make_pair(name
, named_object
));
7432 // The name was already there.
7433 if (named_object
->package() != NULL
7434 && ins
.first
->second
->package() == named_object
->package()
7435 && (ins
.first
->second
->classification()
7436 == named_object
->classification()))
7438 // This is a second import of the same object.
7439 return ins
.first
->second
;
7441 ins
.first
->second
= this->new_definition(ins
.first
->second
,
7443 return ins
.first
->second
;
7447 // Don't push declarations on the list. We push them on when
7448 // and if we find the definitions. That way we genericize the
7449 // functions in order.
7450 if (!named_object
->is_type_declaration()
7451 && !named_object
->is_function_declaration()
7452 && !named_object
->is_unknown())
7453 this->named_objects_
.push_back(named_object
);
7454 return named_object
;
7458 // We had an existing named object OLD_OBJECT, and we've seen a new
7459 // one NEW_OBJECT with the same name. FIXME: This does not free the
7460 // new object when we don't need it.
7463 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
7465 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
7469 switch (old_object
->classification())
7472 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
7475 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7478 case Named_object::NAMED_OBJECT_UNKNOWN
:
7480 Named_object
* real
= old_object
->unknown_value()->real_named_object();
7482 return this->new_definition(real
, new_object
);
7483 go_assert(!new_object
->is_unknown());
7484 old_object
->unknown_value()->set_real_named_object(new_object
);
7485 if (!new_object
->is_type_declaration()
7486 && !new_object
->is_function_declaration())
7487 this->named_objects_
.push_back(new_object
);
7491 case Named_object::NAMED_OBJECT_CONST
:
7494 case Named_object::NAMED_OBJECT_TYPE
:
7495 if (new_object
->is_type_declaration())
7499 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7500 if (new_object
->is_type_declaration())
7502 if (new_object
->is_type())
7504 old_object
->set_type_value(new_object
->type_value());
7505 new_object
->type_value()->set_named_object(old_object
);
7506 this->named_objects_
.push_back(old_object
);
7511 case Named_object::NAMED_OBJECT_VAR
:
7512 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7513 // We have already given an error in the parser for cases where
7514 // one parameter or result variable redeclares another one.
7515 if ((new_object
->is_variable()
7516 && new_object
->var_value()->is_parameter())
7517 || new_object
->is_result_variable())
7521 case Named_object::NAMED_OBJECT_SINK
:
7524 case Named_object::NAMED_OBJECT_FUNC
:
7525 if (new_object
->is_function_declaration())
7527 if (!new_object
->func_declaration_value()->asm_name().empty())
7528 go_error_at(Linemap::unknown_location(),
7529 ("sorry, not implemented: "
7530 "__asm__ for function definitions"));
7531 Function_type
* old_type
= old_object
->func_value()->type();
7532 Function_type
* new_type
=
7533 new_object
->func_declaration_value()->type();
7534 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7539 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7541 if (new_object
->is_function())
7543 Function_type
* old_type
=
7544 old_object
->func_declaration_value()->type();
7545 Function_type
* new_type
= new_object
->func_value()->type();
7546 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
7548 if (!old_object
->func_declaration_value()->asm_name().empty())
7549 go_error_at(Linemap::unknown_location(),
7550 ("sorry, not implemented: "
7551 "__asm__ for function definitions"));
7552 old_object
->set_function_value(new_object
->func_value());
7553 this->named_objects_
.push_back(old_object
);
7560 case Named_object::NAMED_OBJECT_PACKAGE
:
7564 std::string n
= old_object
->message_name();
7566 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
7568 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
7570 old_object
->set_is_redefinition();
7571 new_object
->set_is_redefinition();
7573 go_inform(old_object
->location(), "previous definition of %qs was here",
7579 // Add a named type.
7582 Bindings::add_named_type(Named_type
* named_type
)
7584 return this->add_named_object(named_type
->named_object());
7590 Bindings::add_function(const std::string
& name
, const Package
* package
,
7593 return this->add_named_object(Named_object::make_function(name
, package
,
7597 // Add a function declaration.
7600 Bindings::add_function_declaration(const std::string
& name
,
7601 const Package
* package
,
7602 Function_type
* type
,
7605 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
7607 return this->add_named_object(no
);
7610 // Define a type which was previously declared.
7613 Bindings::define_type(Named_object
* no
, Named_type
* type
)
7615 no
->set_type_value(type
);
7616 this->named_objects_
.push_back(no
);
7619 // Mark all local variables as used. This is used for some types of
7623 Bindings::mark_locals_used()
7625 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
7626 p
!= this->named_objects_
.end();
7628 if ((*p
)->is_variable())
7629 (*p
)->var_value()->set_is_used();
7632 // Traverse bindings.
7635 Bindings::traverse(Traverse
* traverse
, bool is_global
)
7637 unsigned int traverse_mask
= traverse
->traverse_mask();
7639 // We don't use an iterator because we permit the traversal to add
7640 // new global objects.
7641 const unsigned int e_or_t
= (Traverse::traverse_expressions
7642 | Traverse::traverse_types
);
7643 const unsigned int e_or_t_or_s
= (e_or_t
7644 | Traverse::traverse_statements
);
7645 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
7647 Named_object
* p
= this->named_objects_
[i
];
7648 int t
= TRAVERSE_CONTINUE
;
7649 switch (p
->classification())
7651 case Named_object::NAMED_OBJECT_CONST
:
7652 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
7653 t
= traverse
->constant(p
, is_global
);
7654 if (t
== TRAVERSE_CONTINUE
7655 && (traverse_mask
& e_or_t
) != 0)
7657 Type
* tc
= p
->const_value()->type();
7659 && Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
7660 return TRAVERSE_EXIT
;
7661 t
= p
->const_value()->traverse_expression(traverse
);
7665 case Named_object::NAMED_OBJECT_VAR
:
7666 case Named_object::NAMED_OBJECT_RESULT_VAR
:
7667 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
7668 t
= traverse
->variable(p
);
7669 if (t
== TRAVERSE_CONTINUE
7670 && (traverse_mask
& e_or_t
) != 0)
7672 if (p
->is_result_variable()
7673 || p
->var_value()->has_type())
7675 Type
* tv
= (p
->is_variable()
7676 ? p
->var_value()->type()
7677 : p
->result_var_value()->type());
7679 && Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
7680 return TRAVERSE_EXIT
;
7683 if (t
== TRAVERSE_CONTINUE
7684 && (traverse_mask
& e_or_t_or_s
) != 0
7685 && p
->is_variable())
7686 t
= p
->var_value()->traverse_expression(traverse
, traverse_mask
);
7689 case Named_object::NAMED_OBJECT_FUNC
:
7690 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
7691 t
= traverse
->function(p
);
7693 if (t
== TRAVERSE_CONTINUE
7695 & (Traverse::traverse_variables
7696 | Traverse::traverse_constants
7697 | Traverse::traverse_functions
7698 | Traverse::traverse_blocks
7699 | Traverse::traverse_statements
7700 | Traverse::traverse_expressions
7701 | Traverse::traverse_types
)) != 0)
7702 t
= p
->func_value()->traverse(traverse
);
7705 case Named_object::NAMED_OBJECT_PACKAGE
:
7706 // These are traversed in Gogo::traverse.
7707 go_assert(is_global
);
7710 case Named_object::NAMED_OBJECT_TYPE
:
7711 if ((traverse_mask
& e_or_t
) != 0)
7712 t
= Type::traverse(p
->type_value(), traverse
);
7715 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
7716 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
7717 case Named_object::NAMED_OBJECT_UNKNOWN
:
7718 case Named_object::NAMED_OBJECT_ERRONEOUS
:
7721 case Named_object::NAMED_OBJECT_SINK
:
7726 if (t
== TRAVERSE_EXIT
)
7727 return TRAVERSE_EXIT
;
7730 // If we need to traverse types, check the function declarations,
7731 // which have types. Also check any methods of a type declaration.
7732 if ((traverse_mask
& e_or_t
) != 0)
7734 for (Bindings::const_declarations_iterator p
=
7735 this->begin_declarations();
7736 p
!= this->end_declarations();
7739 if (p
->second
->is_function_declaration())
7741 if (Type::traverse(p
->second
->func_declaration_value()->type(),
7744 return TRAVERSE_EXIT
;
7746 else if (p
->second
->is_type_declaration())
7748 const std::vector
<Named_object
*>* methods
=
7749 p
->second
->type_declaration_value()->methods();
7750 for (std::vector
<Named_object
*>::const_iterator pm
=
7752 pm
!= methods
->end();
7755 Named_object
* no
= *pm
;
7757 if (no
->is_function())
7758 t
= no
->func_value()->type();
7759 else if (no
->is_function_declaration())
7760 t
= no
->func_declaration_value()->type();
7763 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
7764 return TRAVERSE_EXIT
;
7770 return TRAVERSE_CONTINUE
;
7775 // Clear any references to this label.
7780 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
7781 p
!= this->refs_
.end();
7784 this->refs_
.clear();
7787 // Get the backend representation for a label.
7790 Label::get_backend_label(Translate_context
* context
)
7792 if (this->blabel_
== NULL
)
7794 Function
* function
= context
->function()->func_value();
7795 Bfunction
* bfunction
= function
->get_decl();
7796 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
7799 return this->blabel_
;
7802 // Return an expression for the address of this label.
7805 Label::get_addr(Translate_context
* context
, Location location
)
7807 Blabel
* label
= this->get_backend_label(context
);
7808 return context
->backend()->label_address(label
, location
);
7811 // Return the dummy label that represents any instance of the blank label.
7814 Label::create_dummy_label()
7816 static Label
* dummy_label
;
7817 if (dummy_label
== NULL
)
7819 dummy_label
= new Label("_");
7820 dummy_label
->set_is_used();
7825 // Class Unnamed_label.
7827 // Get the backend representation for an unnamed label.
7830 Unnamed_label::get_blabel(Translate_context
* context
)
7832 if (this->blabel_
== NULL
)
7834 Function
* function
= context
->function()->func_value();
7835 Bfunction
* bfunction
= function
->get_decl();
7836 this->blabel_
= context
->backend()->label(bfunction
, "",
7839 return this->blabel_
;
7842 // Return a statement which defines this unnamed label.
7845 Unnamed_label::get_definition(Translate_context
* context
)
7847 Blabel
* blabel
= this->get_blabel(context
);
7848 return context
->backend()->label_definition_statement(blabel
);
7851 // Return a goto statement to this unnamed label.
7854 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
7856 Blabel
* blabel
= this->get_blabel(context
);
7857 return context
->backend()->goto_statement(blabel
, location
);
7862 Package::Package(const std::string
& pkgpath
,
7863 const std::string
& pkgpath_symbol
, Location location
)
7864 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
7865 package_name_(), bindings_(new Bindings(NULL
)),
7868 go_assert(!pkgpath
.empty());
7871 // Set the package name.
7874 Package::set_package_name(const std::string
& package_name
, Location location
)
7876 go_assert(!package_name
.empty());
7877 if (this->package_name_
.empty())
7878 this->package_name_
= package_name
;
7879 else if (this->package_name_
!= package_name
)
7880 go_error_at(location
,
7881 ("saw two different packages with "
7882 "the same package path %s: %s, %s"),
7883 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
7884 package_name
.c_str());
7887 // Return the pkgpath symbol, which is a prefix for symbols defined in
7891 Package::pkgpath_symbol() const
7893 if (this->pkgpath_symbol_
.empty())
7894 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
7895 return this->pkgpath_symbol_
;
7898 // Set the package path symbol.
7901 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
7903 go_assert(!pkgpath_symbol
.empty());
7904 if (this->pkgpath_symbol_
.empty())
7905 this->pkgpath_symbol_
= pkgpath_symbol
;
7907 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
7910 // Note that symbol from this package was and qualified by ALIAS.
7913 Package::note_usage(const std::string
& alias
) const
7915 Aliases::const_iterator p
= this->aliases_
.find(alias
);
7916 go_assert(p
!= this->aliases_
.end());
7917 p
->second
->note_usage();
7920 // Forget a given usage. If forgetting this usage means this package becomes
7921 // unused, report that error.
7924 Package::forget_usage(Expression
* usage
) const
7926 if (this->fake_uses_
.empty())
7929 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
7930 go_assert(p
!= this->fake_uses_
.end());
7931 this->fake_uses_
.erase(p
);
7933 if (this->fake_uses_
.empty())
7934 go_error_at(this->location(), "imported and not used: %s",
7935 Gogo::message_name(this->package_name()).c_str());
7938 // Clear the used field for the next file. If the only usages of this package
7939 // are possibly fake, keep the fake usages for lowering.
7942 Package::clear_used()
7944 std::string dot_alias
= "." + this->package_name();
7945 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
7946 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
7947 this->fake_uses_
.clear();
7949 this->aliases_
.clear();
7953 Package::add_alias(const std::string
& alias
, Location location
)
7955 Aliases::const_iterator p
= this->aliases_
.find(alias
);
7956 if (p
== this->aliases_
.end())
7958 std::pair
<Aliases::iterator
, bool> ret
;
7959 ret
= this->aliases_
.insert(std::make_pair(alias
,
7960 new Package_alias(location
)));
7966 // Determine types of constants. Everything else in a package
7967 // (variables, function declarations) should already have a fixed
7968 // type. Constants may have abstract types.
7971 Package::determine_types()
7973 Bindings
* bindings
= this->bindings_
;
7974 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
7975 p
!= bindings
->end_definitions();
7978 if ((*p
)->is_const())
7979 (*p
)->const_value()->determine_type();
7987 Traverse::~Traverse()
7989 if (this->types_seen_
!= NULL
)
7990 delete this->types_seen_
;
7991 if (this->expressions_seen_
!= NULL
)
7992 delete this->expressions_seen_
;
7995 // Record that we are looking at a type, and return true if we have
7999 Traverse::remember_type(const Type
* type
)
8001 if (type
->is_error_type())
8003 go_assert((this->traverse_mask() & traverse_types
) != 0
8004 || (this->traverse_mask() & traverse_expressions
) != 0);
8005 // We mostly only have to remember named types. But it turns out
8006 // that an interface type can refer to itself without using a name
8007 // by relying on interface inheritance, as in
8008 // type I interface { F() interface{I} }
8009 if (type
->classification() != Type::TYPE_NAMED
8010 && type
->classification() != Type::TYPE_INTERFACE
)
8012 if (this->types_seen_
== NULL
)
8013 this->types_seen_
= new Types_seen();
8014 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
8018 // Record that we are looking at an expression, and return true if we
8019 // have already seen it. NB: this routine used to assert if the traverse
8020 // mask did not include expressions/types -- this is no longer the case,
8021 // since it can be useful to remember specific expressions during
8022 // walks that only cover statements.
8025 Traverse::remember_expression(const Expression
* expression
)
8027 if (this->expressions_seen_
== NULL
)
8028 this->expressions_seen_
= new Expressions_seen();
8029 std::pair
<Expressions_seen::iterator
, bool> ins
=
8030 this->expressions_seen_
->insert(expression
);
8034 // The default versions of these functions should never be called: the
8035 // traversal mask indicates which functions may be called.
8038 Traverse::variable(Named_object
*)
8044 Traverse::constant(Named_object
*, bool)
8050 Traverse::function(Named_object
*)
8056 Traverse::block(Block
*)
8062 Traverse::statement(Block
*, size_t*, Statement
*)
8068 Traverse::expression(Expression
**)
8074 Traverse::type(Type
*)
8079 // Class Statement_inserter.
8082 Statement_inserter::insert(Statement
* s
)
8084 if (this->block_
!= NULL
)
8086 go_assert(this->pindex_
!= NULL
);
8087 this->block_
->insert_statement_before(*this->pindex_
, s
);
8090 else if (this->var_
!= NULL
)
8091 this->var_
->add_preinit_statement(this->gogo_
, s
);
8093 go_assert(saw_errors());