1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #include "filenames.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
17 #include "go-optimize.h"
20 #include "statements.h"
21 #include "expressions.h"
30 Gogo::Gogo(Backend
* backend
, Linemap
* linemap
, int, int pointer_size
)
35 globals_(new Bindings(NULL
)),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
40 current_file_imported_embed_(false),
51 pkgpath_from_option_(false),
52 prefix_from_option_(false),
53 relative_import_path_(),
55 check_divide_by_zero_(true),
56 check_divide_overflow_(true),
57 compiling_runtime_(false),
58 debug_escape_level_(0),
59 debug_optimization_(false),
60 nil_check_size_threshold_(4096),
64 specific_type_functions_(),
65 specific_type_functions_are_written_(false),
66 named_types_are_converted_(false),
70 imported_inlinable_functions_(),
71 imported_inline_functions_()
73 const Location loc
= Linemap::predeclared_location();
75 Named_type
* uint8_type
= Type::make_integer_type("uint8", true, 8,
76 RUNTIME_TYPE_KIND_UINT8
);
77 this->add_named_type(uint8_type
);
78 this->add_named_type(Type::make_integer_type("uint16", true, 16,
79 RUNTIME_TYPE_KIND_UINT16
));
80 this->add_named_type(Type::make_integer_type("uint32", true, 32,
81 RUNTIME_TYPE_KIND_UINT32
));
82 this->add_named_type(Type::make_integer_type("uint64", true, 64,
83 RUNTIME_TYPE_KIND_UINT64
));
85 this->add_named_type(Type::make_integer_type("int8", false, 8,
86 RUNTIME_TYPE_KIND_INT8
));
87 this->add_named_type(Type::make_integer_type("int16", false, 16,
88 RUNTIME_TYPE_KIND_INT16
));
89 Named_type
* int32_type
= Type::make_integer_type("int32", false, 32,
90 RUNTIME_TYPE_KIND_INT32
);
91 this->add_named_type(int32_type
);
92 this->add_named_type(Type::make_integer_type("int64", false, 64,
93 RUNTIME_TYPE_KIND_INT64
));
95 this->add_named_type(Type::make_float_type("float32", 32,
96 RUNTIME_TYPE_KIND_FLOAT32
));
97 this->add_named_type(Type::make_float_type("float64", 64,
98 RUNTIME_TYPE_KIND_FLOAT64
));
100 this->add_named_type(Type::make_complex_type("complex64", 64,
101 RUNTIME_TYPE_KIND_COMPLEX64
));
102 this->add_named_type(Type::make_complex_type("complex128", 128,
103 RUNTIME_TYPE_KIND_COMPLEX128
));
105 int int_type_size
= pointer_size
;
106 if (int_type_size
< 32)
108 this->add_named_type(Type::make_integer_type("uint", true,
110 RUNTIME_TYPE_KIND_UINT
));
111 Named_type
* int_type
= Type::make_integer_type("int", false, int_type_size
,
112 RUNTIME_TYPE_KIND_INT
);
113 this->add_named_type(int_type
);
115 this->add_named_type(Type::make_integer_type("uintptr", true,
117 RUNTIME_TYPE_KIND_UINTPTR
));
119 // "byte" is an alias for "uint8".
120 uint8_type
->integer_type()->set_is_byte();
121 this->add_named_type(Type::make_integer_type_alias("byte", uint8_type
));
123 // "rune" is an alias for "int32".
124 int32_type
->integer_type()->set_is_rune();
125 this->add_named_type(Type::make_integer_type_alias("rune", int32_type
));
127 this->add_named_type(Type::make_named_bool_type());
129 this->add_named_type(Type::make_named_string_type());
131 // "error" is interface { Error() string }.
133 Typed_identifier_list
*methods
= new Typed_identifier_list
;
134 Typed_identifier_list
*results
= new Typed_identifier_list
;
135 results
->push_back(Typed_identifier("", Type::lookup_string_type(), loc
));
136 Type
*method_type
= Type::make_function_type(NULL
, NULL
, results
, loc
);
137 methods
->push_back(Typed_identifier("Error", method_type
, loc
));
138 Interface_type
*error_iface
= Type::make_interface_type(methods
, loc
);
139 error_iface
->finalize_methods();
140 Named_type
*error_type
= Named_object::make_type("error", NULL
, error_iface
, loc
)->type_value();
141 this->add_named_type(error_type
);
144 // "any" is an alias for the empty interface type.
146 Type
* empty
= Type::make_empty_interface_type(loc
);
147 Named_object
* no
= Named_object::make_type("any", NULL
, empty
, loc
);
148 Named_type
* nt
= no
->type_value();
150 this->add_named_type(nt
);
153 this->globals_
->add_constant(Typed_identifier("true",
154 Type::make_boolean_type(),
157 Expression::make_boolean(true, loc
),
159 this->globals_
->add_constant(Typed_identifier("false",
160 Type::make_boolean_type(),
163 Expression::make_boolean(false, loc
),
166 this->globals_
->add_constant(Typed_identifier("nil", Type::make_nil_type(),
169 Expression::make_nil(loc
),
172 Type
* abstract_int_type
= Type::make_abstract_integer_type();
173 this->globals_
->add_constant(Typed_identifier("iota", abstract_int_type
,
176 Expression::make_iota(),
179 Function_type
* new_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
180 new_type
->set_is_varargs();
181 new_type
->set_is_builtin();
182 this->globals_
->add_function_declaration("new", NULL
, new_type
, loc
);
184 Function_type
* make_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
185 make_type
->set_is_varargs();
186 make_type
->set_is_builtin();
187 this->globals_
->add_function_declaration("make", NULL
, make_type
, loc
);
189 Typed_identifier_list
* len_result
= new Typed_identifier_list();
190 len_result
->push_back(Typed_identifier("", int_type
, loc
));
191 Function_type
* len_type
= Type::make_function_type(NULL
, NULL
, len_result
,
193 len_type
->set_is_builtin();
194 this->globals_
->add_function_declaration("len", NULL
, len_type
, loc
);
196 Typed_identifier_list
* cap_result
= new Typed_identifier_list();
197 cap_result
->push_back(Typed_identifier("", int_type
, loc
));
198 Function_type
* cap_type
= Type::make_function_type(NULL
, NULL
, len_result
,
200 cap_type
->set_is_builtin();
201 this->globals_
->add_function_declaration("cap", NULL
, cap_type
, loc
);
203 Function_type
* print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
204 print_type
->set_is_varargs();
205 print_type
->set_is_builtin();
206 this->globals_
->add_function_declaration("print", NULL
, print_type
, loc
);
208 print_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
209 print_type
->set_is_varargs();
210 print_type
->set_is_builtin();
211 this->globals_
->add_function_declaration("println", NULL
, print_type
, loc
);
213 Type
*empty
= Type::make_empty_interface_type(loc
);
214 Typed_identifier_list
* panic_parms
= new Typed_identifier_list();
215 panic_parms
->push_back(Typed_identifier("e", empty
, loc
));
216 Function_type
*panic_type
= Type::make_function_type(NULL
, panic_parms
,
218 panic_type
->set_is_builtin();
219 this->globals_
->add_function_declaration("panic", NULL
, panic_type
, loc
);
221 Typed_identifier_list
* recover_result
= new Typed_identifier_list();
222 recover_result
->push_back(Typed_identifier("", empty
, loc
));
223 Function_type
* recover_type
= Type::make_function_type(NULL
, NULL
,
226 recover_type
->set_is_builtin();
227 this->globals_
->add_function_declaration("recover", NULL
, recover_type
, loc
);
229 Function_type
* close_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
230 close_type
->set_is_varargs();
231 close_type
->set_is_builtin();
232 this->globals_
->add_function_declaration("close", NULL
, close_type
, loc
);
234 Typed_identifier_list
* copy_result
= new Typed_identifier_list();
235 copy_result
->push_back(Typed_identifier("", int_type
, loc
));
236 Function_type
* copy_type
= Type::make_function_type(NULL
, NULL
,
238 copy_type
->set_is_varargs();
239 copy_type
->set_is_builtin();
240 this->globals_
->add_function_declaration("copy", NULL
, copy_type
, loc
);
242 Function_type
* append_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
243 append_type
->set_is_varargs();
244 append_type
->set_is_builtin();
245 this->globals_
->add_function_declaration("append", NULL
, append_type
, loc
);
247 Function_type
* complex_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
248 complex_type
->set_is_varargs();
249 complex_type
->set_is_builtin();
250 this->globals_
->add_function_declaration("complex", NULL
, complex_type
, loc
);
252 Function_type
* real_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
253 real_type
->set_is_varargs();
254 real_type
->set_is_builtin();
255 this->globals_
->add_function_declaration("real", NULL
, real_type
, loc
);
257 Function_type
* imag_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
258 imag_type
->set_is_varargs();
259 imag_type
->set_is_builtin();
260 this->globals_
->add_function_declaration("imag", NULL
, imag_type
, loc
);
262 Function_type
* delete_type
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
263 delete_type
->set_is_varargs();
264 delete_type
->set_is_builtin();
265 this->globals_
->add_function_declaration("delete", NULL
, delete_type
, loc
);
269 Gogo::pkgpath_for_symbol(const std::string
& pkgpath
)
271 go_assert(!pkgpath
.empty());
272 return go_encode_id(pkgpath
);
275 // Return a hash code for a string, given a starting hash.
278 Gogo::hash_string(const std::string
& s
, unsigned int h
)
280 const char* p
= s
.data();
281 size_t len
= s
.length();
282 for (; len
> 0; --len
)
290 // Get the package path to use for type reflection data. This should
291 // ideally be unique across the entire link.
294 Gogo::pkgpath() const
296 go_assert(this->pkgpath_set_
);
297 return this->pkgpath_
;
300 // Set the package path from the -fgo-pkgpath command line option.
303 Gogo::set_pkgpath(const std::string
& arg
)
305 go_assert(!this->pkgpath_set_
);
306 this->pkgpath_
= arg
;
307 this->pkgpath_set_
= true;
308 this->pkgpath_from_option_
= true;
311 // Get the package path to use for symbol names.
314 Gogo::pkgpath_symbol() const
316 go_assert(this->pkgpath_set_
);
317 return this->pkgpath_symbol_
;
320 // Set the unique prefix to use to determine the package path, from
321 // the -fgo-prefix command line option.
324 Gogo::set_prefix(const std::string
& arg
)
326 go_assert(!this->prefix_from_option_
);
328 this->prefix_from_option_
= true;
331 // Munge name for use in an error message.
334 Gogo::message_name(const std::string
& name
)
336 return go_localize_identifier(Gogo::unpack_hidden_name(name
).c_str());
339 // Get the package name.
342 Gogo::package_name() const
344 go_assert(this->package_
!= NULL
);
345 return this->package_
->package_name();
348 // Set the package name.
351 Gogo::set_package_name(const std::string
& package_name
,
354 if (this->package_
!= NULL
)
356 if (this->package_
->package_name() != package_name
)
357 go_error_at(location
, "expected package %<%s%>",
358 Gogo::message_name(this->package_
->package_name()).c_str());
362 // Now that we know the name of the package we are compiling, set
363 // the package path to use for reflect.Type.PkgPath and global
365 if (this->pkgpath_set_
)
366 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(this->pkgpath_
);
369 if (!this->prefix_from_option_
&& package_name
== "main")
371 this->pkgpath_
= package_name
;
372 this->pkgpath_symbol_
= Gogo::pkgpath_for_symbol(package_name
);
376 if (!this->prefix_from_option_
)
377 this->prefix_
= "go";
378 this->pkgpath_
= this->prefix_
+ '.' + package_name
;
379 this->pkgpath_symbol_
= (Gogo::pkgpath_for_symbol(this->prefix_
) + '.'
380 + Gogo::pkgpath_for_symbol(package_name
));
382 this->pkgpath_set_
= true;
385 this->package_
= this->register_package(this->pkgpath_
,
386 this->pkgpath_symbol_
, location
);
387 this->package_
->set_package_name(package_name
, location
);
389 if (this->is_main_package())
391 // Declare "main" as a function which takes no parameters and
393 Location uloc
= Linemap::unknown_location();
394 this->declare_function(Gogo::pack_hidden_name("main", false),
395 Type::make_function_type (NULL
, NULL
, NULL
, uloc
),
400 // Return whether this is the "main" package. This is not true if
401 // -fgo-pkgpath or -fgo-prefix was used.
404 Gogo::is_main_package() const
406 return (this->package_name() == "main"
407 && !this->pkgpath_from_option_
408 && !this->prefix_from_option_
);
414 Gogo::import_package(const std::string
& filename
,
415 const std::string
& local_name
,
416 bool is_local_name_exported
,
420 if (filename
.empty())
422 go_error_at(location
, "import path is empty");
426 const char *pf
= filename
.data();
427 const char *pend
= pf
+ filename
.length();
431 int adv
= Lex::fetch_char(pf
, &c
);
434 go_error_at(location
, "import path contains invalid UTF-8 sequence");
439 go_error_at(location
, "import path contains NUL");
442 if (c
< 0x20 || c
== 0x7f)
444 go_error_at(location
, "import path contains control character");
449 go_error_at(location
, "import path contains backslash; use slash");
452 if (Lex::is_unicode_space(c
))
454 go_error_at(location
, "import path contains space character");
457 if (c
< 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c
) != NULL
)
459 go_error_at(location
,
460 "import path contains invalid character '%c'", c
);
466 if (IS_ABSOLUTE_PATH(filename
.c_str()))
468 go_error_at(location
, "import path cannot be absolute path");
472 if (local_name
== "init")
473 go_error_at(location
, "cannot import package as init");
475 if (filename
== "unsafe")
477 this->import_unsafe(local_name
, is_local_name_exported
, location
);
478 this->current_file_imported_unsafe_
= true;
482 if (filename
== "embed")
483 this->current_file_imported_embed_
= true;
485 Imports::const_iterator p
= this->imports_
.find(filename
);
486 if (p
!= this->imports_
.end())
488 Package
* package
= p
->second
;
489 package
->set_location(location
);
490 std::string ln
= local_name
;
491 bool is_ln_exported
= is_local_name_exported
;
494 ln
= package
->package_name();
495 go_assert(!ln
.empty());
496 is_ln_exported
= Lex::is_exported_name(ln
);
502 Bindings
* bindings
= package
->bindings();
503 for (Bindings::const_declarations_iterator pd
=
504 bindings
->begin_declarations();
505 pd
!= bindings
->end_declarations();
507 this->add_dot_import_object(pd
->second
);
508 std::string dot_alias
= "." + package
->package_name();
509 package
->add_alias(dot_alias
, location
);
513 package
->add_alias(ln
, location
);
514 ln
= this->pack_hidden_name(ln
, is_ln_exported
);
515 this->package_
->bindings()->add_package(ln
, package
);
520 Import::Stream
* stream
= Import::open_package(filename
, location
,
521 this->relative_import_path_
);
525 go_error_at(location
, "import file %qs not found", filename
.c_str());
529 Import
* imp
= new Import(stream
, location
);
530 imp
->register_builtin_types(this);
531 Package
* package
= imp
->import(this, local_name
, is_local_name_exported
);
534 if (package
->pkgpath() == this->pkgpath())
535 go_error_at(location
,
536 ("imported package uses same package path as package "
537 "being compiled (see %<-fgo-pkgpath%> option)"));
539 this->imports_
.insert(std::make_pair(filename
, package
));
545 // FIXME: we never delete imp; we may need it for inlinable functions.
549 Gogo::lookup_init(const std::string
& init_name
)
551 Import_init
tmp("", init_name
, -1);
552 Import_init_set::iterator it
= this->imported_init_fns_
.find(&tmp
);
553 return (it
!= this->imported_init_fns_
.end()) ? *it
: NULL
;
556 // Add an import control function for an imported package to the list.
559 Gogo::add_import_init_fn(const std::string
& package_name
,
560 const std::string
& init_name
, int prio
)
562 for (Import_init_set::iterator p
=
563 this->imported_init_fns_
.begin();
564 p
!= this->imported_init_fns_
.end();
567 Import_init
*ii
= (*p
);
568 if (ii
->init_name() == init_name
)
570 // If a test of package P1, built as part of package P1,
571 // imports package P2, and P2 imports P1 (perhaps
572 // indirectly), then we will see the same import name with
573 // different import priorities. That is OK, so don't give
574 // an error about it.
575 if (ii
->package_name() != package_name
)
577 go_error_at(Linemap::unknown_location(),
578 "duplicate package initialization name %qs",
579 Gogo::message_name(init_name
).c_str());
580 go_inform(Linemap::unknown_location(), "used by package %qs",
581 Gogo::message_name(ii
->package_name()).c_str());
582 go_inform(Linemap::unknown_location(), " and by package %qs",
583 Gogo::message_name(package_name
).c_str());
585 ii
->set_priority(prio
);
590 Import_init
* nii
= new Import_init(package_name
, init_name
, prio
);
591 this->imported_init_fns_
.insert(nii
);
594 // Return whether we are at the global binding level.
597 Gogo::in_global_scope() const
599 return this->functions_
.empty();
602 // Return the current binding contour.
605 Gogo::current_bindings()
607 if (!this->functions_
.empty())
608 return this->functions_
.back().blocks
.back()->bindings();
609 else if (this->package_
!= NULL
)
610 return this->package_
->bindings();
612 return this->globals_
;
616 Gogo::current_bindings() const
618 if (!this->functions_
.empty())
619 return this->functions_
.back().blocks
.back()->bindings();
620 else if (this->package_
!= NULL
)
621 return this->package_
->bindings();
623 return this->globals_
;
627 Gogo::update_init_priority(Import_init
* ii
,
628 std::set
<const Import_init
*>* visited
)
633 for (std::set
<std::string
>::const_iterator pci
=
634 ii
->precursors().begin();
635 pci
!= ii
->precursors().end();
638 Import_init
* succ
= this->lookup_init(*pci
);
639 if (visited
->find(succ
) == visited
->end())
640 update_init_priority(succ
, visited
);
641 succ_prior
= std::max(succ_prior
, succ
->priority());
643 if (ii
->priority() <= succ_prior
)
644 ii
->set_priority(succ_prior
+ 1);
648 Gogo::recompute_init_priorities()
650 std::set
<Import_init
*> nonroots
;
652 for (Import_init_set::const_iterator p
=
653 this->imported_init_fns_
.begin();
654 p
!= this->imported_init_fns_
.end();
657 const Import_init
*ii
= *p
;
658 for (std::set
<std::string
>::const_iterator pci
=
659 ii
->precursors().begin();
660 pci
!= ii
->precursors().end();
663 Import_init
* ii_init
= this->lookup_init(*pci
);
664 nonroots
.insert(ii_init
);
668 // Recursively update priorities starting at roots.
669 std::set
<const Import_init
*> visited
;
670 for (Import_init_set::iterator p
=
671 this->imported_init_fns_
.begin();
672 p
!= this->imported_init_fns_
.end();
675 Import_init
* ii
= *p
;
676 if (nonroots
.find(ii
) != nonroots
.end())
678 update_init_priority(ii
, &visited
);
682 // Add statements to INIT_STMTS which run the initialization
683 // functions for imported packages. This is only used for the "main"
687 Gogo::init_imports(std::vector
<Bstatement
*>& init_stmts
, Bfunction
*bfunction
)
689 go_assert(this->is_main_package());
691 if (this->imported_init_fns_
.empty())
694 Location unknown_loc
= Linemap::unknown_location();
695 Function_type
* func_type
=
696 Type::make_function_type(NULL
, NULL
, NULL
, unknown_loc
);
697 Btype
* fntype
= func_type
->get_backend_fntype(this);
699 // Recompute init priorities based on a walk of the init graph.
700 recompute_init_priorities();
702 // We must call them in increasing priority order.
703 std::vector
<const Import_init
*> v
;
704 for (Import_init_set::const_iterator p
=
705 this->imported_init_fns_
.begin();
706 p
!= this->imported_init_fns_
.end();
709 // Don't include dummy inits. They are not real functions.
710 if ((*p
)->is_dummy())
712 if ((*p
)->priority() < 0)
713 go_error_at(Linemap::unknown_location(),
714 "internal error: failed to set init priority for %s",
715 (*p
)->package_name().c_str());
718 std::sort(v
.begin(), v
.end(), priority_compare
);
720 // We build calls to the init functions, which take no arguments.
721 std::vector
<Bexpression
*> empty_args
;
722 for (std::vector
<const Import_init
*>::const_iterator p
= v
.begin();
726 const Import_init
* ii
= *p
;
727 std::string user_name
= ii
->package_name() + ".init";
728 const std::string
& init_name(ii
->init_name());
729 const unsigned int flags
=
730 (Backend::function_is_visible
731 | Backend::function_is_declaration
732 | Backend::function_is_inlinable
);
733 Bfunction
* pfunc
= this->backend()->function(fntype
, user_name
, init_name
,
735 Bexpression
* pfunc_code
=
736 this->backend()->function_code_expression(pfunc
, unknown_loc
);
737 Bexpression
* pfunc_call
=
738 this->backend()->call_expression(bfunction
, pfunc_code
, empty_args
,
740 init_stmts
.push_back(this->backend()->expression_statement(bfunction
,
745 // Register global variables with the garbage collector. We need to
746 // register all variables which can hold a pointer value. They become
747 // roots during the mark phase. We build a struct that is easy to
748 // hook into a list of roots.
750 // type gcRoot struct {
751 // decl unsafe.Pointer // Pointer to variable.
752 // size uintptr // Total size of variable.
753 // ptrdata uintptr // Length of variable's gcdata.
754 // gcdata *byte // Pointer mask.
757 // type gcRootList struct {
763 // The last entry in the roots array has a NULL decl field.
766 Gogo::register_gc_vars(const std::vector
<Named_object
*>& var_gc
,
767 std::vector
<Bstatement
*>& init_stmts
,
770 if (var_gc
.empty() && this->gc_roots_
.empty())
773 Type
* pvt
= Type::make_pointer_type(Type::make_void_type());
774 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
775 Type
* byte_type
= Type::lookup_integer_type("byte");
776 Type
* pointer_byte_type
= Type::make_pointer_type(byte_type
);
777 Struct_type
* root_type
=
778 Type::make_builtin_struct_type(4,
780 "size", uintptr_type
,
781 "ptrdata", uintptr_type
,
782 "gcdata", pointer_byte_type
);
784 Location builtin_loc
= Linemap::predeclared_location();
785 unsigned long roots_len
= var_gc
.size() + this->gc_roots_
.size();
786 Expression
* length
= Expression::make_integer_ul(roots_len
, NULL
,
788 Array_type
* root_array_type
= Type::make_array_type(root_type
, length
);
789 root_array_type
->set_is_array_incomparable();
791 Type
* int_type
= Type::lookup_integer_type("int");
792 Struct_type
* root_list_type
=
793 Type::make_builtin_struct_type(3,
796 "roots", root_array_type
);
798 // Build an initializer for the roots array.
800 Expression_list
* roots_init
= new Expression_list();
802 for (std::vector
<Named_object
*>::const_iterator p
= var_gc
.begin();
806 Expression_list
* init
= new Expression_list();
808 Location no_loc
= (*p
)->location();
809 Expression
* decl
= Expression::make_var_reference(*p
, no_loc
);
810 Expression
* decl_addr
=
811 Expression::make_unary(OPERATOR_AND
, decl
, no_loc
);
812 decl_addr
->unary_expression()->set_does_not_escape();
813 decl_addr
= Expression::make_cast(pvt
, decl_addr
, no_loc
);
814 init
->push_back(decl_addr
);
817 Expression::make_type_info(decl
->type(),
818 Expression::TYPE_INFO_SIZE
);
819 init
->push_back(size
);
821 Expression
* ptrdata
=
822 Expression::make_type_info(decl
->type(),
823 Expression::TYPE_INFO_BACKEND_PTRDATA
);
824 init
->push_back(ptrdata
);
826 Expression
* gcdata
= Expression::make_ptrmask_symbol(decl
->type());
827 init
->push_back(gcdata
);
829 Expression
* root_ctor
=
830 Expression::make_struct_composite_literal(root_type
, init
, no_loc
);
831 roots_init
->push_back(root_ctor
);
834 for (std::vector
<Expression
*>::const_iterator p
= this->gc_roots_
.begin();
835 p
!= this->gc_roots_
.end();
838 Expression_list
*init
= new Expression_list();
840 Expression
* expr
= *p
;
841 Location eloc
= expr
->location();
842 init
->push_back(Expression::make_cast(pvt
, expr
, eloc
));
844 Type
* type
= expr
->type()->points_to();
845 go_assert(type
!= NULL
);
848 Expression::make_type_info(type
,
849 Expression::TYPE_INFO_SIZE
);
850 init
->push_back(size
);
852 Expression
* ptrdata
=
853 Expression::make_type_info(type
,
854 Expression::TYPE_INFO_BACKEND_PTRDATA
);
855 init
->push_back(ptrdata
);
857 Expression
* gcdata
= Expression::make_ptrmask_symbol(type
);
858 init
->push_back(gcdata
);
860 Expression
* root_ctor
=
861 Expression::make_struct_composite_literal(root_type
, init
, eloc
);
862 roots_init
->push_back(root_ctor
);
865 // Build a constructor for the struct.
867 Expression_list
* root_list_init
= new Expression_list();
868 root_list_init
->push_back(Expression::make_nil(builtin_loc
));
869 root_list_init
->push_back(Expression::make_integer_ul(roots_len
, int_type
,
872 Expression
* roots_ctor
=
873 Expression::make_array_composite_literal(root_array_type
, roots_init
,
875 root_list_init
->push_back(roots_ctor
);
877 Expression
* root_list_ctor
=
878 Expression::make_struct_composite_literal(root_list_type
, root_list_init
,
881 Expression
* root_addr
= Expression::make_unary(OPERATOR_AND
, root_list_ctor
,
883 root_addr
->unary_expression()->set_is_gc_root();
884 Expression
* register_roots
= Runtime::make_call(Runtime::REGISTER_GC_ROOTS
,
885 builtin_loc
, 1, root_addr
);
887 Translate_context
context(this, NULL
, NULL
, NULL
);
888 Bexpression
* bcall
= register_roots
->get_backend(&context
);
889 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
, bcall
));
892 // Build the list of type descriptors defined in this package. This is to help
893 // the reflect package to find compiler-generated types.
895 // type typeDescriptorList struct {
897 // types [...]unsafe.Pointer
901 type_descriptor_list_type(unsigned long len
)
903 Location builtin_loc
= Linemap::predeclared_location();
904 Type
* int_type
= Type::lookup_integer_type("int");
905 Type
* ptr_type
= Type::make_pointer_type(Type::make_void_type());
906 // Avoid creating zero-length type.
907 unsigned long nelems
= (len
!= 0 ? len
: 1);
908 Expression
* len_expr
= Expression::make_integer_ul(nelems
, NULL
,
910 Array_type
* array_type
= Type::make_array_type(ptr_type
, len_expr
);
911 array_type
->set_is_array_incomparable();
912 Struct_type
* list_type
=
913 Type::make_builtin_struct_type(2, "count", int_type
,
914 "types", array_type
);
919 Gogo::build_type_descriptor_list()
921 // Create the list type
922 Location builtin_loc
= Linemap::predeclared_location();
923 unsigned long len
= this->type_descriptors_
.size();
924 Struct_type
* list_type
= type_descriptor_list_type(len
);
925 Btype
* bt
= list_type
->get_backend(this);
926 Btype
* bat
= list_type
->field(1)->type()->get_backend(this);
928 // Create the variable
929 std::string name
= this->type_descriptor_list_symbol(this->pkgpath_symbol());
930 unsigned int flags
= Backend::variable_is_constant
;
931 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bt
, flags
, 0);
933 // Build the initializer
934 std::vector
<unsigned long> indexes
;
935 std::vector
<Bexpression
*> vals
;
936 std::vector
<Type
*>::iterator p
= this->type_descriptors_
.begin();
937 for (unsigned long i
= 0; i
< len
; ++i
, ++p
)
939 Bexpression
* bexpr
= (*p
)->type_descriptor_pointer(this,
941 indexes
.push_back(i
);
942 vals
.push_back(bexpr
);
944 Bexpression
* barray
=
945 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
948 Translate_context
context(this, NULL
, NULL
, NULL
);
949 std::vector
<Bexpression
*> fields
;
950 Expression
* len_expr
= Expression::make_integer_ul(len
, NULL
,
952 fields
.push_back(len_expr
->get_backend(&context
));
953 fields
.push_back(barray
);
955 this->backend()->constructor_expression(bt
, fields
, builtin_loc
);
957 this->backend()->implicit_variable_set_init(bv
, name
, bt
, flags
, binit
);
960 // Register the type descriptors with the runtime. This is to help
961 // the reflect package to find compiler-generated types.
964 Gogo::register_type_descriptors(std::vector
<Bstatement
*>& init_stmts
,
967 // Create the list type
968 Location builtin_loc
= Linemap::predeclared_location();
969 Struct_type
* list_type
= type_descriptor_list_type(1);
970 Btype
* bt
= list_type
->get_backend(this);
972 // Collect type lists from transitive imports.
973 std::vector
<std::string
> list_names
;
974 for (Import_init_set::iterator it
= this->imported_init_fns_
.begin();
975 it
!= this->imported_init_fns_
.end();
978 std::string pkgpath_symbol
=
979 this->pkgpath_symbol_from_init_fn_name((*it
)->init_name());
980 list_names
.push_back(this->type_descriptor_list_symbol(pkgpath_symbol
));
982 // Add the main package itself.
983 list_names
.push_back(this->type_descriptor_list_symbol("main"));
985 // Build a list of lists.
986 std::vector
<unsigned long> indexes
;
987 std::vector
<Bexpression
*> vals
;
989 for (std::vector
<std::string
>::iterator p
= list_names
.begin();
990 p
!= list_names
.end();
994 this->backend()->implicit_variable_reference(*p
, *p
, bt
);
995 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
996 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
998 indexes
.push_back(i
);
999 vals
.push_back(bexpr
);
1002 Expression
* len_expr
= Expression::make_integer_ul(i
, NULL
, builtin_loc
);
1003 Type
* list_ptr_type
= Type::make_pointer_type(list_type
);
1004 Type
* list_array_type
= Type::make_array_type(list_ptr_type
, len_expr
);
1005 Btype
* bat
= list_array_type
->get_backend(this);
1006 Bexpression
* barray
=
1007 this->backend()->array_constructor_expression(bat
, indexes
, vals
,
1010 // Create a variable holding the list.
1011 std::string name
= this->typelists_symbol();
1012 unsigned int flags
= (Backend::variable_is_hidden
1013 | Backend::variable_is_constant
);
1014 Bvariable
* bv
= this->backend()->implicit_variable(name
, name
, bat
, flags
,
1016 this->backend()->implicit_variable_set_init(bv
, name
, bat
, flags
, barray
);
1018 // Build the call in main package's init function.
1019 Translate_context
context(this, NULL
, NULL
, NULL
);
1020 Bexpression
* bexpr
= this->backend()->var_expression(bv
, builtin_loc
);
1021 bexpr
= this->backend()->address_expression(bexpr
, builtin_loc
);
1022 Type
* array_ptr_type
= Type::make_pointer_type(list_array_type
);
1023 Expression
* expr
= Expression::make_backend(bexpr
, array_ptr_type
,
1025 expr
= Runtime::make_call(Runtime::REGISTER_TYPE_DESCRIPTORS
,
1026 builtin_loc
, 2, len_expr
->copy(), expr
);
1027 Bexpression
* bcall
= expr
->get_backend(&context
);
1028 init_stmts
.push_back(this->backend()->expression_statement(init_bfn
,
1032 // Build the decl for the initialization function.
1035 Gogo::initialization_function_decl()
1037 std::string name
= this->get_init_fn_name();
1038 Location loc
= this->package_
->location();
1040 Function_type
* fntype
= Type::make_function_type(NULL
, NULL
, NULL
, loc
);
1041 Function
* initfn
= new Function(fntype
, NULL
, NULL
, loc
);
1042 return Named_object::make_function(name
, NULL
, initfn
);
1045 // Create the magic initialization function. CODE_STMT is the
1046 // code that it needs to run.
1049 Gogo::create_initialization_function(Named_object
* initfn
,
1050 Bstatement
* code_stmt
)
1052 // Make sure that we thought we needed an initialization function,
1053 // as otherwise we will not have reported it in the export data.
1054 go_assert(this->is_main_package() || this->need_init_fn_
);
1057 initfn
= this->initialization_function_decl();
1059 // Bind the initialization function code to a block.
1060 Bfunction
* fndecl
= initfn
->func_value()->get_or_make_decl(this, initfn
);
1061 Location pkg_loc
= this->package_
->location();
1062 std::vector
<Bvariable
*> vars
;
1063 this->backend()->block(fndecl
, NULL
, vars
, pkg_loc
, pkg_loc
);
1065 if (!this->backend()->function_set_body(fndecl
, code_stmt
))
1067 go_assert(saw_errors());
1073 // Given an expression, collect all the global variables defined in
1074 // this package that it references.
1076 class Find_vars
: public Traverse
1079 // The list of variables we accumulate.
1080 typedef Unordered_set(Named_object
*) Vars
;
1082 // A hash table we use to avoid looping. The index is a
1083 // Named_object* or a Temporary_statement*. We only look through
1084 // objects defined in this package.
1085 typedef Unordered_set(const void*) Seen_objects
;
1089 : Traverse(traverse_expressions
),
1090 vars_(), seen_objects_()
1093 // An iterator through the variables found, after the traversal.
1094 typedef Vars::const_iterator const_iterator
;
1098 { return this->vars_
.begin(); }
1102 { return this->vars_
.end(); }
1105 expression(Expression
**);
1108 // Accumulated variables.
1110 // Objects we have already seen.
1111 Seen_objects seen_objects_
;
1114 // Collect global variables referenced by EXPR. Look through function
1115 // calls and variable initializations.
1118 Find_vars::expression(Expression
** pexpr
)
1120 Expression
* e
= *pexpr
;
1122 Var_expression
* ve
= e
->var_expression();
1125 Named_object
* v
= ve
->named_object();
1126 if (!v
->is_variable() || v
->package() != NULL
)
1128 // This is a result parameter or a variable defined in a
1129 // different package. Either way we don't care about it.
1130 return TRAVERSE_CONTINUE
;
1133 std::pair
<Seen_objects::iterator
, bool> ins
=
1134 this->seen_objects_
.insert(v
);
1137 // We've seen this variable before.
1138 return TRAVERSE_CONTINUE
;
1141 if (v
->var_value()->is_global())
1142 this->vars_
.insert(v
);
1144 Expression
* init
= v
->var_value()->init();
1147 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1148 return TRAVERSE_EXIT
;
1152 // We traverse the code of any function or bound method we see. Note that
1153 // this means that we will traverse the code of a function or bound method
1154 // whose address is taken even if it is not called.
1155 Func_expression
* fe
= e
->func_expression();
1156 Bound_method_expression
* bme
= e
->bound_method_expression();
1157 if (fe
!= NULL
|| bme
!= NULL
)
1159 const Named_object
* f
= fe
!= NULL
? fe
->named_object() : bme
->function();
1160 if (f
->is_function() && f
->package() == NULL
)
1162 std::pair
<Seen_objects::iterator
, bool> ins
=
1163 this->seen_objects_
.insert(f
);
1166 // This is the first time we have seen this name.
1167 if (f
->func_value()->block()->traverse(this) == TRAVERSE_EXIT
)
1168 return TRAVERSE_EXIT
;
1173 Temporary_reference_expression
* tre
= e
->temporary_reference_expression();
1176 Temporary_statement
* ts
= tre
->statement();
1177 Expression
* init
= ts
->init();
1180 std::pair
<Seen_objects::iterator
, bool> ins
=
1181 this->seen_objects_
.insert(ts
);
1184 // This is the first time we have seen this temporary
1186 if (Expression::traverse(&init
, this) == TRAVERSE_EXIT
)
1187 return TRAVERSE_EXIT
;
1192 return TRAVERSE_CONTINUE
;
1195 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1198 expression_requires(Expression
* expr
, Block
* preinit
, Named_object
* dep
,
1201 Find_vars find_vars
;
1203 Expression::traverse(&expr
, &find_vars
);
1204 if (preinit
!= NULL
)
1205 preinit
->traverse(&find_vars
);
1208 Expression
* init
= dep
->var_value()->init();
1210 Expression::traverse(&init
, &find_vars
);
1211 if (dep
->var_value()->has_pre_init())
1212 dep
->var_value()->preinit()->traverse(&find_vars
);
1215 for (Find_vars::const_iterator p
= find_vars
.begin();
1216 p
!= find_vars
.end();
1225 // Sort variable initializations. If the initialization expression
1226 // for variable A refers directly or indirectly to the initialization
1227 // expression for variable B, then we must initialize B before A.
1233 : var_(NULL
), init_(NULL
), refs_(NULL
), dep_count_(0)
1236 Var_init(Named_object
* var
, Bstatement
* init
)
1237 : var_(var
), init_(init
), refs_(NULL
), dep_count_(0)
1240 // Return the variable.
1243 { return this->var_
; }
1245 // Return the initialization expression.
1248 { return this->init_
; }
1252 add_ref(Named_object
* var
);
1254 // The variables which this variable's initializers refer to.
1255 const std::vector
<Named_object
*>*
1257 { return this->refs_
; }
1259 // Clear the references, if any.
1263 // Return the number of remaining dependencies.
1266 { return this->dep_count_
; }
1268 // Increment the number of dependencies.
1271 { ++this->dep_count_
; }
1273 // Decrement the number of dependencies.
1276 { --this->dep_count_
; }
1279 // The variable being initialized.
1281 // The backend initialization statement.
1283 // Variables this refers to.
1284 std::vector
<Named_object
*>* refs_
;
1285 // The number of initializations this is dependent on. A variable
1286 // initialization should not be emitted if any of its dependencies
1287 // have not yet been resolved.
1294 Var_init::add_ref(Named_object
* var
)
1296 if (this->refs_
== NULL
)
1297 this->refs_
= new std::vector
<Named_object
*>;
1298 this->refs_
->push_back(var
);
1301 // Clear the references, if any.
1304 Var_init::clear_refs()
1306 if (this->refs_
!= NULL
)
1313 // For comparing Var_init keys in a map.
1316 operator<(const Var_init
& v1
, const Var_init
& v2
)
1317 { return v1
.var()->name() < v2
.var()->name(); }
1319 typedef std::list
<Var_init
> Var_inits
;
1321 // Sort the variable initializations. The rule we follow is that we
1322 // emit them in the order they appear in the array, except that if the
1323 // initialization expression for a variable V1 depends upon another
1324 // variable V2 then we initialize V1 after V2.
1327 sort_var_inits(Gogo
* gogo
, Var_inits
* var_inits
)
1329 if (var_inits
->empty())
1332 std::map
<Named_object
*, Var_init
*> var_to_init
;
1334 // A mapping from a variable initialization to a set of
1335 // variable initializations that depend on it.
1336 typedef std::map
<Var_init
, std::set
<Var_init
*> > Init_deps
;
1337 Init_deps init_deps
;
1338 bool init_loop
= false;
1340 // Compute all variable references.
1341 for (Var_inits::iterator pvar
= var_inits
->begin();
1342 pvar
!= var_inits
->end();
1345 Named_object
* var
= pvar
->var();
1346 var_to_init
[var
] = &*pvar
;
1348 Find_vars find_vars
;
1349 Expression
* init
= var
->var_value()->init();
1351 Expression::traverse(&init
, &find_vars
);
1352 if (var
->var_value()->has_pre_init())
1353 var
->var_value()->preinit()->traverse(&find_vars
);
1354 Named_object
* dep
= gogo
->var_depends_on(var
->var_value());
1357 Expression
* dinit
= dep
->var_value()->init();
1359 Expression::traverse(&dinit
, &find_vars
);
1360 if (dep
->var_value()->has_pre_init())
1361 dep
->var_value()->preinit()->traverse(&find_vars
);
1363 for (Find_vars::const_iterator p
= find_vars
.begin();
1364 p
!= find_vars
.end();
1369 // Add dependencies to init_deps, and check for cycles.
1370 for (Var_inits::iterator pvar
= var_inits
->begin();
1371 pvar
!= var_inits
->end();
1374 Named_object
* var
= pvar
->var();
1376 const std::vector
<Named_object
*>* refs
= pvar
->refs();
1379 for (std::vector
<Named_object
*>::const_iterator pdep
= refs
->begin();
1380 pdep
!= refs
->end();
1383 Named_object
* dep
= *pdep
;
1386 // This is a reference from a variable to itself, which
1387 // may indicate a loop. We only report an error if
1388 // there is an initializer and there is no dependency.
1389 // When there is no initializer, it means that the
1390 // preinitializer sets the variable, which will appear
1391 // to be a loop here.
1392 if (var
->var_value()->init() != NULL
1393 && gogo
->var_depends_on(var
->var_value()) == NULL
)
1394 go_error_at(var
->location(),
1395 ("initialization expression for %qs "
1396 "depends upon itself"),
1397 var
->message_name().c_str());
1402 Var_init
* dep_init
= var_to_init
[dep
];
1403 if (dep_init
== NULL
)
1405 // This is a dependency on some variable that doesn't
1406 // have an initializer, so for purposes of
1407 // initialization ordering this is irrelevant.
1411 init_deps
[*dep_init
].insert(&(*pvar
));
1412 pvar
->add_dependency();
1414 // Check for cycles.
1415 const std::vector
<Named_object
*>* deprefs
= dep_init
->refs();
1416 if (deprefs
== NULL
)
1418 for (std::vector
<Named_object
*>::const_iterator pdepdep
=
1420 pdepdep
!= deprefs
->end();
1423 if (*pdepdep
== var
)
1425 go_error_at(var
->location(),
1426 ("initialization expressions for %qs and "
1427 "%qs depend upon each other"),
1428 var
->message_name().c_str(),
1429 dep
->message_name().c_str());
1430 go_inform(dep
->location(), "%qs defined here",
1431 dep
->message_name().c_str());
1439 var_to_init
.clear();
1440 for (Var_inits::iterator pvar
= var_inits
->begin();
1441 pvar
!= var_inits
->end();
1445 // If there are no dependencies then the declaration order is sorted.
1446 if (!init_deps
.empty() && !init_loop
)
1448 // Otherwise, sort variable initializations by emitting all variables with
1449 // no dependencies in declaration order. VAR_INITS is already in
1450 // declaration order.
1452 while (!var_inits
->empty())
1454 Var_inits::iterator v1
;;
1455 for (v1
= var_inits
->begin(); v1
!= var_inits
->end(); ++v1
)
1457 if (v1
->dep_count() == 0)
1460 go_assert(v1
!= var_inits
->end());
1462 // V1 either has no dependencies or its dependencies have already
1463 // been emitted, add it to READY next. When V1 is emitted, remove
1464 // a dependency from each V that depends on V1.
1465 ready
.splice(ready
.end(), *var_inits
, v1
);
1467 Init_deps::iterator p1
= init_deps
.find(*v1
);
1468 if (p1
!= init_deps
.end())
1470 std::set
<Var_init
*> resolved
= p1
->second
;
1471 for (std::set
<Var_init
*>::iterator pv
= resolved
.begin();
1472 pv
!= resolved
.end();
1474 (*pv
)->remove_dependency();
1475 init_deps
.erase(p1
);
1478 var_inits
->swap(ready
);
1479 go_assert(init_deps
.empty());
1483 // Give an error if the initialization expression for VAR depends on
1484 // itself. We only check if INIT is not NULL and there is no
1485 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1486 // which we will interpret as a loop.
1489 Gogo::check_self_dep(Named_object
* var
)
1491 Expression
* init
= var
->var_value()->init();
1492 Block
* preinit
= var
->var_value()->preinit();
1493 Named_object
* dep
= this->var_depends_on(var
->var_value());
1496 && expression_requires(init
, preinit
, NULL
, var
))
1497 go_error_at(var
->location(),
1498 "initialization expression for %qs depends upon itself",
1499 var
->message_name().c_str());
1502 // Write out the global definitions.
1505 Gogo::write_globals()
1507 this->build_interface_method_tables();
1509 Bindings
* bindings
= this->current_bindings();
1511 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
1512 p
!= bindings
->end_declarations();
1515 // If any function declarations needed a descriptor, make sure
1517 Named_object
* no
= p
->second
;
1518 if (no
->is_function_declaration())
1519 no
->func_declaration_value()->build_backend_descriptor(this);
1522 // Lists of globally declared types, variables, constants, and functions
1523 // that must be defined.
1524 std::vector
<Btype
*> type_decls
;
1525 std::vector
<Bvariable
*> var_decls
;
1526 std::vector
<Bexpression
*> const_decls
;
1527 std::vector
<Bfunction
*> func_decls
;
1529 // The init function declaration and associated Bfunction, if necessary.
1530 Named_object
* init_fndecl
= NULL
;
1531 Bfunction
* init_bfn
= NULL
;
1533 std::vector
<Bstatement
*> init_stmts
;
1534 std::vector
<Bstatement
*> var_init_stmts
;
1536 if (this->is_main_package())
1538 init_fndecl
= this->initialization_function_decl();
1539 init_bfn
= init_fndecl
->func_value()->get_or_make_decl(this, init_fndecl
);
1542 // A list of variable initializations.
1543 Var_inits var_inits
;
1545 // A list of variables which need to be registered with the garbage
1547 size_t count_definitions
= bindings
->size_definitions();
1548 std::vector
<Named_object
*> var_gc
;
1549 var_gc
.reserve(count_definitions
);
1551 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
1552 p
!= bindings
->end_definitions();
1555 Named_object
* no
= *p
;
1556 go_assert(!no
->is_type_declaration() && !no
->is_function_declaration());
1558 // There is nothing to do for a package.
1559 if (no
->is_package())
1562 // There is nothing to do for an object which was imported from
1563 // a different package into the global scope.
1564 if (no
->package() != NULL
)
1567 // Skip blank named functions and constants.
1568 if ((no
->is_function() && no
->func_value()->is_sink())
1569 || (no
->is_const() && no
->const_value()->is_sink()))
1572 // Skip global sink variables with static initializers. With
1573 // non-static initializers we have to evaluate for side effects,
1574 // and we wind up initializing a dummy variable. That is not
1575 // ideal but it works and it's a rare case.
1576 if (no
->is_variable()
1577 && no
->var_value()->is_global_sink()
1578 && !no
->var_value()->has_pre_init()
1579 && (no
->var_value()->init() == NULL
1580 || no
->var_value()->init()->is_static_initializer()))
1583 // There is nothing useful we can output for constants which
1584 // have ideal or non-integral type.
1587 Type
* type
= no
->const_value()->type();
1589 type
= no
->const_value()->expr()->type();
1590 if (type
->is_abstract() || !type
->is_numeric_type())
1594 if (!no
->is_variable())
1595 no
->get_backend(this, const_decls
, type_decls
, func_decls
);
1598 Variable
* var
= no
->var_value();
1599 Bvariable
* bvar
= no
->get_backend_variable(this, NULL
);
1600 var_decls
.push_back(bvar
);
1602 // Check for a sink variable, which may be used to run an
1603 // initializer purely for its side effects.
1604 bool is_sink
= no
->name()[0] == '_' && no
->name()[1] == '.';
1606 Bstatement
* var_init_stmt
= NULL
;
1607 if (!var
->has_pre_init())
1609 // If the backend representation of the variable initializer is
1610 // constant, we can just set the initial value using
1611 // global_var_set_init instead of during the init() function.
1612 // The initializer is constant if it is the zero-value of the
1613 // variable's type or if the initial value is an immutable value
1614 // that is not copied to the heap.
1615 bool is_static_initializer
= false;
1616 if (var
->init() == NULL
)
1617 is_static_initializer
= true;
1620 Type
* var_type
= var
->type();
1621 Expression
* init
= var
->init();
1622 Expression
* init_cast
=
1623 Expression::make_cast(var_type
, init
, var
->location());
1624 is_static_initializer
= init_cast
->is_static_initializer();
1627 // Non-constant variable initializations might need to create
1628 // temporary variables, which will need the initialization
1629 // function as context.
1630 Named_object
* var_init_fn
;
1631 if (is_static_initializer
)
1635 if (init_fndecl
== NULL
)
1637 init_fndecl
= this->initialization_function_decl();
1638 Function
* func
= init_fndecl
->func_value();
1639 init_bfn
= func
->get_or_make_decl(this, init_fndecl
);
1641 var_init_fn
= init_fndecl
;
1643 Bexpression
* var_binit
= var
->get_init(this, var_init_fn
);
1645 if (var_binit
== NULL
)
1647 else if (is_static_initializer
)
1649 if (expression_requires(var
->init(), NULL
,
1650 this->var_depends_on(var
), no
))
1651 go_error_at(no
->location(),
1652 "initialization expression for %qs depends "
1654 no
->message_name().c_str());
1655 this->backend()->global_variable_set_init(bvar
, var_binit
);
1659 this->backend()->expression_statement(init_bfn
, var_binit
);
1662 Location loc
= var
->location();
1663 Bexpression
* var_expr
=
1664 this->backend()->var_expression(bvar
, loc
);
1666 this->backend()->assignment_statement(init_bfn
, var_expr
,
1672 // We are going to create temporary variables which
1673 // means that we need an fndecl.
1674 if (init_fndecl
== NULL
)
1675 init_fndecl
= this->initialization_function_decl();
1677 Bvariable
* var_decl
= is_sink
? NULL
: bvar
;
1678 var_init_stmt
= var
->get_init_block(this, init_fndecl
, var_decl
);
1681 if (var_init_stmt
!= NULL
)
1683 if (var
->init() == NULL
&& !var
->has_pre_init())
1684 var_init_stmts
.push_back(var_init_stmt
);
1686 var_inits
.push_back(Var_init(no
, var_init_stmt
));
1688 else if (this->var_depends_on(var
) != NULL
)
1690 // This variable is initialized from something that is
1691 // not in its init or preinit. This variable needs to
1692 // participate in dependency analysis sorting, in case
1693 // some other variable depends on this one.
1694 Btype
* btype
= no
->var_value()->type()->get_backend(this);
1695 Bexpression
* zero
= this->backend()->zero_expression(btype
);
1696 Bstatement
* zero_stmt
=
1697 this->backend()->expression_statement(init_bfn
, zero
);
1698 var_inits
.push_back(Var_init(no
, zero_stmt
));
1701 // Collect a list of all global variables with pointers,
1702 // to register them for the garbage collector.
1703 if (!is_sink
&& var
->type()->has_pointer())
1705 // Avoid putting runtime.gcRoots itself on the list.
1706 if (this->compiling_runtime()
1707 && this->package_name() == "runtime"
1708 && (Gogo::unpack_hidden_name(no
->name()) == "gcRoots"
1709 || Gogo::unpack_hidden_name(no
->name()) == "gcRootsIndex"))
1712 var_gc
.push_back(no
);
1717 // Output inline functions, which are in different packages.
1718 for (std::vector
<Named_object
*>::const_iterator p
=
1719 this->imported_inline_functions_
.begin();
1720 p
!= this->imported_inline_functions_
.end();
1722 (*p
)->get_backend(this, const_decls
, type_decls
, func_decls
);
1724 // Build the list of type descriptors.
1725 this->build_type_descriptor_list();
1727 if (this->is_main_package())
1729 // Register the type descriptor lists, so that at run time
1730 // the reflect package can find compiler-created types, and
1731 // deduplicate if the same type is created with reflection.
1732 // This needs to be done before calling any package's init
1733 // function, as it may create type through reflection.
1734 this->register_type_descriptors(init_stmts
, init_bfn
);
1736 // Initialize imported packages.
1737 this->init_imports(init_stmts
, init_bfn
);
1740 // Register global variables with the garbage collector.
1741 this->register_gc_vars(var_gc
, init_stmts
, init_bfn
);
1743 // Simple variable initializations, after all variables are
1745 init_stmts
.push_back(this->backend()->statement_list(var_init_stmts
));
1747 // Complete variable initializations, first sorting them into a
1749 if (!var_inits
.empty())
1751 sort_var_inits(this, &var_inits
);
1752 for (Var_inits::const_iterator p
= var_inits
.begin();
1753 p
!= var_inits
.end();
1755 init_stmts
.push_back(p
->init());
1758 // After all the variables are initialized, call the init
1759 // functions if there are any. Init functions take no arguments, so
1760 // we pass in EMPTY_ARGS to call them.
1761 std::vector
<Bexpression
*> empty_args
;
1762 for (std::vector
<Named_object
*>::const_iterator p
=
1763 this->init_functions_
.begin();
1764 p
!= this->init_functions_
.end();
1767 Location func_loc
= (*p
)->location();
1768 Function
* func
= (*p
)->func_value();
1769 Bfunction
* initfn
= func
->get_or_make_decl(this, *p
);
1770 Bexpression
* func_code
=
1771 this->backend()->function_code_expression(initfn
, func_loc
);
1772 Bexpression
* call
= this->backend()->call_expression(init_bfn
, func_code
,
1775 Bstatement
* ist
= this->backend()->expression_statement(init_bfn
, call
);
1776 init_stmts
.push_back(ist
);
1779 // Set up a magic function to do all the initialization actions.
1780 // This will be called if this package is imported.
1781 Bstatement
* init_fncode
= this->backend()->statement_list(init_stmts
);
1782 if (this->need_init_fn_
|| this->is_main_package())
1785 this->create_initialization_function(init_fndecl
, init_fncode
);
1786 if (init_fndecl
!= NULL
)
1787 func_decls
.push_back(init_fndecl
->func_value()->get_decl());
1790 // We should not have seen any new bindings created during the conversion.
1791 go_assert(count_definitions
== this->current_bindings()->size_definitions());
1793 // Define all globally declared values.
1795 this->backend()->write_global_definitions(type_decls
, const_decls
,
1796 func_decls
, var_decls
);
1799 // Return the current block.
1802 Gogo::current_block()
1804 if (this->functions_
.empty())
1807 return this->functions_
.back().blocks
.back();
1810 // Look up a name in the current binding contour. If PFUNCTION is not
1811 // NULL, set it to the function in which the name is defined, or NULL
1812 // if the name is defined in global scope.
1815 Gogo::lookup(const std::string
& name
, Named_object
** pfunction
) const
1817 if (pfunction
!= NULL
)
1820 if (Gogo::is_sink_name(name
))
1821 return Named_object::make_sink();
1823 for (Open_functions::const_reverse_iterator p
= this->functions_
.rbegin();
1824 p
!= this->functions_
.rend();
1827 Named_object
* ret
= p
->blocks
.back()->bindings()->lookup(name
);
1830 if (pfunction
!= NULL
)
1831 *pfunction
= p
->function
;
1836 if (this->package_
!= NULL
)
1838 Named_object
* ret
= this->package_
->bindings()->lookup(name
);
1841 if (ret
->package() != NULL
)
1843 std::string dot_alias
= "." + ret
->package()->package_name();
1844 ret
->package()->note_usage(dot_alias
);
1850 // We do not look in the global namespace. If we did, the global
1851 // namespace would effectively hide names which were defined in
1852 // package scope which we have not yet seen. Instead,
1853 // define_global_names is called after parsing is over to connect
1854 // undefined names at package scope with names defined at global
1860 // Look up a name in the current block, without searching enclosing
1864 Gogo::lookup_in_block(const std::string
& name
) const
1866 go_assert(!this->functions_
.empty());
1867 go_assert(!this->functions_
.back().blocks
.empty());
1868 return this->functions_
.back().blocks
.back()->bindings()->lookup_local(name
);
1871 // Look up a name in the global namespace.
1874 Gogo::lookup_global(const char* name
) const
1876 return this->globals_
->lookup(name
);
1879 // Add an imported package.
1882 Gogo::add_imported_package(const std::string
& real_name
,
1883 const std::string
& alias_arg
,
1884 bool is_alias_exported
,
1885 const std::string
& pkgpath
,
1886 const std::string
& pkgpath_symbol
,
1888 bool* padd_to_globals
)
1890 Package
* ret
= this->register_package(pkgpath
, pkgpath_symbol
, location
);
1891 ret
->set_package_name(real_name
, location
);
1893 *padd_to_globals
= false;
1895 if (alias_arg
== "_")
1897 else if (alias_arg
== ".")
1899 *padd_to_globals
= true;
1900 std::string dot_alias
= "." + real_name
;
1901 ret
->add_alias(dot_alias
, location
);
1905 std::string alias
= alias_arg
;
1909 is_alias_exported
= Lex::is_exported_name(alias
);
1911 ret
->add_alias(alias
, location
);
1912 alias
= this->pack_hidden_name(alias
, is_alias_exported
);
1913 Named_object
* no
= this->package_
->bindings()->add_package(alias
, ret
);
1914 if (!no
->is_package())
1921 // Register a package. This package may or may not be imported. This
1922 // returns the Package structure for the package, creating if it
1923 // necessary. LOCATION is the location of the import statement that
1924 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1925 // for names in the package; it may be the empty string, in which case
1926 // we either get it later or make a guess when we need it.
1929 Gogo::register_package(const std::string
& pkgpath
,
1930 const std::string
& pkgpath_symbol
, Location location
)
1932 Package
* package
= NULL
;
1933 std::pair
<Packages::iterator
, bool> ins
=
1934 this->packages_
.insert(std::make_pair(pkgpath
, package
));
1937 // We have seen this package name before.
1938 package
= ins
.first
->second
;
1939 go_assert(package
!= NULL
&& package
->pkgpath() == pkgpath
);
1940 if (!pkgpath_symbol
.empty())
1941 package
->set_pkgpath_symbol(pkgpath_symbol
);
1942 if (Linemap::is_unknown_location(package
->location()))
1943 package
->set_location(location
);
1947 // First time we have seen this package name.
1948 package
= new Package(pkgpath
, pkgpath_symbol
, location
);
1949 go_assert(ins
.first
->second
== NULL
);
1950 ins
.first
->second
= package
;
1956 // Return the pkgpath symbol for a package, given the pkgpath.
1959 Gogo::pkgpath_symbol_for_package(const std::string
& pkgpath
)
1961 Packages::iterator p
= this->packages_
.find(pkgpath
);
1962 go_assert(p
!= this->packages_
.end());
1963 return p
->second
->pkgpath_symbol();
1966 // Start compiling a function.
1969 Gogo::start_function(const std::string
& name
, Function_type
* type
,
1970 bool add_method_to_type
, Location location
)
1972 bool at_top_level
= this->functions_
.empty();
1974 Block
* block
= new Block(NULL
, location
);
1976 Named_object
* enclosing
= (at_top_level
1978 : this->functions_
.back().function
);
1980 Function
* function
= new Function(type
, enclosing
, block
, location
);
1982 if (type
->is_method())
1984 const Typed_identifier
* receiver
= type
->receiver();
1985 Variable
* this_param
= new Variable(receiver
->type(), NULL
, false,
1986 true, true, location
);
1987 std::string rname
= receiver
->name();
1988 unsigned rcounter
= 0;
1990 // We need to give a nameless receiver parameter a synthesized name to
1991 // avoid having it clash with some other nameless param. FIXME.
1992 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
1994 block
->bindings()->add_variable(rname
, NULL
, this_param
);
1997 const Typed_identifier_list
* parameters
= type
->parameters();
1998 bool is_varargs
= type
->is_varargs();
1999 unsigned pcounter
= 0;
2000 if (parameters
!= NULL
)
2002 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
2003 p
!= parameters
->end();
2006 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
2008 if (is_varargs
&& p
+ 1 == parameters
->end())
2009 param
->set_is_varargs_parameter();
2011 std::string pname
= p
->name();
2013 // We need to give each nameless parameter a non-empty name to avoid
2014 // having it clash with some other nameless param. FIXME.
2015 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
2017 block
->bindings()->add_variable(pname
, NULL
, param
);
2021 function
->create_result_variables(this);
2023 const std::string
* pname
;
2024 std::string nested_name
;
2025 bool is_init
= false;
2026 if (Gogo::unpack_hidden_name(name
) == "init" && !type
->is_method())
2028 if ((type
->parameters() != NULL
&& !type
->parameters()->empty())
2029 || (type
->results() != NULL
&& !type
->results()->empty()))
2030 go_error_at(location
,
2031 "func init must have no arguments and no return values");
2032 // There can be multiple "init" functions, so give them each a
2034 nested_name
= this->init_function_name();
2035 pname
= &nested_name
;
2038 else if (!name
.empty())
2042 // Invent a name for a nested function.
2043 nested_name
= this->nested_function_name(enclosing
);
2044 pname
= &nested_name
;
2048 if (Gogo::is_sink_name(*pname
))
2050 std::string
sname(this->sink_function_name());
2051 ret
= Named_object::make_function(sname
, NULL
, function
);
2052 ret
->func_value()->set_is_sink();
2054 if (!type
->is_method())
2055 ret
= this->package_
->bindings()->add_named_object(ret
);
2056 else if (add_method_to_type
)
2058 // We should report errors even for sink methods.
2059 Type
* rtype
= type
->receiver()->type();
2060 // Avoid points_to and deref to avoid getting an error if
2061 // the type is not yet defined.
2062 if (rtype
->classification() == Type::TYPE_POINTER
)
2063 rtype
= rtype
->points_to();
2064 while (rtype
->named_type() != NULL
2065 && rtype
->named_type()->is_alias())
2066 rtype
= rtype
->named_type()->real_type()->forwarded();
2067 if (rtype
->is_error_type())
2069 else if (rtype
->named_type() != NULL
)
2071 if (rtype
->named_type()->named_object()->package() != NULL
)
2072 go_error_at(type
->receiver()->location(),
2073 "may not define methods on non-local type");
2075 else if (rtype
->forward_declaration_type() != NULL
)
2077 // Go ahead and add the method in case we need to report
2078 // an error when we see the definition.
2079 rtype
->forward_declaration_type()->add_existing_method(ret
);
2082 go_error_at(type
->receiver()->location(),
2083 ("invalid receiver type "
2084 "(receiver must be a named type)"));
2087 else if (!type
->is_method())
2089 ret
= this->package_
->bindings()->add_function(*pname
, NULL
, function
);
2090 if (!ret
->is_function() || ret
->func_value() != function
)
2092 // Redefinition error. Invent a name to avoid knockon
2094 std::string
rname(this->redefined_function_name());
2095 ret
= this->package_
->bindings()->add_function(rname
, NULL
, function
);
2100 if (!add_method_to_type
)
2101 ret
= Named_object::make_function(name
, NULL
, function
);
2104 go_assert(at_top_level
);
2105 Type
* rtype
= type
->receiver()->type();
2107 while (rtype
->named_type() != NULL
2108 && rtype
->named_type()->is_alias())
2109 rtype
= rtype
->named_type()->real_type()->forwarded();
2111 // We want to look through the pointer created by the
2112 // parser, without getting an error if the type is not yet
2114 if (rtype
->classification() == Type::TYPE_POINTER
)
2115 rtype
= rtype
->points_to();
2117 while (rtype
->named_type() != NULL
2118 && rtype
->named_type()->is_alias())
2119 rtype
= rtype
->named_type()->real_type()->forwarded();
2121 if (rtype
->is_error_type())
2122 ret
= Named_object::make_function(name
, NULL
, function
);
2123 else if (rtype
->named_type() != NULL
)
2125 if (rtype
->named_type()->named_object()->package() != NULL
)
2127 go_error_at(type
->receiver()->location(),
2128 "may not define methods on non-local type");
2129 ret
= Named_object::make_function(name
, NULL
, function
);
2133 ret
= rtype
->named_type()->add_method(name
, function
);
2134 if (!ret
->is_function())
2136 // Redefinition error.
2137 ret
= Named_object::make_function(name
, NULL
, function
);
2141 else if (rtype
->forward_declaration_type() != NULL
)
2143 Named_object
* type_no
=
2144 rtype
->forward_declaration_type()->named_object();
2145 if (type_no
->is_unknown())
2147 // If we are seeing methods it really must be a
2148 // type. Declare it as such. An alternative would
2149 // be to support lists of methods for unknown
2150 // expressions. Either way the error messages if
2151 // this is not a type are going to get confusing.
2152 Named_object
* declared
=
2153 this->declare_package_type(type_no
->name(),
2154 type_no
->location());
2156 == type_no
->unknown_value()->real_named_object());
2158 ret
= rtype
->forward_declaration_type()->add_method(name
,
2163 go_error_at(type
->receiver()->location(),
2164 ("invalid receiver type (receiver must "
2165 "be a named type)"));
2166 ret
= Named_object::make_function(name
, NULL
, function
);
2169 this->package_
->bindings()->add_method(ret
);
2172 this->functions_
.resize(this->functions_
.size() + 1);
2173 Open_function
& of(this->functions_
.back());
2175 of
.blocks
.push_back(block
);
2179 this->init_functions_
.push_back(ret
);
2180 this->need_init_fn_
= true;
2186 // Finish compiling a function.
2189 Gogo::finish_function(Location location
)
2191 this->finish_block(location
);
2192 go_assert(this->functions_
.back().blocks
.empty());
2193 this->functions_
.pop_back();
2196 // Return the current function.
2199 Gogo::current_function() const
2201 go_assert(!this->functions_
.empty());
2202 return this->functions_
.back().function
;
2205 // Start a new block.
2208 Gogo::start_block(Location location
)
2210 go_assert(!this->functions_
.empty());
2211 Block
* block
= new Block(this->current_block(), location
);
2212 this->functions_
.back().blocks
.push_back(block
);
2218 Gogo::finish_block(Location location
)
2220 go_assert(!this->functions_
.empty());
2221 go_assert(!this->functions_
.back().blocks
.empty());
2222 Block
* block
= this->functions_
.back().blocks
.back();
2223 this->functions_
.back().blocks
.pop_back();
2224 block
->set_end_location(location
);
2228 // Add an erroneous name.
2231 Gogo::add_erroneous_name(const std::string
& name
)
2233 return this->package_
->bindings()->add_erroneous_name(name
);
2236 // Add an unknown name.
2239 Gogo::add_unknown_name(const std::string
& name
, Location location
)
2241 return this->package_
->bindings()->add_unknown_name(name
, location
);
2244 // Declare a function.
2247 Gogo::declare_function(const std::string
& name
, Function_type
* type
,
2250 if (!type
->is_method())
2251 return this->current_bindings()->add_function_declaration(name
, NULL
, type
,
2255 // We don't bother to add this to the list of global
2257 Type
* rtype
= type
->receiver()->type();
2259 while (rtype
->named_type() != NULL
2260 && rtype
->named_type()->is_alias())
2261 rtype
= rtype
->named_type()->real_type()->forwarded();
2263 // We want to look through the pointer created by the
2264 // parser, without getting an error if the type is not yet
2266 if (rtype
->classification() == Type::TYPE_POINTER
)
2267 rtype
= rtype
->points_to();
2269 while (rtype
->named_type() != NULL
2270 && rtype
->named_type()->is_alias())
2271 rtype
= rtype
->named_type()->real_type()->forwarded();
2273 if (rtype
->is_error_type())
2275 else if (rtype
->named_type() != NULL
)
2276 return rtype
->named_type()->add_method_declaration(name
, NULL
, type
,
2278 else if (rtype
->forward_declaration_type() != NULL
)
2280 Forward_declaration_type
* ftype
= rtype
->forward_declaration_type();
2281 return ftype
->add_method_declaration(name
, NULL
, type
, location
);
2285 go_error_at(type
->receiver()->location(),
2286 "invalid receiver type (receiver must be a named type)");
2287 return Named_object::make_erroneous_name(name
);
2292 // Add a label definition.
2295 Gogo::add_label_definition(const std::string
& label_name
,
2298 go_assert(!this->functions_
.empty());
2299 Function
* func
= this->functions_
.back().function
->func_value();
2300 Label
* label
= func
->add_label_definition(this, label_name
, location
);
2301 this->add_statement(Statement::make_label_statement(label
, location
));
2305 // Add a label reference.
2308 Gogo::add_label_reference(const std::string
& label_name
,
2309 Location location
, bool issue_goto_errors
)
2311 go_assert(!this->functions_
.empty());
2312 Function
* func
= this->functions_
.back().function
->func_value();
2313 return func
->add_label_reference(this, label_name
, location
,
2317 // Return the current binding state.
2320 Gogo::bindings_snapshot(Location location
)
2322 return new Bindings_snapshot(this->current_block(), location
);
2328 Gogo::add_statement(Statement
* statement
)
2330 go_assert(!this->functions_
.empty()
2331 && !this->functions_
.back().blocks
.empty());
2332 this->functions_
.back().blocks
.back()->add_statement(statement
);
2338 Gogo::add_block(Block
* block
, Location location
)
2340 go_assert(!this->functions_
.empty()
2341 && !this->functions_
.back().blocks
.empty());
2342 Statement
* statement
= Statement::make_block_statement(block
, location
);
2343 this->functions_
.back().blocks
.back()->add_statement(statement
);
2349 Gogo::add_constant(const Typed_identifier
& tid
, Expression
* expr
,
2352 return this->current_bindings()->add_constant(tid
, NULL
, expr
, iota_value
);
2358 Gogo::add_type(const std::string
& name
, Type
* type
, Location location
)
2360 Named_object
* no
= this->current_bindings()->add_type(name
, NULL
, type
,
2362 if (!this->in_global_scope() && no
->is_type())
2364 Named_object
* f
= this->functions_
.back().function
;
2366 if (f
->is_function())
2367 index
= f
->func_value()->new_local_type_index();
2370 no
->type_value()->set_in_function(f
, index
);
2374 // Add a named type.
2377 Gogo::add_named_type(Named_type
* type
)
2379 go_assert(this->in_global_scope());
2380 this->current_bindings()->add_named_type(type
);
2386 Gogo::declare_type(const std::string
& name
, Location location
)
2388 Bindings
* bindings
= this->current_bindings();
2389 Named_object
* no
= bindings
->add_type_declaration(name
, NULL
, location
);
2390 if (!this->in_global_scope() && no
->is_type_declaration())
2392 Named_object
* f
= this->functions_
.back().function
;
2394 if (f
->is_function())
2395 index
= f
->func_value()->new_local_type_index();
2398 no
->type_declaration_value()->set_in_function(f
, index
);
2403 // Declare a type at the package level.
2406 Gogo::declare_package_type(const std::string
& name
, Location location
)
2408 return this->package_
->bindings()->add_type_declaration(name
, NULL
, location
);
2411 // Declare a function at the package level.
2414 Gogo::declare_package_function(const std::string
& name
, Function_type
* type
,
2417 return this->package_
->bindings()->add_function_declaration(name
, NULL
, type
,
2421 // Add a function declaration to the list of functions we may want to
2425 Gogo::add_imported_inlinable_function(Named_object
* no
)
2427 go_assert(no
->is_function_declaration());
2428 Function_declaration
* fd
= no
->func_declaration_value();
2429 if (fd
->is_on_inlinable_list())
2431 this->imported_inlinable_functions_
.push_back(no
);
2432 fd
->set_is_on_inlinable_list();
2435 // Define a type which was already declared.
2438 Gogo::define_type(Named_object
* no
, Named_type
* type
)
2440 this->current_bindings()->define_type(no
, type
);
2446 Gogo::add_variable(const std::string
& name
, Variable
* variable
)
2448 Named_object
* no
= this->current_bindings()->add_variable(name
, NULL
,
2451 // In a function the middle-end wants to see a DECL_EXPR node.
2453 && no
->is_variable()
2454 && !no
->var_value()->is_parameter()
2455 && !this->functions_
.empty())
2456 this->add_statement(Statement::make_variable_declaration(no
));
2462 Gogo::rename_if_empty(std::string
* pname
, const char* tag
, unsigned* count
)
2464 if (pname
->empty() || Gogo::is_sink_name(*pname
))
2467 go_assert(strlen(tag
) < 10);
2468 snprintf(buf
, sizeof buf
, "%s.%u", tag
, *count
);
2475 // Add a sink--a reference to the blank identifier _.
2480 return Named_object::make_sink();
2483 // Add a named object for a dot import.
2486 Gogo::add_dot_import_object(Named_object
* no
)
2488 // If the name already exists, then it was defined in some file seen
2489 // earlier. If the earlier name is just a declaration, don't add
2490 // this name, because that will cause the previous declaration to
2491 // merge to this imported name, which should not happen. Just add
2492 // this name to the list of file block names to get appropriate
2493 // errors if we see a later definition.
2494 Named_object
* e
= this->package_
->bindings()->lookup(no
->name());
2495 if (e
!= NULL
&& e
->package() == NULL
)
2497 if (e
->is_unknown())
2499 if (e
->package() == NULL
2500 && (e
->is_type_declaration()
2501 || e
->is_function_declaration()
2502 || e
->is_unknown()))
2504 this->add_file_block_name(no
->name(), no
->location());
2509 this->current_bindings()->add_named_object(no
);
2512 // Add a linkname. This implements the go:linkname compiler directive.
2513 // We only support this for functions and function declarations.
2516 Gogo::add_linkname(const std::string
& go_name
, bool is_exported
,
2517 const std::string
& ext_name
, Location loc
)
2520 this->package_
->bindings()->lookup(this->pack_hidden_name(go_name
,
2523 go_error_at(loc
, "%s is not defined", go_name
.c_str());
2524 else if (no
->is_function())
2526 if (ext_name
.empty())
2527 no
->func_value()->set_is_exported_by_linkname();
2529 no
->func_value()->set_asm_name(ext_name
);
2531 else if (no
->is_function_declaration())
2533 if (ext_name
.empty())
2535 ("%<//go:linkname%> missing external name "
2536 "for declaration of %s"),
2539 no
->func_declaration_value()->set_asm_name(ext_name
);
2543 ("%s is not a function; "
2544 "%<//go:linkname%> is only supported for functions"),
2548 // Mark all local variables used. This is used when some types of
2549 // parse error occur.
2552 Gogo::mark_locals_used()
2554 for (Open_functions::iterator pf
= this->functions_
.begin();
2555 pf
!= this->functions_
.end();
2558 for (std::vector
<Block
*>::iterator pb
= pf
->blocks
.begin();
2559 pb
!= pf
->blocks
.end();
2561 (*pb
)->bindings()->mark_locals_used();
2565 // Record that we've seen an interface type.
2568 Gogo::record_interface_type(Interface_type
* itype
)
2570 this->interface_types_
.push_back(itype
);
2573 // Define the global names. We do this only after parsing all the
2574 // input files, because the program might define the global names
2578 Gogo::define_global_names()
2580 if (this->is_main_package())
2582 // Every Go program has to import the runtime package, so that
2583 // it is properly initialized. We can't use
2584 // predeclared_location here as it will cause runtime functions
2585 // to appear to be builtin functions.
2586 this->import_package("runtime", "_", false, false,
2587 this->package_
->location());
2590 for (Bindings::const_declarations_iterator p
=
2591 this->globals_
->begin_declarations();
2592 p
!= this->globals_
->end_declarations();
2595 Named_object
* global_no
= p
->second
;
2596 std::string
name(Gogo::pack_hidden_name(global_no
->name(), false));
2597 Named_object
* no
= this->package_
->bindings()->lookup(name
);
2601 if (no
->is_type_declaration())
2603 if (global_no
->is_type())
2605 if (no
->type_declaration_value()->has_methods())
2607 for (std::vector
<Named_object
*>::const_iterator pm
=
2608 no
->type_declaration_value()->methods()->begin();
2609 pm
!= no
->type_declaration_value()->methods()->end();
2611 go_error_at((*pm
)->location(),
2612 "may not define methods on non-local type");
2614 no
->set_type_value(global_no
->type_value());
2618 go_error_at(no
->location(), "expected type");
2619 Type
* errtype
= Type::make_error_type();
2621 Named_object::make_type("erroneous_type", NULL
, errtype
,
2622 Linemap::predeclared_location());
2623 no
->set_type_value(err
->type_value());
2626 else if (no
->is_unknown())
2627 no
->unknown_value()->set_real_named_object(global_no
);
2630 // Give an error if any name is defined in both the package block
2631 // and the file block. For example, this can happen if one file
2632 // imports "fmt" and another file defines a global variable fmt.
2633 for (Bindings::const_declarations_iterator p
=
2634 this->package_
->bindings()->begin_declarations();
2635 p
!= this->package_
->bindings()->end_declarations();
2638 if (p
->second
->is_unknown()
2639 && p
->second
->unknown_value()->real_named_object() == NULL
)
2641 // No point in warning about an undefined name, as we will
2642 // get other errors later anyhow.
2645 File_block_names::const_iterator pf
=
2646 this->file_block_names_
.find(p
->second
->name());
2647 if (pf
!= this->file_block_names_
.end())
2649 std::string n
= p
->second
->message_name();
2650 go_error_at(p
->second
->location(),
2651 "%qs defined as both imported name and global name",
2653 go_inform(pf
->second
, "%qs imported here", n
.c_str());
2656 // No package scope identifier may be named "init".
2657 if (!p
->second
->is_function()
2658 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
2660 go_error_at(p
->second
->location(),
2661 "cannot declare init - must be func");
2666 // Clear out names in file scope.
2669 Gogo::clear_file_scope()
2671 this->package_
->bindings()->clear_file_scope(this);
2673 // Warn about packages which were imported but not used.
2674 bool quiet
= saw_errors();
2675 for (Packages::iterator p
= this->packages_
.begin();
2676 p
!= this->packages_
.end();
2679 Package
* package
= p
->second
;
2680 if (package
!= this->package_
&& !quiet
)
2682 for (Package::Aliases::const_iterator p1
= package
->aliases().begin();
2683 p1
!= package
->aliases().end();
2686 if (!p1
->second
->used())
2688 // Give a more refined error message if the alias name is known.
2689 std::string pkg_name
= package
->package_name();
2690 if (p1
->first
!= pkg_name
&& p1
->first
[0] != '.')
2692 go_error_at(p1
->second
->location(),
2693 "imported and not used: %s as %s",
2694 Gogo::message_name(pkg_name
).c_str(),
2695 Gogo::message_name(p1
->first
).c_str());
2698 go_error_at(p1
->second
->location(),
2699 "imported and not used: %s",
2700 Gogo::message_name(pkg_name
).c_str());
2704 package
->clear_used();
2707 this->current_file_imported_unsafe_
= false;
2708 this->current_file_imported_embed_
= false;
2711 // Queue up a type-specific hash function for later writing. These
2712 // are written out in write_specific_type_functions, called after the
2713 // parse tree is lowered.
2716 Gogo::queue_hash_function(Type
* type
, int64_t size
, Backend_name
* bname
,
2717 Function_type
* hash_fntype
)
2719 go_assert(!this->specific_type_functions_are_written_
);
2720 go_assert(!this->in_global_scope());
2721 Specific_type_function::Specific_type_function_kind kind
=
2722 Specific_type_function::SPECIFIC_HASH
;
2723 Specific_type_function
* tsf
= new Specific_type_function(type
, NULL
, size
,
2726 this->specific_type_functions_
.push_back(tsf
);
2729 // Queue up a type-specific equal function for later writing. These
2730 // are written out in write_specific_type_functions, called after the
2731 // parse tree is lowered.
2734 Gogo::queue_equal_function(Type
* type
, Named_type
* name
, int64_t size
,
2735 Backend_name
* bname
, Function_type
* equal_fntype
)
2737 go_assert(!this->specific_type_functions_are_written_
);
2738 go_assert(!this->in_global_scope());
2739 Specific_type_function::Specific_type_function_kind kind
=
2740 Specific_type_function::SPECIFIC_EQUAL
;
2741 Specific_type_function
* tsf
= new Specific_type_function(type
, name
, size
,
2744 this->specific_type_functions_
.push_back(tsf
);
2747 // Look for types which need specific hash or equality functions.
2749 class Specific_type_functions
: public Traverse
2752 Specific_type_functions(Gogo
* gogo
)
2753 : Traverse(traverse_types
),
2765 Specific_type_functions::type(Type
* t
)
2767 switch (t
->classification())
2769 case Type::TYPE_NAMED
:
2771 Named_type
* nt
= t
->named_type();
2773 return TRAVERSE_CONTINUE
;
2774 if (t
->needs_specific_type_functions(this->gogo_
))
2775 t
->equal_function(this->gogo_
, nt
, NULL
);
2777 // If this is a struct type, we don't want to make functions
2778 // for the unnamed struct.
2779 Type
* rt
= nt
->real_type();
2780 if (rt
->struct_type() == NULL
)
2782 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
2783 return TRAVERSE_EXIT
;
2787 // If this type is defined in another package, then we don't
2788 // need to worry about the unexported fields.
2789 bool is_defined_elsewhere
= nt
->named_object()->package() != NULL
;
2790 const Struct_field_list
* fields
= rt
->struct_type()->fields();
2791 for (Struct_field_list::const_iterator p
= fields
->begin();
2795 if (is_defined_elsewhere
2796 && Gogo::is_hidden_name(p
->field_name()))
2798 if (Type::traverse(p
->type(), this) == TRAVERSE_EXIT
)
2799 return TRAVERSE_EXIT
;
2803 return TRAVERSE_SKIP_COMPONENTS
;
2806 case Type::TYPE_STRUCT
:
2807 case Type::TYPE_ARRAY
:
2808 if (t
->needs_specific_type_functions(this->gogo_
))
2809 t
->equal_function(this->gogo_
, NULL
, NULL
);
2812 case Type::TYPE_MAP
:
2814 Type
* key_type
= t
->map_type()->key_type();
2815 if (key_type
->needs_specific_type_functions(this->gogo_
))
2816 key_type
->hash_function(this->gogo_
, NULL
);
2824 return TRAVERSE_CONTINUE
;
2827 // Write out type specific functions.
2830 Gogo::write_specific_type_functions()
2832 Specific_type_functions
stf(this);
2833 this->traverse(&stf
);
2835 while (!this->specific_type_functions_
.empty())
2837 Specific_type_function
* tsf
= this->specific_type_functions_
.back();
2838 this->specific_type_functions_
.pop_back();
2839 if (tsf
->kind
== Specific_type_function::SPECIFIC_HASH
)
2840 tsf
->type
->write_hash_function(this, tsf
->size
, &tsf
->bname
,
2843 tsf
->type
->write_equal_function(this, tsf
->name
, tsf
->size
,
2844 &tsf
->bname
, tsf
->fntype
);
2847 this->specific_type_functions_are_written_
= true;
2850 // Traverse the tree.
2853 Gogo::traverse(Traverse
* traverse
)
2855 // Traverse the current package first for consistency. The other
2856 // packages will only contain imported types, constants, and
2858 if (this->package_
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2860 for (Packages::const_iterator p
= this->packages_
.begin();
2861 p
!= this->packages_
.end();
2864 if (p
->second
!= this->package_
)
2866 if (p
->second
->bindings()->traverse(traverse
, true) == TRAVERSE_EXIT
)
2872 // Add a type to verify. This is used for types of sink variables, in
2873 // order to give appropriate error messages.
2876 Gogo::add_type_to_verify(Type
* type
)
2878 this->verify_types_
.push_back(type
);
2881 // Traversal class used to verify types.
2883 class Verify_types
: public Traverse
2887 : Traverse(traverse_types
)
2894 // Verify that a type is correct.
2897 Verify_types::type(Type
* t
)
2900 return TRAVERSE_SKIP_COMPONENTS
;
2901 return TRAVERSE_CONTINUE
;
2904 // Verify that all types are correct.
2907 Gogo::verify_types()
2909 Verify_types traverse
;
2910 this->traverse(&traverse
);
2912 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
2913 p
!= this->verify_types_
.end();
2916 this->verify_types_
.clear();
2919 // Traversal class used to lower parse tree.
2921 class Lower_parse_tree
: public Traverse
2924 Lower_parse_tree(Gogo
* gogo
, Named_object
* function
)
2925 : Traverse(traverse_variables
2926 | traverse_constants
2927 | traverse_functions
2928 | traverse_statements
2929 | traverse_expressions
),
2930 gogo_(gogo
), function_(function
), iota_value_(-1), inserter_()
2934 set_inserter(const Statement_inserter
* inserter
)
2935 { this->inserter_
= *inserter
; }
2938 variable(Named_object
*);
2941 constant(Named_object
*, bool);
2944 function(Named_object
*);
2947 statement(Block
*, size_t* pindex
, Statement
*);
2950 expression(Expression
**);
2955 // The function we are traversing.
2956 Named_object
* function_
;
2957 // Value to use for the predeclared constant iota.
2959 // Current statement inserter for use by expressions.
2960 Statement_inserter inserter_
;
2966 Lower_parse_tree::variable(Named_object
* no
)
2968 if (!no
->is_variable())
2969 return TRAVERSE_CONTINUE
;
2971 if (no
->is_variable() && no
->var_value()->is_global())
2973 // Global variables can have loops in their initialization
2974 // expressions. This is handled in lower_init_expression.
2975 no
->var_value()->lower_init_expression(this->gogo_
, this->function_
,
2977 return TRAVERSE_CONTINUE
;
2980 // This is a local variable. We are going to return
2981 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2982 // initialization expression when we reach the variable declaration
2983 // statement. However, that means that we need to traverse the type
2985 if (no
->var_value()->has_type())
2987 Type
* type
= no
->var_value()->type();
2990 if (Type::traverse(type
, this) == TRAVERSE_EXIT
)
2991 return TRAVERSE_EXIT
;
2994 go_assert(!no
->var_value()->has_pre_init());
2996 return TRAVERSE_SKIP_COMPONENTS
;
2999 // Lower constants. We handle constants specially so that we can set
3000 // the right value for the predeclared constant iota. This works in
3001 // conjunction with the way we lower Const_expression objects.
3004 Lower_parse_tree::constant(Named_object
* no
, bool)
3006 Named_constant
* nc
= no
->const_value();
3008 // Don't get into trouble if the constant's initializer expression
3009 // refers to the constant itself.
3011 return TRAVERSE_CONTINUE
;
3014 go_assert(this->iota_value_
== -1);
3015 this->iota_value_
= nc
->iota_value();
3016 nc
->traverse_expression(this);
3017 this->iota_value_
= -1;
3019 nc
->clear_lowering();
3021 // We will traverse the expression a second time, but that will be
3024 return TRAVERSE_CONTINUE
;
3027 // Lower the body of a function, and set the closure type. Record the
3028 // function while lowering it, so that we can pass it down when
3029 // lowering an expression.
3032 Lower_parse_tree::function(Named_object
* no
)
3034 no
->func_value()->set_closure_type();
3036 go_assert(this->function_
== NULL
);
3037 this->function_
= no
;
3038 int t
= no
->func_value()->traverse(this);
3039 this->function_
= NULL
;
3041 if (t
== TRAVERSE_EXIT
)
3043 return TRAVERSE_SKIP_COMPONENTS
;
3046 // Lower statement parse trees.
3049 Lower_parse_tree::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3051 // Because we explicitly traverse the statement's contents
3052 // ourselves, we want to skip block statements here. There is
3053 // nothing to lower in a block statement.
3054 if (sorig
->is_block_statement())
3055 return TRAVERSE_CONTINUE
;
3057 Statement_inserter
hold_inserter(this->inserter_
);
3058 this->inserter_
= Statement_inserter(block
, pindex
);
3060 // Lower the expressions first.
3061 int t
= sorig
->traverse_contents(this);
3062 if (t
== TRAVERSE_EXIT
)
3064 this->inserter_
= hold_inserter
;
3068 // Keep lowering until nothing changes.
3069 Statement
* s
= sorig
;
3072 Statement
* snew
= s
->lower(this->gogo_
, this->function_
, block
,
3077 t
= s
->traverse_contents(this);
3078 if (t
== TRAVERSE_EXIT
)
3080 this->inserter_
= hold_inserter
;
3086 block
->replace_statement(*pindex
, s
);
3088 this->inserter_
= hold_inserter
;
3089 return TRAVERSE_SKIP_COMPONENTS
;
3092 // Lower expression parse trees.
3095 Lower_parse_tree::expression(Expression
** pexpr
)
3097 // We have to lower all subexpressions first, so that we can get
3098 // their type if necessary. This is awkward, because we don't have
3099 // a postorder traversal pass.
3100 if ((*pexpr
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3101 return TRAVERSE_EXIT
;
3102 // Keep lowering until nothing changes.
3105 Expression
* e
= *pexpr
;
3106 Expression
* enew
= e
->lower(this->gogo_
, this->function_
,
3107 &this->inserter_
, this->iota_value_
);
3110 if (enew
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3111 return TRAVERSE_EXIT
;
3115 // Lower the type of this expression before the parent looks at it,
3116 // in case the type contains an array that has expressions in its
3117 // length. Skip an Unknown_expression, as at this point that means
3118 // a composite literal key that does not have a type.
3119 if ((*pexpr
)->unknown_expression() == NULL
)
3120 Type::traverse((*pexpr
)->type(), this);
3122 return TRAVERSE_SKIP_COMPONENTS
;
3125 // Lower the parse tree. This is called after the parse is complete,
3126 // when all names should be resolved.
3129 Gogo::lower_parse_tree()
3131 Lower_parse_tree
lower_parse_tree(this, NULL
);
3132 this->traverse(&lower_parse_tree
);
3134 // If we found any functions defined in other packages that are
3135 // inlinables, import their bodies and turn them into functions.
3137 // Note that as we import inlinable functions we may find more
3138 // inlinable functions, so don't use an iterator.
3139 for (size_t i
= 0; i
< this->imported_inlinable_functions_
.size(); i
++)
3141 Named_object
* no
= this->imported_inlinable_functions_
[i
];
3142 no
->func_declaration_value()->import_function_body(this, no
);
3145 // There might be type definitions that involve expressions such as the
3146 // array length. Make sure to lower these expressions as well. Otherwise,
3147 // errors hidden within a type can introduce unexpected errors into later
3149 for (std::vector
<Type
*>::iterator p
= this->verify_types_
.begin();
3150 p
!= this->verify_types_
.end();
3152 Type::traverse(*p
, &lower_parse_tree
);
3158 Gogo::lower_block(Named_object
* function
, Block
* block
)
3160 Lower_parse_tree
lower_parse_tree(this, function
);
3161 block
->traverse(&lower_parse_tree
);
3164 // Lower an expression. INSERTER may be NULL, in which case the
3165 // expression had better not need to create any temporaries.
3168 Gogo::lower_expression(Named_object
* function
, Statement_inserter
* inserter
,
3171 Lower_parse_tree
lower_parse_tree(this, function
);
3172 if (inserter
!= NULL
)
3173 lower_parse_tree
.set_inserter(inserter
);
3174 lower_parse_tree
.expression(pexpr
);
3177 // Lower a constant. This is called when lowering a reference to a
3178 // constant. We have to make sure that the constant has already been
3182 Gogo::lower_constant(Named_object
* no
)
3184 go_assert(no
->is_const());
3185 Lower_parse_tree
lower(this, NULL
);
3186 lower
.constant(no
, false);
3189 // Make implicit type conversions explicit. Currently only does for
3190 // interface conversions, so the escape analysis can see them and
3193 class Add_conversions
: public Traverse
3197 : Traverse(traverse_statements
3198 | traverse_expressions
)
3202 statement(Block
*, size_t* pindex
, Statement
*);
3205 expression(Expression
**);
3208 // Add explicit conversions in a statement.
3211 Add_conversions::statement(Block
*, size_t*, Statement
* sorig
)
3213 sorig
->add_conversions();
3214 return TRAVERSE_CONTINUE
;
3217 // Add explicit conversions in an expression.
3220 Add_conversions::expression(Expression
** pexpr
)
3222 (*pexpr
)->add_conversions();
3223 return TRAVERSE_CONTINUE
;
3227 Gogo::add_conversions()
3229 Add_conversions add_conversions
;
3230 this->traverse(&add_conversions
);
3234 Gogo::add_conversions_in_block(Block
*b
)
3236 Add_conversions add_conversions
;
3237 b
->traverse(&add_conversions
);
3240 // Traversal class for simple deadcode elimination.
3242 class Remove_deadcode
: public Traverse
3246 : Traverse(traverse_statements
3247 | traverse_expressions
)
3251 statement(Block
*, size_t* pindex
, Statement
*);
3254 expression(Expression
**);
3257 // Remove deadcode in a statement.
3260 Remove_deadcode::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
3262 Location loc
= sorig
->location();
3263 If_statement
* ifs
= sorig
->if_statement();
3266 // Remove the dead branch of an if statement.
3268 if (ifs
->condition()->boolean_constant_value(&bval
))
3272 s
= Statement::make_block_statement(ifs
->then_block(),
3275 if (ifs
->else_block() != NULL
)
3276 s
= Statement::make_block_statement(ifs
->else_block(),
3279 // Make a dummy statement.
3280 s
= Statement::make_statement(Expression::make_boolean(false, loc
),
3283 block
->replace_statement(*pindex
, s
);
3286 return TRAVERSE_CONTINUE
;
3289 // Remove deadcode in an expression.
3292 Remove_deadcode::expression(Expression
** pexpr
)
3294 // Discard the right arm of a shortcut expression of constant value.
3295 Binary_expression
* be
= (*pexpr
)->binary_expression();
3298 && be
->boolean_constant_value(&bval
)
3299 && (be
->op() == OPERATOR_ANDAND
3300 || be
->op() == OPERATOR_OROR
))
3302 *pexpr
= Expression::make_boolean(bval
, be
->location());
3303 Type_context
context(NULL
, false);
3304 (*pexpr
)->determine_type(&context
);
3306 return TRAVERSE_CONTINUE
;
3312 Gogo::remove_deadcode()
3314 Remove_deadcode remove_deadcode
;
3315 this->traverse(&remove_deadcode
);
3318 // Traverse the tree to create function descriptors as needed.
3320 class Create_function_descriptors
: public Traverse
3323 Create_function_descriptors(Gogo
* gogo
)
3324 : Traverse(traverse_functions
| traverse_expressions
),
3329 function(Named_object
*);
3332 expression(Expression
**);
3338 // Create a descriptor for every top-level exported function and every
3339 // function referenced by an inline function.
3342 Create_function_descriptors::function(Named_object
* no
)
3344 if (no
->is_function()
3345 && no
->func_value()->enclosing() == NULL
3346 && !no
->func_value()->is_method()
3347 && ((!Gogo::is_hidden_name(no
->name())
3348 && !Gogo::is_thunk(no
))
3349 || no
->func_value()->is_referenced_by_inline()))
3350 no
->func_value()->descriptor(this->gogo_
, no
);
3352 return TRAVERSE_CONTINUE
;
3355 // If we see a function referenced in any way other than calling it,
3356 // create a descriptor for it.
3359 Create_function_descriptors::expression(Expression
** pexpr
)
3361 Expression
* expr
= *pexpr
;
3363 Func_expression
* fe
= expr
->func_expression();
3366 // We would not get here for a call to this function, so this is
3367 // a reference to a function other than calling it. We need a
3369 if (fe
->closure() != NULL
)
3370 return TRAVERSE_CONTINUE
;
3371 Named_object
* no
= fe
->named_object();
3372 if (no
->is_function() && !no
->func_value()->is_method())
3373 no
->func_value()->descriptor(this->gogo_
, no
);
3374 else if (no
->is_function_declaration()
3375 && !no
->func_declaration_value()->type()->is_method()
3376 && !Linemap::is_predeclared_location(no
->location()))
3377 no
->func_declaration_value()->descriptor(this->gogo_
, no
);
3378 return TRAVERSE_CONTINUE
;
3381 Bound_method_expression
* bme
= expr
->bound_method_expression();
3384 // We would not get here for a call to this method, so this is a
3385 // method value. We need to create a thunk.
3386 Bound_method_expression::create_thunk(this->gogo_
, bme
->method(),
3388 return TRAVERSE_CONTINUE
;
3391 Interface_field_reference_expression
* ifre
=
3392 expr
->interface_field_reference_expression();
3395 // We would not get here for a call to this interface method, so
3396 // this is a method value. We need to create a thunk.
3397 Interface_type
* type
= ifre
->expr()->type()->interface_type();
3399 Interface_field_reference_expression::create_thunk(this->gogo_
, type
,
3401 return TRAVERSE_CONTINUE
;
3404 Call_expression
* ce
= expr
->call_expression();
3407 Expression
* fn
= ce
->fn();
3408 if (fn
->func_expression() != NULL
3409 || fn
->bound_method_expression() != NULL
3410 || fn
->interface_field_reference_expression() != NULL
)
3412 // Traverse the arguments but not the function.
3413 Expression_list
* args
= ce
->args();
3416 if (args
->traverse(this) == TRAVERSE_EXIT
)
3417 return TRAVERSE_EXIT
;
3420 // Traverse the subexpressions of the function, if any.
3421 if (fn
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3422 return TRAVERSE_EXIT
;
3424 return TRAVERSE_SKIP_COMPONENTS
;
3428 return TRAVERSE_CONTINUE
;
3431 // Create function descriptors as needed. We need a function
3432 // descriptor for all exported functions and for all functions that
3433 // are referenced without being called.
3436 Gogo::create_function_descriptors()
3438 // Create a function descriptor for any exported function that is
3439 // declared in this package. This is so that we have a descriptor
3440 // for functions written in assembly. Gather the descriptors first
3441 // so that we don't add declarations while looping over them.
3442 std::vector
<Named_object
*> fndecls
;
3443 Bindings
* b
= this->package_
->bindings();
3444 for (Bindings::const_declarations_iterator p
= b
->begin_declarations();
3445 p
!= b
->end_declarations();
3448 Named_object
* no
= p
->second
;
3449 if (no
->is_function_declaration()
3450 && !no
->func_declaration_value()->type()->is_method()
3451 && !Linemap::is_predeclared_location(no
->location())
3452 && !Gogo::is_hidden_name(no
->name()))
3453 fndecls
.push_back(no
);
3455 for (std::vector
<Named_object
*>::const_iterator p
= fndecls
.begin();
3458 (*p
)->func_declaration_value()->descriptor(this, *p
);
3461 Create_function_descriptors
cfd(this);
3462 this->traverse(&cfd
);
3465 // Finalize the methods of an interface type.
3468 Finalize_methods::type(Type
* t
)
3470 // Check the classification so that we don't finalize the methods
3471 // twice for a named interface type.
3472 switch (t
->classification())
3474 case Type::TYPE_INTERFACE
:
3475 t
->interface_type()->finalize_methods();
3478 case Type::TYPE_NAMED
:
3480 Named_type
* nt
= t
->named_type();
3483 return TRAVERSE_CONTINUE
;
3485 Type
* rt
= nt
->real_type();
3486 if (rt
->classification() != Type::TYPE_STRUCT
)
3488 // Finalize the methods of the real type first.
3489 if (Type::traverse(rt
, this) == TRAVERSE_EXIT
)
3490 return TRAVERSE_EXIT
;
3492 // Finalize the methods of this type.
3493 nt
->finalize_methods(this->gogo_
);
3497 // We don't want to finalize the methods of a named struct
3498 // type, as the methods should be attached to the named
3499 // type, not the struct type. We just want to finalize
3502 // It is possible that a field type refers indirectly to
3503 // this type, such as via a field with function type with
3504 // an argument or result whose type is this type. To
3505 // avoid the cycle, first finalize the methods of any
3506 // embedded types, which are the only types we need to
3507 // know to finalize the methods of this type.
3508 const Struct_field_list
* fields
= rt
->struct_type()->fields();
3511 for (Struct_field_list::const_iterator pf
= fields
->begin();
3512 pf
!= fields
->end();
3515 if (pf
->is_anonymous())
3517 if (Type::traverse(pf
->type(), this) == TRAVERSE_EXIT
)
3518 return TRAVERSE_EXIT
;
3523 // Finalize the methods of this type.
3524 nt
->finalize_methods(this->gogo_
);
3526 // Finalize all the struct fields.
3527 if (rt
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3528 return TRAVERSE_EXIT
;
3531 // If this type is defined in a different package, then finalize the
3532 // types of all the methods, since we won't see them otherwise.
3533 if (nt
->named_object()->package() != NULL
&& nt
->has_any_methods())
3535 const Methods
* methods
= nt
->methods();
3536 for (Methods::const_iterator p
= methods
->begin();
3537 p
!= methods
->end();
3540 if (Type::traverse(p
->second
->type(), this) == TRAVERSE_EXIT
)
3541 return TRAVERSE_EXIT
;
3545 // Finalize the types of all methods that are declared but not
3546 // defined, since we won't see the declarations otherwise.
3547 if (nt
->named_object()->package() == NULL
3548 && nt
->local_methods() != NULL
)
3550 const Bindings
* methods
= nt
->local_methods();
3551 for (Bindings::const_declarations_iterator p
=
3552 methods
->begin_declarations();
3553 p
!= methods
->end_declarations();
3556 if (p
->second
->is_function_declaration())
3558 Type
* mt
= p
->second
->func_declaration_value()->type();
3559 if (Type::traverse(mt
, this) == TRAVERSE_EXIT
)
3560 return TRAVERSE_EXIT
;
3565 return TRAVERSE_SKIP_COMPONENTS
;
3568 case Type::TYPE_STRUCT
:
3569 // Traverse the field types first in case there is an embedded
3570 // field with methods that the struct should inherit.
3571 if (t
->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT
)
3572 return TRAVERSE_EXIT
;
3573 t
->struct_type()->finalize_methods(this->gogo_
);
3574 return TRAVERSE_SKIP_COMPONENTS
;
3580 return TRAVERSE_CONTINUE
;
3583 // Finalize method lists and build stub methods for types.
3586 Gogo::finalize_methods()
3588 Finalize_methods
finalize(this);
3589 this->traverse(&finalize
);
3592 // Finalize the method list for a type. This is called when a type is
3593 // parsed for an inlined function body, which happens after the
3594 // finalize_methods pass.
3597 Gogo::finalize_methods_for_type(Type
* type
)
3599 Finalize_methods
finalize(this);
3600 Type::traverse(type
, &finalize
);
3603 // Set types for unspecified variables and constants.
3606 Gogo::determine_types()
3608 Bindings
* bindings
= this->current_bindings();
3609 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
3610 p
!= bindings
->end_definitions();
3613 if ((*p
)->is_function())
3614 (*p
)->func_value()->determine_types();
3615 else if ((*p
)->is_variable())
3616 (*p
)->var_value()->determine_type();
3617 else if ((*p
)->is_const())
3618 (*p
)->const_value()->determine_type();
3620 // See if a variable requires us to build an initialization
3621 // function. We know that we will see all global variables
3623 if (!this->need_init_fn_
&& (*p
)->is_variable())
3625 Variable
* variable
= (*p
)->var_value();
3627 // If this is a global variable which requires runtime
3628 // initialization, we need an initialization function.
3629 if (!variable
->is_global())
3631 else if (variable
->init() == NULL
)
3633 else if (variable
->type()->interface_type() != NULL
)
3634 this->need_init_fn_
= true;
3635 else if (variable
->init()->is_constant())
3637 else if (!variable
->init()->is_composite_literal())
3638 this->need_init_fn_
= true;
3639 else if (variable
->init()->is_nonconstant_composite_literal())
3640 this->need_init_fn_
= true;
3642 // If this is a global variable which holds a pointer value,
3643 // then we need an initialization function to register it as a
3645 if (variable
->is_global() && variable
->type()->has_pointer())
3646 this->need_init_fn_
= true;
3650 // Determine the types of constants in packages.
3651 for (Packages::const_iterator p
= this->packages_
.begin();
3652 p
!= this->packages_
.end();
3654 p
->second
->determine_types();
3657 // Traversal class used for type checking.
3659 class Check_types_traverse
: public Traverse
3662 Check_types_traverse(Gogo
* gogo
)
3663 : Traverse(traverse_variables
3664 | traverse_constants
3665 | traverse_functions
3666 | traverse_statements
3667 | traverse_expressions
),
3672 variable(Named_object
*);
3675 constant(Named_object
*, bool);
3678 function(Named_object
*);
3681 statement(Block
*, size_t* pindex
, Statement
*);
3684 expression(Expression
**);
3691 // Check that a variable initializer has the right type.
3694 Check_types_traverse::variable(Named_object
* named_object
)
3696 if (named_object
->is_variable())
3698 Variable
* var
= named_object
->var_value();
3700 // Give error if variable type is not defined.
3701 var
->type()->base();
3703 Expression
* init
= var
->init();
3706 && !Type::are_assignable(var
->type(), init
->type(), &reason
))
3709 go_error_at(var
->location(), "incompatible type in initialization");
3711 go_error_at(var
->location(),
3712 "incompatible type in initialization (%s)",
3714 init
= Expression::make_error(named_object
->location());
3717 else if (init
!= NULL
3718 && init
->func_expression() != NULL
)
3720 Named_object
* no
= init
->func_expression()->named_object();
3721 Function_type
* fntype
;
3722 if (no
->is_function())
3723 fntype
= no
->func_value()->type();
3724 else if (no
->is_function_declaration())
3725 fntype
= no
->func_declaration_value()->type();
3729 // Builtin functions cannot be used as function values for variable
3731 if (fntype
->is_builtin())
3733 go_error_at(init
->location(),
3734 "invalid use of special built-in function %qs; "
3736 no
->message_name().c_str());
3740 && !var
->is_global()
3741 && !var
->is_parameter()
3742 && !var
->is_receiver()
3743 && !var
->type()->is_error()
3744 && (init
== NULL
|| !init
->is_error_expression())
3745 && !Lex::is_invalid_identifier(named_object
->name()))
3746 go_error_at(var
->location(), "%qs declared but not used",
3747 named_object
->message_name().c_str());
3749 return TRAVERSE_CONTINUE
;
3752 // Check that a constant initializer has the right type.
3755 Check_types_traverse::constant(Named_object
* named_object
, bool)
3757 Named_constant
* constant
= named_object
->const_value();
3758 Type
* ctype
= constant
->type();
3759 if (ctype
->integer_type() == NULL
3760 && ctype
->float_type() == NULL
3761 && ctype
->complex_type() == NULL
3762 && !ctype
->is_boolean_type()
3763 && !ctype
->is_string_type())
3765 if (ctype
->is_nil_type())
3766 go_error_at(constant
->location(), "const initializer cannot be nil");
3767 else if (!ctype
->is_error())
3768 go_error_at(constant
->location(), "invalid constant type");
3769 constant
->set_error();
3771 else if (!constant
->expr()->is_constant())
3773 go_error_at(constant
->expr()->location(), "expression is not constant");
3774 constant
->set_error();
3776 else if (!Type::are_assignable(constant
->type(), constant
->expr()->type(),
3779 go_error_at(constant
->location(),
3780 "initialization expression has wrong type");
3781 constant
->set_error();
3783 return TRAVERSE_CONTINUE
;
3786 // There are no types to check in a function, but this is where we
3787 // issue warnings about labels which are defined but not referenced.
3790 Check_types_traverse::function(Named_object
* no
)
3792 no
->func_value()->check_labels();
3793 return TRAVERSE_CONTINUE
;
3796 // Check that types are valid in a statement.
3799 Check_types_traverse::statement(Block
*, size_t*, Statement
* s
)
3801 s
->check_types(this->gogo_
);
3802 return TRAVERSE_CONTINUE
;
3805 // Check that types are valid in an expression.
3808 Check_types_traverse::expression(Expression
** expr
)
3810 (*expr
)->check_types(this->gogo_
);
3811 return TRAVERSE_CONTINUE
;
3814 // Check that types are valid.
3819 Check_types_traverse
traverse(this);
3820 this->traverse(&traverse
);
3822 Bindings
* bindings
= this->current_bindings();
3823 for (Bindings::const_declarations_iterator p
= bindings
->begin_declarations();
3824 p
!= bindings
->end_declarations();
3827 // Also check the types in a function declaration's signature.
3828 Named_object
* no
= p
->second
;
3829 if (no
->is_function_declaration())
3830 no
->func_declaration_value()->check_types();
3834 // Check the types in a single block.
3837 Gogo::check_types_in_block(Block
* block
)
3839 Check_types_traverse
traverse(this);
3840 block
->traverse(&traverse
);
3843 // A traversal class which finds all the expressions which must be
3844 // evaluated in order within a statement or larger expression. This
3845 // is used to implement the rules about order of evaluation.
3847 class Find_eval_ordering
: public Traverse
3850 typedef std::vector
<Expression
**> Expression_pointers
;
3853 Find_eval_ordering()
3854 : Traverse(traverse_blocks
3855 | traverse_statements
3856 | traverse_expressions
),
3862 { return this->exprs_
.size(); }
3864 typedef Expression_pointers::const_iterator const_iterator
;
3868 { return this->exprs_
.begin(); }
3872 { return this->exprs_
.end(); }
3877 { return TRAVERSE_SKIP_COMPONENTS
; }
3880 statement(Block
*, size_t*, Statement
*)
3881 { return TRAVERSE_SKIP_COMPONENTS
; }
3884 expression(Expression
**);
3887 // A list of pointers to expressions with side-effects.
3888 Expression_pointers exprs_
;
3891 // If an expression must be evaluated in order, put it on the list.
3894 Find_eval_ordering::expression(Expression
** expression_pointer
)
3896 Binary_expression
* binexp
= (*expression_pointer
)->binary_expression();
3898 && (binexp
->op() == OPERATOR_ANDAND
|| binexp
->op() == OPERATOR_OROR
))
3900 // Shortcut expressions may potentially have side effects which need
3901 // to be ordered, so add them to the list.
3902 // We don't order its subexpressions here since they may be evaluated
3903 // conditionally. This is handled in remove_shortcuts.
3904 this->exprs_
.push_back(expression_pointer
);
3905 return TRAVERSE_SKIP_COMPONENTS
;
3908 // We have to look at subexpressions before this one.
3909 if ((*expression_pointer
)->traverse_subexpressions(this) == TRAVERSE_EXIT
)
3910 return TRAVERSE_EXIT
;
3911 if ((*expression_pointer
)->must_eval_in_order())
3912 this->exprs_
.push_back(expression_pointer
);
3913 return TRAVERSE_SKIP_COMPONENTS
;
3916 // A traversal class for ordering evaluations.
3918 class Order_eval
: public Traverse
3921 Order_eval(Gogo
* gogo
)
3922 : Traverse(traverse_variables
3923 | traverse_statements
),
3928 variable(Named_object
*);
3931 statement(Block
*, size_t*, Statement
*);
3938 // Implement the order of evaluation rules for a statement.
3941 Order_eval::statement(Block
* block
, size_t* pindex
, Statement
* stmt
)
3943 // FIXME: This approach doesn't work for switch statements, because
3944 // we add the new statements before the whole switch when we need to
3945 // instead add them just before the switch expression. The right
3946 // fix is probably to lower switch statements with nonconstant cases
3947 // to a series of conditionals.
3948 if (stmt
->switch_statement() != NULL
)
3949 return TRAVERSE_CONTINUE
;
3951 Find_eval_ordering find_eval_ordering
;
3953 // If S is a variable declaration, then ordinary traversal won't do
3954 // anything. We want to explicitly traverse the initialization
3955 // expression if there is one.
3956 Variable_declaration_statement
* vds
= stmt
->variable_declaration_statement();
3957 Expression
* init
= NULL
;
3958 Expression
* orig_init
= NULL
;
3960 stmt
->traverse_contents(&find_eval_ordering
);
3963 init
= vds
->var()->var_value()->init();
3965 return TRAVERSE_CONTINUE
;
3968 // It might seem that this could be
3969 // init->traverse_subexpressions. Unfortunately that can fail
3972 // newvar, err := call(arg())
3973 // Here newvar will have an init of call result 0 of
3974 // call(arg()). If we only traverse subexpressions, we will
3975 // only find arg(), and we won't bother to move anything out.
3976 // Then we get to the assignment to err, we will traverse the
3977 // whole statement, and this time we will find both call() and
3978 // arg(), and so we will move them out. This will cause them to
3979 // be put into temporary variables before the assignment to err
3980 // but after the declaration of newvar. To avoid that problem,
3981 // we traverse the entire expression here.
3982 Expression::traverse(&init
, &find_eval_ordering
);
3985 size_t c
= find_eval_ordering
.size();
3987 return TRAVERSE_CONTINUE
;
3989 // If there is only one expression with a side-effect, we can
3990 // usually leave it in place.
3993 switch (stmt
->classification())
3995 case Statement::STATEMENT_ASSIGNMENT
:
3996 // For an assignment statement, we need to evaluate an
3997 // expression on the right hand side before we evaluate any
3998 // index expression on the left hand side, so for that case
3999 // we always move the expression. Otherwise we mishandle
4000 // m[0] = len(m) where m is a map.
4003 case Statement::STATEMENT_EXPRESSION
:
4005 // If this is a call statement that doesn't return any
4006 // values, it will not have been counted as a value to
4007 // move. We need to move any subexpressions in case they
4008 // are themselves call statements that require passing a
4010 Expression
* expr
= stmt
->expression_statement()->expr();
4011 if (expr
->call_expression() != NULL
4012 && expr
->call_expression()->result_count() == 0)
4014 return TRAVERSE_CONTINUE
;
4018 // We can leave the expression in place.
4019 return TRAVERSE_CONTINUE
;
4023 bool is_thunk
= stmt
->thunk_statement() != NULL
;
4024 Expression_statement
* es
= stmt
->expression_statement();
4025 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4026 p
!= find_eval_ordering
.end();
4029 Expression
** pexpr
= *p
;
4031 // The last expression in a thunk will be the call passed to go
4032 // or defer, which we must not evaluate early.
4033 if (is_thunk
&& p
+ 1 == find_eval_ordering
.end())
4036 Location loc
= (*pexpr
)->location();
4038 if ((*pexpr
)->call_expression() == NULL
4039 || (*pexpr
)->call_expression()->result_count() < 2)
4041 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4044 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4048 // A call expression which returns multiple results needs to
4049 // be handled specially. We can't create a temporary
4050 // because there is no type to give it. Any actual uses of
4051 // the values will be done via Call_result_expressions.
4053 // Since a given call expression can be shared by multiple
4054 // Call_result_expressions, avoid hoisting the call the
4055 // second time we see it here. In addition, don't try to
4056 // hoist the top-level multi-return call in the statement,
4057 // since doing this would result a tree with more than one copy
4059 if (this->remember_expression(*pexpr
))
4061 else if (es
!= NULL
&& *pexpr
== es
->expr())
4064 s
= Statement::make_statement(*pexpr
, true);
4069 block
->insert_statement_before(*pindex
, s
);
4074 if (init
!= orig_init
)
4075 vds
->var()->var_value()->set_init(init
);
4077 return TRAVERSE_CONTINUE
;
4080 // Implement the order of evaluation rules for the initializer of a
4084 Order_eval::variable(Named_object
* no
)
4086 if (no
->is_result_variable())
4087 return TRAVERSE_CONTINUE
;
4088 Variable
* var
= no
->var_value();
4089 Expression
* init
= var
->init();
4090 if (!var
->is_global() || init
== NULL
)
4091 return TRAVERSE_CONTINUE
;
4093 Find_eval_ordering find_eval_ordering
;
4094 Expression::traverse(&init
, &find_eval_ordering
);
4096 if (find_eval_ordering
.size() <= 1)
4098 // If there is only one expression with a side-effect, we can
4099 // leave it in place.
4100 return TRAVERSE_SKIP_COMPONENTS
;
4103 Expression
* orig_init
= init
;
4105 for (Find_eval_ordering::const_iterator p
= find_eval_ordering
.begin();
4106 p
!= find_eval_ordering
.end();
4109 Expression
** pexpr
= *p
;
4110 Location loc
= (*pexpr
)->location();
4112 if ((*pexpr
)->call_expression() == NULL
4113 || (*pexpr
)->call_expression()->result_count() < 2)
4115 Temporary_statement
* ts
= Statement::make_temporary(NULL
, *pexpr
,
4118 *pexpr
= Expression::make_temporary_reference(ts
, loc
);
4122 // A call expression which returns multiple results needs to
4123 // be handled specially.
4124 s
= Statement::make_statement(*pexpr
, true);
4126 var
->add_preinit_statement(this->gogo_
, s
);
4129 if (init
!= orig_init
)
4130 var
->set_init(init
);
4132 return TRAVERSE_SKIP_COMPONENTS
;
4135 // Use temporary variables to implement the order of evaluation rules.
4138 Gogo::order_evaluations()
4140 Order_eval
order_eval(this);
4141 this->traverse(&order_eval
);
4144 // Order evaluations in a block.
4147 Gogo::order_block(Block
* block
)
4149 Order_eval
order_eval(this);
4150 block
->traverse(&order_eval
);
4153 // A traversal class used to find a single shortcut operator within an
4156 class Find_shortcut
: public Traverse
4160 : Traverse(traverse_blocks
4161 | traverse_statements
4162 | traverse_expressions
),
4166 // A pointer to the expression which was found, or NULL if none was
4170 { return this->found_
; }
4175 { return TRAVERSE_SKIP_COMPONENTS
; }
4178 statement(Block
*, size_t*, Statement
*)
4179 { return TRAVERSE_SKIP_COMPONENTS
; }
4182 expression(Expression
**);
4185 Expression
** found_
;
4188 // Find a shortcut expression.
4191 Find_shortcut::expression(Expression
** pexpr
)
4193 Expression
* expr
= *pexpr
;
4194 Binary_expression
* be
= expr
->binary_expression();
4196 return TRAVERSE_CONTINUE
;
4197 Operator op
= be
->op();
4198 if (op
!= OPERATOR_OROR
&& op
!= OPERATOR_ANDAND
)
4199 return TRAVERSE_CONTINUE
;
4200 go_assert(this->found_
== NULL
);
4201 this->found_
= pexpr
;
4202 return TRAVERSE_EXIT
;
4205 // A traversal class used to turn shortcut operators into explicit if
4208 class Shortcuts
: public Traverse
4211 Shortcuts(Gogo
* gogo
)
4212 : Traverse(traverse_variables
4213 | traverse_statements
),
4219 variable(Named_object
*);
4222 statement(Block
*, size_t*, Statement
*);
4225 // Convert a shortcut operator.
4227 convert_shortcut(Block
* enclosing
, Expression
** pshortcut
);
4233 // Remove shortcut operators in a single statement.
4236 Shortcuts::statement(Block
* block
, size_t* pindex
, Statement
* s
)
4238 // FIXME: This approach doesn't work for switch statements, because
4239 // we add the new statements before the whole switch when we need to
4240 // instead add them just before the switch expression. The right
4241 // fix is probably to lower switch statements with nonconstant cases
4242 // to a series of conditionals.
4243 if (s
->switch_statement() != NULL
)
4244 return TRAVERSE_CONTINUE
;
4248 Find_shortcut find_shortcut
;
4250 // If S is a variable declaration, then ordinary traversal won't
4251 // do anything. We want to explicitly traverse the
4252 // initialization expression if there is one.
4253 Variable_declaration_statement
* vds
= s
->variable_declaration_statement();
4254 Expression
* init
= NULL
;
4256 s
->traverse_contents(&find_shortcut
);
4259 init
= vds
->var()->var_value()->init();
4261 return TRAVERSE_CONTINUE
;
4262 init
->traverse(&init
, &find_shortcut
);
4264 Expression
** pshortcut
= find_shortcut
.found();
4265 if (pshortcut
== NULL
)
4266 return TRAVERSE_CONTINUE
;
4268 Statement
* snew
= this->convert_shortcut(block
, pshortcut
);
4269 block
->insert_statement_before(*pindex
, snew
);
4272 if (pshortcut
== &init
)
4273 vds
->var()->var_value()->set_init(init
);
4277 // Remove shortcut operators in the initializer of a global variable.
4280 Shortcuts::variable(Named_object
* no
)
4282 if (no
->is_result_variable())
4283 return TRAVERSE_CONTINUE
;
4284 Variable
* var
= no
->var_value();
4285 Expression
* init
= var
->init();
4286 if (!var
->is_global() || init
== NULL
)
4287 return TRAVERSE_CONTINUE
;
4291 Find_shortcut find_shortcut
;
4292 init
->traverse(&init
, &find_shortcut
);
4293 Expression
** pshortcut
= find_shortcut
.found();
4294 if (pshortcut
== NULL
)
4295 return TRAVERSE_CONTINUE
;
4297 Statement
* snew
= this->convert_shortcut(NULL
, pshortcut
);
4298 var
->add_preinit_statement(this->gogo_
, snew
);
4299 if (pshortcut
== &init
)
4300 var
->set_init(init
);
4304 // Given an expression which uses a shortcut operator, return a
4305 // statement which implements it, and update *PSHORTCUT accordingly.
4308 Shortcuts::convert_shortcut(Block
* enclosing
, Expression
** pshortcut
)
4310 Binary_expression
* shortcut
= (*pshortcut
)->binary_expression();
4311 Expression
* left
= shortcut
->left();
4312 Expression
* right
= shortcut
->right();
4313 Location loc
= shortcut
->location();
4315 Block
* retblock
= new Block(enclosing
, loc
);
4316 retblock
->set_end_location(loc
);
4318 Temporary_statement
* ts
= Statement::make_temporary(shortcut
->type(),
4320 retblock
->add_statement(ts
);
4322 Block
* block
= new Block(retblock
, loc
);
4323 block
->set_end_location(loc
);
4324 Expression
* tmpref
= Expression::make_temporary_reference(ts
, loc
);
4325 Statement
* assign
= Statement::make_assignment(tmpref
, right
, loc
);
4326 block
->add_statement(assign
);
4328 Expression
* cond
= Expression::make_temporary_reference(ts
, loc
);
4329 if (shortcut
->binary_expression()->op() == OPERATOR_OROR
)
4330 cond
= Expression::make_unary(OPERATOR_NOT
, cond
, loc
);
4332 Statement
* if_statement
= Statement::make_if_statement(cond
, block
, NULL
,
4334 retblock
->add_statement(if_statement
);
4336 *pshortcut
= Expression::make_temporary_reference(ts
, loc
);
4340 // Now convert any shortcut operators in LEFT and RIGHT.
4341 // LEFT and RIGHT were skipped in the top level
4342 // Gogo::order_evaluations. We need to order their
4343 // components first.
4344 Order_eval
order_eval(this->gogo_
);
4345 retblock
->traverse(&order_eval
);
4346 Shortcuts
shortcuts(this->gogo_
);
4347 retblock
->traverse(&shortcuts
);
4349 return Statement::make_block_statement(retblock
, loc
);
4352 // Turn shortcut operators into explicit if statements. Doing this
4353 // considerably simplifies the order of evaluation rules.
4356 Gogo::remove_shortcuts()
4358 Shortcuts
shortcuts(this);
4359 this->traverse(&shortcuts
);
4362 // Turn shortcut operators into explicit if statements in a block.
4365 Gogo::remove_shortcuts_in_block(Block
* block
)
4367 Shortcuts
shortcuts(this);
4368 block
->traverse(&shortcuts
);
4371 // Traversal to flatten parse tree after order of evaluation rules are applied.
4373 class Flatten
: public Traverse
4376 Flatten(Gogo
* gogo
, Named_object
* function
)
4377 : Traverse(traverse_variables
4378 | traverse_functions
4379 | traverse_statements
4380 | traverse_expressions
),
4381 gogo_(gogo
), function_(function
), inserter_()
4385 set_inserter(const Statement_inserter
* inserter
)
4386 { this->inserter_
= *inserter
; }
4389 variable(Named_object
*);
4392 function(Named_object
*);
4395 statement(Block
*, size_t* pindex
, Statement
*);
4398 expression(Expression
**);
4403 // The function we are traversing.
4404 Named_object
* function_
;
4405 // Current statement inserter for use by expressions.
4406 Statement_inserter inserter_
;
4409 // Flatten variables.
4412 Flatten::variable(Named_object
* no
)
4414 if (!no
->is_variable())
4415 return TRAVERSE_CONTINUE
;
4417 if (no
->is_variable() && no
->var_value()->is_global())
4419 // Global variables can have loops in their initialization
4420 // expressions. This is handled in flatten_init_expression.
4421 no
->var_value()->flatten_init_expression(this->gogo_
, this->function_
,
4423 return TRAVERSE_CONTINUE
;
4426 if (!no
->var_value()->is_parameter()
4427 && !no
->var_value()->is_receiver()
4428 && !no
->var_value()->is_closure()
4429 && no
->var_value()->is_non_escaping_address_taken()
4430 && !no
->var_value()->is_in_heap()
4431 && no
->var_value()->toplevel_decl() == NULL
)
4433 // Local variable that has address taken but not escape.
4434 // It needs to be live beyond its lexical scope. So we
4435 // create a top-level declaration for it.
4436 // No need to do it if it is already in the top level.
4437 Block
* top_block
= function_
->func_value()->block();
4438 if (top_block
->bindings()->lookup_local(no
->name()) != no
)
4440 Variable
* var
= no
->var_value();
4441 Temporary_statement
* ts
=
4442 Statement::make_temporary(var
->type(), NULL
, var
->location());
4443 ts
->set_is_address_taken();
4444 top_block
->add_statement_at_front(ts
);
4445 var
->set_toplevel_decl(ts
);
4449 go_assert(!no
->var_value()->has_pre_init());
4451 return TRAVERSE_SKIP_COMPONENTS
;
4454 // Flatten the body of a function. Record the function while flattening it,
4455 // so that we can pass it down when flattening an expression.
4458 Flatten::function(Named_object
* no
)
4460 go_assert(this->function_
== NULL
);
4461 this->function_
= no
;
4462 int t
= no
->func_value()->traverse(this);
4463 this->function_
= NULL
;
4465 if (t
== TRAVERSE_EXIT
)
4467 return TRAVERSE_SKIP_COMPONENTS
;
4470 // Flatten statement parse trees.
4473 Flatten::statement(Block
* block
, size_t* pindex
, Statement
* sorig
)
4475 // Because we explicitly traverse the statement's contents
4476 // ourselves, we want to skip block statements here. There is
4477 // nothing to flatten in a block statement.
4478 if (sorig
->is_block_statement())
4479 return TRAVERSE_CONTINUE
;
4481 Statement_inserter
hold_inserter(this->inserter_
);
4482 this->inserter_
= Statement_inserter(block
, pindex
);
4484 // Flatten the expressions first.
4485 int t
= sorig
->traverse_contents(this);
4486 if (t
== TRAVERSE_EXIT
)
4488 this->inserter_
= hold_inserter
;
4492 // Keep flattening until nothing changes.
4493 Statement
* s
= sorig
;
4496 Statement
* snew
= s
->flatten(this->gogo_
, this->function_
, block
,
4501 t
= s
->traverse_contents(this);
4502 if (t
== TRAVERSE_EXIT
)
4504 this->inserter_
= hold_inserter
;
4510 block
->replace_statement(*pindex
, s
);
4512 this->inserter_
= hold_inserter
;
4513 return TRAVERSE_SKIP_COMPONENTS
;
4516 // Flatten expression parse trees.
4519 Flatten::expression(Expression
** pexpr
)
4521 // Keep flattening until nothing changes.
4524 Expression
* e
= *pexpr
;
4525 if (e
->traverse_subexpressions(this) == TRAVERSE_EXIT
)
4526 return TRAVERSE_EXIT
;
4528 Expression
* enew
= e
->flatten(this->gogo_
, this->function_
,
4534 return TRAVERSE_SKIP_COMPONENTS
;
4540 Gogo::flatten_block(Named_object
* function
, Block
* block
)
4542 Flatten
flatten(this, function
);
4543 block
->traverse(&flatten
);
4546 // Flatten an expression. INSERTER may be NULL, in which case the
4547 // expression had better not need to create any temporaries.
4550 Gogo::flatten_expression(Named_object
* function
, Statement_inserter
* inserter
,
4553 Flatten
flatten(this, function
);
4554 if (inserter
!= NULL
)
4555 flatten
.set_inserter(inserter
);
4556 flatten
.expression(pexpr
);
4562 Flatten
flatten(this, NULL
);
4563 this->traverse(&flatten
);
4566 // Traversal to convert calls to the predeclared recover function to
4567 // pass in an argument indicating whether it can recover from a panic
4570 class Convert_recover
: public Traverse
4573 Convert_recover(Named_object
* arg
)
4574 : Traverse(traverse_expressions
),
4580 expression(Expression
**);
4583 // The argument to pass to the function.
4587 // Convert calls to recover.
4590 Convert_recover::expression(Expression
** pp
)
4592 Call_expression
* ce
= (*pp
)->call_expression();
4593 if (ce
!= NULL
&& ce
->is_recover_call())
4594 ce
->set_recover_arg(Expression::make_var_reference(this->arg_
,
4596 return TRAVERSE_CONTINUE
;
4599 // Traversal for build_recover_thunks.
4601 class Build_recover_thunks
: public Traverse
4604 Build_recover_thunks(Gogo
* gogo
)
4605 : Traverse(traverse_functions
),
4610 function(Named_object
*);
4614 can_recover_arg(Location
);
4620 // If this function calls recover, turn it into a thunk.
4623 Build_recover_thunks::function(Named_object
* orig_no
)
4625 Function
* orig_func
= orig_no
->func_value();
4626 if (!orig_func
->calls_recover()
4627 || orig_func
->is_recover_thunk()
4628 || orig_func
->has_recover_thunk())
4629 return TRAVERSE_CONTINUE
;
4631 Gogo
* gogo
= this->gogo_
;
4632 Location location
= orig_func
->location();
4637 Function_type
* orig_fntype
= orig_func
->type();
4638 Typed_identifier_list
* new_params
= new Typed_identifier_list();
4639 std::string receiver_name
;
4640 if (orig_fntype
->is_method())
4642 const Typed_identifier
* receiver
= orig_fntype
->receiver();
4643 snprintf(buf
, sizeof buf
, "rt.%u", count
);
4645 receiver_name
= buf
;
4646 new_params
->push_back(Typed_identifier(receiver_name
, receiver
->type(),
4647 receiver
->location()));
4649 const Typed_identifier_list
* orig_params
= orig_fntype
->parameters();
4650 if (orig_params
!= NULL
&& !orig_params
->empty())
4652 for (Typed_identifier_list::const_iterator p
= orig_params
->begin();
4653 p
!= orig_params
->end();
4656 snprintf(buf
, sizeof buf
, "pt.%u", count
);
4658 new_params
->push_back(Typed_identifier(buf
, p
->type(),
4662 snprintf(buf
, sizeof buf
, "pr.%u", count
);
4664 std::string can_recover_name
= buf
;
4665 new_params
->push_back(Typed_identifier(can_recover_name
,
4666 Type::lookup_bool_type(),
4667 orig_fntype
->location()));
4669 const Typed_identifier_list
* orig_results
= orig_fntype
->results();
4670 Typed_identifier_list
* new_results
;
4671 if (orig_results
== NULL
|| orig_results
->empty())
4675 new_results
= new Typed_identifier_list();
4676 for (Typed_identifier_list::const_iterator p
= orig_results
->begin();
4677 p
!= orig_results
->end();
4679 new_results
->push_back(Typed_identifier("", p
->type(), p
->location()));
4682 Function_type
*new_fntype
= Type::make_function_type(NULL
, new_params
,
4684 orig_fntype
->location());
4685 if (orig_fntype
->is_varargs())
4686 new_fntype
->set_is_varargs();
4689 if (orig_fntype
->is_method())
4690 rtype
= orig_fntype
->receiver()->type();
4691 std::string
name(gogo
->recover_thunk_name(orig_no
->name(), rtype
));
4692 Named_object
*new_no
= gogo
->start_function(name
, new_fntype
, false,
4694 Function
*new_func
= new_no
->func_value();
4695 if (orig_func
->enclosing() != NULL
)
4696 new_func
->set_enclosing(orig_func
->enclosing());
4698 // We build the code for the original function attached to the new
4699 // function, and then swap the original and new function bodies.
4700 // This means that existing references to the original function will
4701 // then refer to the new function. That makes this code a little
4702 // confusing, in that the reference to NEW_NO really refers to the
4703 // other function, not the one we are building.
4705 Expression
* closure
= NULL
;
4706 if (orig_func
->needs_closure())
4708 // For the new function we are creating, declare a new parameter
4709 // variable NEW_CLOSURE_NO and set it to be the closure variable
4710 // of the function. This will be set to the closure value
4711 // passed in by the caller. Then pass a reference to this
4712 // variable as the closure value when calling the original
4713 // function. In other words, simply pass the closure value
4714 // through the thunk we are creating.
4715 Named_object
* orig_closure_no
= orig_func
->closure_var();
4716 Variable
* orig_closure_var
= orig_closure_no
->var_value();
4717 Variable
* new_var
= new Variable(orig_closure_var
->type(), NULL
, false,
4718 false, false, location
);
4719 new_var
->set_is_closure();
4720 snprintf(buf
, sizeof buf
, "closure.%u", count
);
4722 Named_object
* new_closure_no
= Named_object::make_variable(buf
, NULL
,
4724 new_func
->set_closure_var(new_closure_no
);
4725 closure
= Expression::make_var_reference(new_closure_no
, location
);
4728 Expression
* fn
= Expression::make_func_reference(new_no
, closure
, location
);
4730 Expression_list
* args
= new Expression_list();
4731 if (new_params
!= NULL
)
4733 // Note that we skip the last parameter, which is the boolean
4734 // indicating whether recover can succed.
4735 for (Typed_identifier_list::const_iterator p
= new_params
->begin();
4736 p
+ 1 != new_params
->end();
4739 Named_object
* p_no
= gogo
->lookup(p
->name(), NULL
);
4740 go_assert(p_no
!= NULL
4741 && p_no
->is_variable()
4742 && p_no
->var_value()->is_parameter());
4743 args
->push_back(Expression::make_var_reference(p_no
, location
));
4746 args
->push_back(this->can_recover_arg(location
));
4748 gogo
->start_block(location
);
4750 Call_expression
* call
= Expression::make_call(fn
, args
, false, location
);
4752 // Any varargs call has already been lowered.
4753 call
->set_varargs_are_lowered();
4755 Statement
* s
= Statement::make_return_from_call(call
, location
);
4756 s
->determine_types();
4757 gogo
->add_statement(s
);
4759 Block
* b
= gogo
->finish_block(location
);
4761 gogo
->add_block(b
, location
);
4763 // Lower the call in case it returns multiple results.
4764 gogo
->lower_block(new_no
, b
);
4766 gogo
->finish_function(location
);
4768 // Swap the function bodies and types.
4769 new_func
->swap_for_recover(orig_func
);
4770 orig_func
->set_is_recover_thunk();
4771 new_func
->set_calls_recover();
4772 new_func
->set_has_recover_thunk();
4774 Bindings
* orig_bindings
= orig_func
->block()->bindings();
4775 Bindings
* new_bindings
= new_func
->block()->bindings();
4776 if (orig_fntype
->is_method())
4778 // We changed the receiver to be a regular parameter. We have
4779 // to update the binding accordingly in both functions.
4780 Named_object
* orig_rec_no
= orig_bindings
->lookup_local(receiver_name
);
4781 go_assert(orig_rec_no
!= NULL
4782 && orig_rec_no
->is_variable()
4783 && !orig_rec_no
->var_value()->is_receiver());
4784 orig_rec_no
->var_value()->set_is_receiver();
4786 std::string
new_receiver_name(orig_fntype
->receiver()->name());
4787 if (new_receiver_name
.empty())
4789 // Find the receiver. It was named "r.NNN" in
4790 // Gogo::start_function.
4791 for (Bindings::const_definitions_iterator p
=
4792 new_bindings
->begin_definitions();
4793 p
!= new_bindings
->end_definitions();
4796 const std::string
& pname((*p
)->name());
4797 if (pname
[0] == 'r' && pname
[1] == '.')
4799 new_receiver_name
= pname
;
4803 go_assert(!new_receiver_name
.empty());
4805 Named_object
* new_rec_no
= new_bindings
->lookup_local(new_receiver_name
);
4806 if (new_rec_no
== NULL
)
4807 go_assert(saw_errors());
4810 go_assert(new_rec_no
->is_variable()
4811 && new_rec_no
->var_value()->is_receiver());
4812 new_rec_no
->var_value()->set_is_not_receiver();
4816 // Because we flipped blocks but not types, the can_recover
4817 // parameter appears in the (now) old bindings as a parameter.
4818 // Change it to a local variable, whereupon it will be discarded.
4819 Named_object
* can_recover_no
= orig_bindings
->lookup_local(can_recover_name
);
4820 go_assert(can_recover_no
!= NULL
4821 && can_recover_no
->is_variable()
4822 && can_recover_no
->var_value()->is_parameter());
4823 orig_bindings
->remove_binding(can_recover_no
);
4825 // Add the can_recover argument to the (now) new bindings, and
4826 // attach it to any recover statements.
4827 Variable
* can_recover_var
= new Variable(Type::lookup_bool_type(), NULL
,
4828 false, true, false, location
);
4829 can_recover_no
= new_bindings
->add_variable(can_recover_name
, NULL
,
4831 Convert_recover
convert_recover(can_recover_no
);
4832 new_func
->traverse(&convert_recover
);
4834 // Update the function pointers in any named results.
4835 new_func
->update_result_variables();
4836 orig_func
->update_result_variables();
4838 return TRAVERSE_CONTINUE
;
4841 // Return the expression to pass for the .can_recover parameter to the
4842 // new function. This indicates whether a call to recover may return
4843 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4846 Build_recover_thunks::can_recover_arg(Location location
)
4848 Type
* uintptr_type
= Type::lookup_integer_type("uintptr");
4849 static Named_object
* can_recover
;
4850 if (can_recover
== NULL
)
4852 const Location bloc
= Linemap::predeclared_location();
4853 Typed_identifier_list
* param_types
= new Typed_identifier_list();
4854 param_types
->push_back(Typed_identifier("a", uintptr_type
, bloc
));
4855 Type
* boolean_type
= Type::lookup_bool_type();
4856 Typed_identifier_list
* results
= new Typed_identifier_list();
4857 results
->push_back(Typed_identifier("", boolean_type
, bloc
));
4858 Function_type
* fntype
= Type::make_function_type(NULL
, param_types
,
4861 Named_object::make_function_declaration("runtime_canrecover",
4862 NULL
, fntype
, bloc
);
4863 can_recover
->func_declaration_value()->set_asm_name("runtime.canrecover");
4866 Expression
* zexpr
= Expression::make_integer_ul(0, NULL
, location
);
4867 Expression
* call
= Runtime::make_call(Runtime::BUILTIN_RETURN_ADDRESS
,
4868 location
, 1, zexpr
);
4869 call
= Expression::make_unsafe_cast(uintptr_type
, call
, location
);
4871 Expression_list
* args
= new Expression_list();
4872 args
->push_back(call
);
4874 Expression
* fn
= Expression::make_func_reference(can_recover
, NULL
, location
);
4875 return Expression::make_call(fn
, args
, false, location
);
4878 // Build thunks for functions which call recover. We build a new
4879 // function with an extra parameter, which is whether a call to
4880 // recover can succeed. We then move the body of this function to
4881 // that one. We then turn this function into a thunk which calls the
4882 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4883 // The function will be marked as not splitting the stack. This will
4884 // cooperate with the implementation of defer to make recover do the
4888 Gogo::build_recover_thunks()
4890 Build_recover_thunks
build_recover_thunks(this);
4891 this->traverse(&build_recover_thunks
);
4894 // Look for named types to see whether we need to create an interface
4897 class Build_method_tables
: public Traverse
4900 Build_method_tables(Gogo
* gogo
,
4901 const std::vector
<Interface_type
*>& interfaces
)
4902 : Traverse(traverse_types
),
4903 gogo_(gogo
), interfaces_(interfaces
)
4912 // A list of locally defined interfaces which have hidden methods.
4913 const std::vector
<Interface_type
*>& interfaces_
;
4916 // Build all required interface method tables for types. We need to
4917 // ensure that we have an interface method table for every interface
4918 // which has a hidden method, for every named type which implements
4919 // that interface. Normally we can just build interface method tables
4920 // as we need them. However, in some cases we can require an
4921 // interface method table for an interface defined in a different
4922 // package for a type defined in that package. If that interface and
4923 // type both use a hidden method, that is OK. However, we will not be
4924 // able to build that interface method table when we need it, because
4925 // the type's hidden method will be static. So we have to build it
4926 // here, and just refer it from other packages as needed.
4929 Gogo::build_interface_method_tables()
4934 std::vector
<Interface_type
*> hidden_interfaces
;
4935 hidden_interfaces
.reserve(this->interface_types_
.size());
4936 for (std::vector
<Interface_type
*>::const_iterator pi
=
4937 this->interface_types_
.begin();
4938 pi
!= this->interface_types_
.end();
4941 const Typed_identifier_list
* methods
= (*pi
)->methods();
4942 if (methods
== NULL
)
4944 for (Typed_identifier_list::const_iterator pm
= methods
->begin();
4945 pm
!= methods
->end();
4948 if (Gogo::is_hidden_name(pm
->name()))
4950 hidden_interfaces
.push_back(*pi
);
4956 if (!hidden_interfaces
.empty())
4958 // Now traverse the tree looking for all named types.
4959 Build_method_tables
bmt(this, hidden_interfaces
);
4960 this->traverse(&bmt
);
4963 // We no longer need the list of interfaces.
4965 this->interface_types_
.clear();
4968 // This is called for each type. For a named type, for each of the
4969 // interfaces with hidden methods that it implements, create the
4973 Build_method_tables::type(Type
* type
)
4975 Named_type
* nt
= type
->named_type();
4976 Struct_type
* st
= type
->struct_type();
4977 if (nt
!= NULL
|| st
!= NULL
)
4979 Translate_context
context(this->gogo_
, NULL
, NULL
, NULL
);
4980 for (std::vector
<Interface_type
*>::const_iterator p
=
4981 this->interfaces_
.begin();
4982 p
!= this->interfaces_
.end();
4985 // We ask whether a pointer to the named type implements the
4986 // interface, because a pointer can implement more methods
4990 if ((*p
)->implements_interface(Type::make_pointer_type(nt
),
4993 nt
->interface_method_table(*p
, false)->get_backend(&context
);
4994 nt
->interface_method_table(*p
, true)->get_backend(&context
);
4999 if ((*p
)->implements_interface(Type::make_pointer_type(st
),
5002 st
->interface_method_table(*p
, false)->get_backend(&context
);
5003 st
->interface_method_table(*p
, true)->get_backend(&context
);
5008 return TRAVERSE_CONTINUE
;
5011 // Return an expression which allocates memory to hold values of type TYPE.
5014 Gogo::allocate_memory(Type
* type
, Location location
)
5016 Expression
* td
= Expression::make_type_descriptor(type
, location
);
5017 return Runtime::make_call(Runtime::NEW
, location
, 1, td
);
5020 // Traversal class used to check for return statements.
5022 class Check_return_statements_traverse
: public Traverse
5025 Check_return_statements_traverse()
5026 : Traverse(traverse_functions
)
5030 function(Named_object
*);
5033 // Check that a function has a return statement if it needs one.
5036 Check_return_statements_traverse::function(Named_object
* no
)
5038 Function
* func
= no
->func_value();
5039 const Function_type
* fntype
= func
->type();
5040 const Typed_identifier_list
* results
= fntype
->results();
5042 // We only need a return statement if there is a return value.
5043 if (results
== NULL
|| results
->empty())
5044 return TRAVERSE_CONTINUE
;
5046 if (func
->block()->may_fall_through())
5047 go_error_at(func
->block()->end_location(),
5048 "missing return at end of function");
5050 return TRAVERSE_CONTINUE
;
5053 // Check return statements.
5056 Gogo::check_return_statements()
5058 Check_return_statements_traverse traverse
;
5059 this->traverse(&traverse
);
5062 // Traversal class to decide whether a function body is less than the
5063 // inlining budget. This adjusts *available as it goes, and stops the
5064 // traversal if it goes negative.
5066 class Inline_within_budget
: public Traverse
5069 Inline_within_budget(int* available
)
5070 : Traverse(traverse_statements
5071 | traverse_expressions
),
5072 available_(available
)
5076 statement(Block
*, size_t*, Statement
*);
5079 expression(Expression
**);
5082 // Pointer to remaining budget.
5086 // Adjust the budget for the inlining cost of a statement.
5089 Inline_within_budget::statement(Block
*, size_t*, Statement
* s
)
5091 if (*this->available_
< 0)
5092 return TRAVERSE_EXIT
;
5093 *this->available_
-= s
->inlining_cost();
5094 return TRAVERSE_CONTINUE
;
5097 // Adjust the budget for the inlining cost of an expression.
5100 Inline_within_budget::expression(Expression
** pexpr
)
5102 if (*this->available_
< 0)
5103 return TRAVERSE_EXIT
;
5104 *this->available_
-= (*pexpr
)->inlining_cost();
5105 return TRAVERSE_CONTINUE
;
5108 // Traversal class to find functions whose body should be exported for
5109 // inlining by other packages.
5111 class Mark_inline_candidates
: public Traverse
5114 Mark_inline_candidates(Unordered_set(Named_object
*)* marked
)
5115 : Traverse(traverse_functions
5117 marked_functions_(marked
)
5121 function(Named_object
*);
5127 // We traverse the function body trying to determine how expensive
5128 // it is for inlining. We start with a budget, and decrease that
5129 // budget for each statement and expression. If the budget goes
5130 // negative, we do not export the function body. The value of this
5131 // budget is a heuristic. In the usual GCC spirit, we could
5132 // consider setting this via a command line option.
5133 const int budget_heuristic
= 80;
5135 // Set of named objects that are marked as inline candidates.
5136 Unordered_set(Named_object
*)* marked_functions_
;
5139 // Mark a function if it is an inline candidate.
5142 Mark_inline_candidates::function(Named_object
* no
)
5144 Function
* func
= no
->func_value();
5145 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5146 return TRAVERSE_CONTINUE
;
5147 int budget
= budget_heuristic
;
5148 Inline_within_budget
iwb(&budget
);
5149 func
->block()->traverse(&iwb
);
5152 func
->set_export_for_inlining();
5153 this->marked_functions_
->insert(no
);
5155 return TRAVERSE_CONTINUE
;
5158 // Mark methods if they are inline candidates.
5161 Mark_inline_candidates::type(Type
* t
)
5163 Named_type
* nt
= t
->named_type();
5164 if (nt
== NULL
|| nt
->is_alias())
5165 return TRAVERSE_CONTINUE
;
5166 const Bindings
* methods
= nt
->local_methods();
5167 if (methods
== NULL
)
5168 return TRAVERSE_CONTINUE
;
5169 for (Bindings::const_definitions_iterator p
= methods
->begin_definitions();
5170 p
!= methods
->end_definitions();
5173 Named_object
* no
= *p
;
5174 go_assert(no
->is_function());
5175 Function
*func
= no
->func_value();
5176 if ((func
->pragmas() & GOPRAGMA_NOINLINE
) != 0)
5178 int budget
= budget_heuristic
;
5179 Inline_within_budget
iwb(&budget
);
5180 func
->block()->traverse(&iwb
);
5183 func
->set_export_for_inlining();
5184 this->marked_functions_
->insert(no
);
5187 return TRAVERSE_CONTINUE
;
5190 // Export identifiers as requested.
5198 // Mark any functions whose body should be exported for inlining by
5200 Unordered_set(Named_object
*) marked_functions
;
5201 Mark_inline_candidates
mic(&marked_functions
);
5202 this->traverse(&mic
);
5204 // For now we always stream to a section. Later we may want to
5205 // support streaming to a separate file.
5206 Stream_to_section
stream(this->backend());
5208 // Write out either the prefix or pkgpath depending on how we were
5211 std::string pkgpath
;
5212 if (this->pkgpath_from_option_
)
5213 pkgpath
= this->pkgpath_
;
5214 else if (this->prefix_from_option_
)
5215 prefix
= this->prefix_
;
5216 else if (this->is_main_package())
5221 std::string init_fn_name
;
5222 if (this->is_main_package())
5224 else if (this->need_init_fn_
)
5225 init_fn_name
= this->get_init_fn_name();
5227 init_fn_name
= this->dummy_init_fn_name();
5229 Export
exp(&stream
);
5230 exp
.register_builtin_types(this);
5231 exp
.export_globals(this->package_name(),
5237 this->imported_init_fns_
,
5238 this->package_
->bindings(),
5241 if (!this->c_header_
.empty() && !saw_errors())
5242 this->write_c_header();
5245 // Write the top level named struct types in C format to a C header
5246 // file. This is used when building the runtime package, to share
5247 // struct definitions between C and Go.
5250 Gogo::write_c_header()
5253 out
.open(this->c_header_
.c_str());
5256 go_error_at(Linemap::unknown_location(),
5257 "cannot open %s: %m", this->c_header_
.c_str());
5261 std::list
<Named_object
*> types
;
5262 Bindings
* top
= this->package_
->bindings();
5263 for (Bindings::const_definitions_iterator p
= top
->begin_definitions();
5264 p
!= top
->end_definitions();
5267 Named_object
* no
= *p
;
5269 // Skip names that start with underscore followed by something
5270 // other than an uppercase letter, as when compiling the runtime
5271 // package they are mostly types defined by mkrsysinfo.sh based
5272 // on the C system header files. We don't need to translate
5273 // types to C and back to Go. But do accept the special cases
5274 // _defer, _panic, and _type.
5275 std::string name
= Gogo::unpack_hidden_name(no
->name());
5277 && (name
[1] < 'A' || name
[1] > 'Z')
5278 && (name
!= "_defer" && name
!= "_panic" && name
!= "_type"))
5281 if (no
->is_type() && no
->type_value()->struct_type() != NULL
)
5282 types
.push_back(no
);
5284 && no
->const_value()->type()->integer_type() != NULL
5285 && !no
->const_value()->is_sink())
5287 Numeric_constant nc
;
5289 if (no
->const_value()->expr()->numeric_constant_value(&nc
)
5290 && nc
.to_unsigned_long(&val
) == Numeric_constant::NC_UL_VALID
)
5292 out
<< "#define " << no
->message_name() << ' ' << val
5298 std::vector
<const Named_object
*> written
;
5300 while (!types
.empty())
5302 Named_object
* no
= types
.front();
5305 std::vector
<const Named_object
*> requires
;
5306 std::vector
<const Named_object
*> declare
;
5307 if (!no
->type_value()->struct_type()->can_write_to_c_header(&requires
,
5312 for (std::vector
<const Named_object
*>::const_iterator pr
5314 pr
!= requires
.end() && ok
;
5317 for (std::list
<Named_object
*>::const_iterator pt
= types
.begin();
5318 pt
!= types
.end() && ok
;
5328 // This should be impossible since the code parsed and
5333 types
.push_back(no
);
5337 for (std::vector
<const Named_object
*>::const_iterator pd
5339 pd
!= declare
.end();
5345 std::vector
<const Named_object
*> drequires
;
5346 std::vector
<const Named_object
*> ddeclare
;
5347 if (!(*pd
)->type_value()->struct_type()->
5348 can_write_to_c_header(&drequires
, &ddeclare
))
5352 for (std::vector
<const Named_object
*>::const_iterator pw
5354 pw
!= written
.end();
5366 out
<< "struct " << (*pd
)->message_name() << ";" << std::endl
;
5367 written
.push_back(*pd
);
5372 out
<< "struct " << no
->message_name() << " {" << std::endl
;
5373 no
->type_value()->struct_type()->write_to_c_header(out
);
5374 out
<< "};" << std::endl
;
5375 written
.push_back(no
);
5380 go_error_at(Linemap::unknown_location(),
5381 "error writing to %s: %m", this->c_header_
.c_str());
5384 // Find the blocks in order to convert named types defined in blocks.
5386 class Convert_named_types
: public Traverse
5389 Convert_named_types(Gogo
* gogo
)
5390 : Traverse(traverse_blocks
),
5396 block(Block
* block
);
5403 Convert_named_types::block(Block
* block
)
5405 this->gogo_
->convert_named_types_in_bindings(block
->bindings());
5406 return TRAVERSE_CONTINUE
;
5409 // Convert all named types to the backend representation. Since named
5410 // types can refer to other types, this needs to be done in the right
5411 // sequence, which is handled by Named_type::convert. Here we arrange
5412 // to call that for each named type.
5415 Gogo::convert_named_types()
5417 this->convert_named_types_in_bindings(this->globals_
);
5418 for (Packages::iterator p
= this->packages_
.begin();
5419 p
!= this->packages_
.end();
5422 Package
* package
= p
->second
;
5423 this->convert_named_types_in_bindings(package
->bindings());
5426 Convert_named_types
cnt(this);
5427 this->traverse(&cnt
);
5429 // Make all the builtin named types used for type descriptors, and
5430 // then convert them. They will only be written out if they are
5432 Type::make_type_descriptor_type();
5433 Type::make_type_descriptor_ptr_type();
5434 Function_type::make_function_type_descriptor_type();
5435 Pointer_type::make_pointer_type_descriptor_type();
5436 Struct_type::make_struct_type_descriptor_type();
5437 Array_type::make_array_type_descriptor_type();
5438 Array_type::make_slice_type_descriptor_type();
5439 Map_type::make_map_type_descriptor_type();
5440 Channel_type::make_chan_type_descriptor_type();
5441 Interface_type::make_interface_type_descriptor_type();
5442 Expression::make_func_descriptor_type();
5443 Type::convert_builtin_named_types(this);
5445 Runtime::convert_types(this);
5447 this->named_types_are_converted_
= true;
5449 Type::finish_pointer_types(this);
5452 // Convert all names types in a set of bindings.
5455 Gogo::convert_named_types_in_bindings(Bindings
* bindings
)
5457 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
5458 p
!= bindings
->end_definitions();
5461 if ((*p
)->is_type())
5462 (*p
)->type_value()->convert(this);
5467 debug_go_gogo(Gogo
* gogo
)
5476 std::cerr
<< "Packages:\n";
5477 for (Packages::const_iterator p
= this->packages_
.begin();
5478 p
!= this->packages_
.end();
5481 const char *tag
= " ";
5482 if (p
->second
== this->package_
)
5484 std::cerr
<< tag
<< "'" << p
->first
<< "' "
5485 << p
->second
->pkgpath() << " " << ((void*)p
->second
) << "\n";
5491 Function::Function(Function_type
* type
, Named_object
* enclosing
, Block
* block
,
5493 : type_(type
), enclosing_(enclosing
), results_(NULL
),
5494 closure_var_(NULL
), block_(block
), location_(location
), labels_(),
5495 local_type_count_(0), descriptor_(NULL
), fndecl_(NULL
), defer_stack_(NULL
),
5496 pragmas_(0), nested_functions_(0), is_sink_(false),
5497 results_are_named_(false), is_unnamed_type_stub_method_(false),
5498 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
5499 calls_defer_retaddr_(false), is_type_specific_function_(false),
5500 in_unique_section_(false), export_for_inlining_(false),
5501 is_inline_only_(false), is_referenced_by_inline_(false),
5502 is_exported_by_linkname_(false)
5506 // Create the named result variables.
5509 Function::create_result_variables(Gogo
* gogo
)
5511 const Typed_identifier_list
* results
= this->type_
->results();
5512 if (results
== NULL
|| results
->empty())
5515 if (!results
->front().name().empty())
5516 this->results_are_named_
= true;
5518 this->results_
= new Results();
5519 this->results_
->reserve(results
->size());
5521 Block
* block
= this->block_
;
5523 for (Typed_identifier_list::const_iterator p
= results
->begin();
5524 p
!= results
->end();
5527 std::string name
= p
->name();
5528 if (name
.empty() || Gogo::is_sink_name(name
))
5530 static int result_counter
;
5532 snprintf(buf
, sizeof buf
, "$ret%d", result_counter
);
5534 name
= gogo
->pack_hidden_name(buf
, false);
5536 Result_variable
* result
= new Result_variable(p
->type(), this, index
,
5538 Named_object
* no
= block
->bindings()->add_result_variable(name
, result
);
5539 if (no
->is_result_variable())
5540 this->results_
->push_back(no
);
5543 static int dummy_result_count
;
5545 snprintf(buf
, sizeof buf
, "$dret%d", dummy_result_count
);
5546 ++dummy_result_count
;
5547 name
= gogo
->pack_hidden_name(buf
, false);
5548 no
= block
->bindings()->add_result_variable(name
, result
);
5549 go_assert(no
->is_result_variable());
5550 this->results_
->push_back(no
);
5555 // Update the named result variables when cloning a function which
5559 Function::update_result_variables()
5561 if (this->results_
== NULL
)
5564 for (Results::iterator p
= this->results_
->begin();
5565 p
!= this->results_
->end();
5567 (*p
)->result_var_value()->set_function(this);
5570 // Whether this method should not be included in the type descriptor.
5573 Function::nointerface() const
5575 go_assert(this->is_method());
5576 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
5579 // Record that this method should not be included in the type
5583 Function::set_nointerface()
5585 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
5588 // Return the closure variable, creating it if necessary.
5591 Function::closure_var()
5593 if (this->closure_var_
== NULL
)
5595 go_assert(this->descriptor_
== NULL
);
5596 // We don't know the type of the variable yet. We add fields as
5598 Location loc
= this->type_
->location();
5599 Struct_field_list
* sfl
= new Struct_field_list
;
5600 Struct_type
* struct_type
= Type::make_struct_type(sfl
, loc
);
5601 struct_type
->set_is_struct_incomparable();
5602 Variable
* var
= new Variable(Type::make_pointer_type(struct_type
),
5603 NULL
, false, false, false, loc
);
5605 var
->set_is_closure();
5606 this->closure_var_
= Named_object::make_variable("$closure", NULL
, var
);
5607 // Note that the new variable is not in any binding contour.
5609 return this->closure_var_
;
5612 // Set the type of the closure variable.
5615 Function::set_closure_type()
5617 if (this->closure_var_
== NULL
)
5619 Named_object
* closure
= this->closure_var_
;
5620 Struct_type
* st
= closure
->var_value()->type()->deref()->struct_type();
5622 // The first field of a closure is always a pointer to the function
5624 Type
* voidptr_type
= Type::make_pointer_type(Type::make_void_type());
5625 st
->push_field(Struct_field(Typed_identifier(".f", voidptr_type
,
5628 unsigned int index
= 1;
5629 for (Closure_fields::const_iterator p
= this->closure_fields_
.begin();
5630 p
!= this->closure_fields_
.end();
5633 Named_object
* no
= p
->first
;
5635 snprintf(buf
, sizeof buf
, "%u", index
);
5636 std::string n
= no
->name() + buf
;
5638 if (no
->is_variable())
5639 var_type
= no
->var_value()->type();
5641 var_type
= no
->result_var_value()->type();
5642 Type
* field_type
= Type::make_pointer_type(var_type
);
5643 st
->push_field(Struct_field(Typed_identifier(n
, field_type
, p
->second
)));
5647 // Return whether this function is a method.
5650 Function::is_method() const
5652 return this->type_
->is_method();
5655 // Add a label definition.
5658 Function::add_label_definition(Gogo
* gogo
, const std::string
& label_name
,
5661 Label
* lnull
= NULL
;
5662 std::pair
<Labels::iterator
, bool> ins
=
5663 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5665 if (label_name
== "_")
5667 label
= Label::create_dummy_label();
5669 ins
.first
->second
= label
;
5671 else if (ins
.second
)
5673 // This is a new label.
5674 label
= new Label(label_name
);
5675 ins
.first
->second
= label
;
5679 // The label was already in the hash table.
5680 label
= ins
.first
->second
;
5681 if (label
->is_defined())
5683 go_error_at(location
, "label %qs already defined",
5684 Gogo::message_name(label_name
).c_str());
5685 go_inform(label
->location(), "previous definition of %qs was here",
5686 Gogo::message_name(label_name
).c_str());
5687 return new Label(label_name
);
5691 label
->define(location
, gogo
->bindings_snapshot(location
));
5693 // Issue any errors appropriate for any previous goto's to this
5695 const std::vector
<Bindings_snapshot
*>& refs(label
->refs());
5696 for (std::vector
<Bindings_snapshot
*>::const_iterator p
= refs
.begin();
5699 (*p
)->check_goto_to(gogo
->current_block());
5700 label
->clear_refs();
5705 // Add a reference to a label.
5708 Function::add_label_reference(Gogo
* gogo
, const std::string
& label_name
,
5709 Location location
, bool issue_goto_errors
)
5711 Label
* lnull
= NULL
;
5712 std::pair
<Labels::iterator
, bool> ins
=
5713 this->labels_
.insert(std::make_pair(label_name
, lnull
));
5717 // The label was already in the hash table.
5718 label
= ins
.first
->second
;
5722 go_assert(ins
.first
->second
== NULL
);
5723 label
= new Label(label_name
);
5724 ins
.first
->second
= label
;
5727 label
->set_is_used();
5729 if (issue_goto_errors
)
5731 Bindings_snapshot
* snapshot
= label
->snapshot();
5732 if (snapshot
!= NULL
)
5733 snapshot
->check_goto_from(gogo
->current_block(), location
);
5735 label
->add_snapshot_ref(gogo
->bindings_snapshot(location
));
5741 // Warn about labels that are defined but not used.
5744 Function::check_labels() const
5746 for (Labels::const_iterator p
= this->labels_
.begin();
5747 p
!= this->labels_
.end();
5750 Label
* label
= p
->second
;
5751 if (!label
->is_used())
5752 go_error_at(label
->location(), "label %qs defined and not used",
5753 Gogo::message_name(label
->name()).c_str());
5757 // Set the receiver type. This is used to remove aliases.
5760 Function::set_receiver_type(Type
* rtype
)
5762 Function_type
* oft
= this->type_
;
5763 Typed_identifier
* rec
= new Typed_identifier(oft
->receiver()->name(),
5765 oft
->receiver()->location());
5766 Typed_identifier_list
* parameters
= NULL
;
5767 if (oft
->parameters() != NULL
)
5768 parameters
= oft
->parameters()->copy();
5769 Typed_identifier_list
* results
= NULL
;
5770 if (oft
->results() != NULL
)
5771 results
= oft
->results()->copy();
5772 Function_type
* nft
= Type::make_function_type(rec
, parameters
, results
,
5777 // Swap one function with another. This is used when building the
5778 // thunk we use to call a function which calls recover. It may not
5779 // work for any other case.
5782 Function::swap_for_recover(Function
*x
)
5784 go_assert(this->enclosing_
== x
->enclosing_
);
5785 std::swap(this->results_
, x
->results_
);
5786 std::swap(this->closure_var_
, x
->closure_var_
);
5787 std::swap(this->block_
, x
->block_
);
5788 go_assert(this->location_
== x
->location_
);
5789 go_assert(this->fndecl_
== NULL
&& x
->fndecl_
== NULL
);
5790 go_assert(this->defer_stack_
== NULL
&& x
->defer_stack_
== NULL
);
5793 // Traverse the tree.
5796 Function::traverse(Traverse
* traverse
)
5798 unsigned int traverse_mask
= traverse
->traverse_mask();
5801 & (Traverse::traverse_types
| Traverse::traverse_expressions
))
5804 if (Type::traverse(this->type_
, traverse
) == TRAVERSE_EXIT
)
5805 return TRAVERSE_EXIT
;
5808 // FIXME: We should check traverse_functions here if nested
5809 // functions are stored in block bindings.
5810 if (this->block_
!= NULL
5812 & (Traverse::traverse_variables
5813 | Traverse::traverse_constants
5814 | Traverse::traverse_blocks
5815 | Traverse::traverse_statements
5816 | Traverse::traverse_expressions
5817 | Traverse::traverse_types
)) != 0)
5819 if (this->block_
->traverse(traverse
) == TRAVERSE_EXIT
)
5820 return TRAVERSE_EXIT
;
5823 return TRAVERSE_CONTINUE
;
5826 // Work out types for unspecified variables and constants.
5829 Function::determine_types()
5831 if (this->block_
!= NULL
)
5832 this->block_
->determine_types();
5835 // Return the function descriptor, the value you get when you refer to
5836 // the function in Go code without calling it.
5839 Function::descriptor(Gogo
*, Named_object
* no
)
5841 go_assert(!this->is_method());
5842 go_assert(this->closure_var_
== NULL
);
5843 if (this->descriptor_
== NULL
)
5844 this->descriptor_
= Expression::make_func_descriptor(no
);
5845 return this->descriptor_
;
5848 // Get a pointer to the variable representing the defer stack for this
5849 // function, making it if necessary. The value of the variable is set
5850 // by the runtime routines to true if the function is returning,
5851 // rather than panicing through. A pointer to this variable is used
5852 // as a marker for the functions on the defer stack associated with
5853 // this function. A function-specific variable permits inlining a
5854 // function which uses defer.
5857 Function::defer_stack(Location location
)
5859 if (this->defer_stack_
== NULL
)
5861 Type
* t
= Type::lookup_bool_type();
5862 Expression
* n
= Expression::make_boolean(false, location
);
5863 this->defer_stack_
= Statement::make_temporary(t
, n
, location
);
5864 this->defer_stack_
->set_is_address_taken();
5866 Expression
* ref
= Expression::make_temporary_reference(this->defer_stack_
,
5868 return Expression::make_unary(OPERATOR_AND
, ref
, location
);
5871 // Export the function.
5874 Function::export_func(Export
* exp
, const Named_object
* no
) const
5876 Block
* block
= NULL
;
5877 if (this->export_for_inlining())
5878 block
= this->block_
;
5879 Function::export_func_with_type(exp
, no
, this->type_
, this->results_
,
5880 this->is_method() && this->nointerface(),
5881 this->asm_name(), block
, this->location_
);
5884 // Export a function with a type.
5887 Function::export_func_with_type(Export
* exp
, const Named_object
* no
,
5888 const Function_type
* fntype
,
5889 Function::Results
* result_vars
,
5890 bool nointerface
, const std::string
& asm_name
,
5891 Block
* block
, Location loc
)
5893 exp
->write_c_string("func ");
5897 go_assert(fntype
->is_method());
5898 exp
->write_c_string("/*nointerface*/ ");
5901 if (!asm_name
.empty())
5903 exp
->write_c_string("/*asm ");
5904 exp
->write_string(asm_name
);
5905 exp
->write_c_string(" */ ");
5908 if (fntype
->is_method())
5910 exp
->write_c_string("(");
5911 const Typed_identifier
* receiver
= fntype
->receiver();
5912 exp
->write_name(receiver
->name());
5913 exp
->write_escape(receiver
->note());
5914 exp
->write_c_string(" ");
5915 exp
->write_type(receiver
->type()->unalias());
5916 exp
->write_c_string(") ");
5919 if (no
->package() != NULL
&& !fntype
->is_method())
5922 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
5923 exp
->write_c_string(buf
);
5926 const std::string
& name(no
->name());
5927 if (!Gogo::is_hidden_name(name
))
5928 exp
->write_string(name
);
5931 exp
->write_c_string(".");
5932 exp
->write_string(Gogo::unpack_hidden_name(name
));
5935 exp
->write_c_string(" (");
5936 const Typed_identifier_list
* parameters
= fntype
->parameters();
5937 if (parameters
!= NULL
)
5940 bool is_varargs
= fntype
->is_varargs();
5942 for (Typed_identifier_list::const_iterator p
= parameters
->begin();
5943 p
!= parameters
->end();
5949 exp
->write_c_string(", ");
5950 exp
->write_name(p
->name());
5951 exp
->write_escape(p
->note());
5952 exp
->write_c_string(" ");
5953 if (!is_varargs
|| p
+ 1 != parameters
->end())
5954 exp
->write_type(p
->type());
5957 exp
->write_c_string("...");
5958 exp
->write_type(p
->type()->array_type()->element_type());
5962 exp
->write_c_string(")");
5964 const Typed_identifier_list
* result_decls
= fntype
->results();
5965 if (result_decls
!= NULL
)
5967 if (result_decls
->size() == 1
5968 && result_decls
->begin()->name().empty()
5971 exp
->write_c_string(" ");
5972 exp
->write_type(result_decls
->begin()->type());
5976 exp
->write_c_string(" (");
5978 Results::const_iterator pr
;
5979 if (result_vars
!= NULL
)
5980 pr
= result_vars
->begin();
5981 for (Typed_identifier_list::const_iterator pd
= result_decls
->begin();
5982 pd
!= result_decls
->end();
5988 exp
->write_c_string(", ");
5989 // We only use pr->name, which may be artificial, if
5990 // need it for inlining.
5991 if (block
== NULL
|| result_vars
== NULL
)
5992 exp
->write_name(pd
->name());
5994 exp
->write_name((*pr
)->name());
5995 exp
->write_escape(pd
->note());
5996 exp
->write_c_string(" ");
5997 exp
->write_type(pd
->type());
5998 if (result_vars
!= NULL
)
6001 if (result_vars
!= NULL
)
6002 go_assert(pr
== result_vars
->end());
6003 exp
->write_c_string(")");
6008 exp
->write_c_string("\n");
6012 if (fntype
->is_method())
6015 Export_function_body
efb(exp
, indent
);
6018 efb
.write_c_string("// ");
6019 efb
.write_string(Linemap::location_to_file(block
->start_location()));
6020 efb
.write_char(':');
6022 snprintf(buf
, sizeof buf
, "%d", Linemap::location_to_line(loc
));
6023 efb
.write_c_string(buf
);
6024 efb
.write_char('\n');
6025 block
->export_block(&efb
);
6027 const std::string
& body(efb
.body());
6029 snprintf(buf
, sizeof buf
, " <inl:%lu>\n",
6030 static_cast<unsigned long>(body
.length()));
6031 exp
->write_c_string(buf
);
6033 exp
->write_string(body
);
6037 // Import a function.
6040 Function::import_func(Import
* imp
, std::string
* pname
,
6041 Package
** ppkg
, bool* pis_exported
,
6042 Typed_identifier
** preceiver
,
6043 Typed_identifier_list
** pparameters
,
6044 Typed_identifier_list
** presults
,
6047 std::string
* asm_name
,
6050 imp
->require_c_string("func ");
6052 *nointerface
= false;
6053 while (imp
->match_c_string("/*"))
6056 if (imp
->match_c_string("nointerface"))
6058 imp
->require_c_string("nointerface*/ ");
6059 *nointerface
= true;
6061 else if (imp
->match_c_string("asm"))
6063 imp
->require_c_string("asm ");
6064 *asm_name
= imp
->read_identifier();
6065 imp
->require_c_string(" */ ");
6069 go_error_at(imp
->location(),
6070 "import error at %d: unrecognized function comment",
6078 // Only a method can be nointerface.
6079 go_assert(imp
->peek_char() == '(');
6083 if (imp
->peek_char() == '(')
6085 imp
->require_c_string("(");
6086 std::string name
= imp
->read_name();
6087 std::string escape_note
= imp
->read_escape();
6088 imp
->require_c_string(" ");
6089 Type
* rtype
= imp
->read_type();
6090 *preceiver
= new Typed_identifier(name
, rtype
, imp
->location());
6091 (*preceiver
)->set_note(escape_note
);
6092 imp
->require_c_string(") ");
6095 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
6097 go_error_at(imp
->location(),
6098 "import error at %d: bad function name in export data",
6103 Typed_identifier_list
* parameters
;
6104 *is_varargs
= false;
6105 imp
->require_c_string(" (");
6106 if (imp
->peek_char() == ')')
6110 parameters
= new Typed_identifier_list();
6113 std::string name
= imp
->read_name();
6114 std::string escape_note
= imp
->read_escape();
6115 imp
->require_c_string(" ");
6117 if (imp
->match_c_string("..."))
6123 Type
* ptype
= imp
->read_type();
6125 ptype
= Type::make_array_type(ptype
, NULL
);
6126 Typed_identifier t
= Typed_identifier(name
, ptype
, imp
->location());
6127 t
.set_note(escape_note
);
6128 parameters
->push_back(t
);
6129 if (imp
->peek_char() != ',')
6131 go_assert(!*is_varargs
);
6132 imp
->require_c_string(", ");
6135 imp
->require_c_string(")");
6136 *pparameters
= parameters
;
6138 Typed_identifier_list
* results
;
6139 if (imp
->peek_char() != ' ' || imp
->match_c_string(" <inl"))
6143 results
= new Typed_identifier_list();
6144 imp
->require_c_string(" ");
6145 if (imp
->peek_char() != '(')
6147 Type
* rtype
= imp
->read_type();
6148 results
->push_back(Typed_identifier("", rtype
, imp
->location()));
6152 imp
->require_c_string("(");
6155 std::string name
= imp
->read_name();
6156 std::string note
= imp
->read_escape();
6157 imp
->require_c_string(" ");
6158 Type
* rtype
= imp
->read_type();
6159 Typed_identifier t
= Typed_identifier(name
, rtype
,
6162 results
->push_back(t
);
6163 if (imp
->peek_char() != ',')
6165 imp
->require_c_string(", ");
6167 imp
->require_c_string(")");
6170 *presults
= results
;
6172 if (!imp
->match_c_string(" <inl:"))
6174 imp
->require_semicolon_if_old_version();
6175 imp
->require_c_string("\n");
6180 imp
->require_c_string(" <inl:");
6185 c
= imp
->peek_char();
6186 if (c
< '0' || c
> '9')
6191 imp
->require_c_string(">\n");
6195 long llen
= strtol(lenstr
.c_str(), &end
, 10);
6198 || (llen
== LONG_MAX
&& errno
== ERANGE
))
6200 go_error_at(imp
->location(), "invalid inline function length %s",
6205 imp
->read(static_cast<size_t>(llen
), body
);
6211 // Get the backend name.
6214 Function::backend_name(Gogo
* gogo
, Named_object
* no
, Backend_name
*bname
)
6216 if (!this->asm_name_
.empty())
6217 bname
->set_asm_name(this->asm_name_
);
6218 else if (no
->package() == NULL
&& no
->name() == gogo
->get_init_fn_name())
6220 // These names appear in the export data and are used
6221 // directly in the assembler code. If we change this here
6222 // we need to change Gogo::init_imports.
6223 bname
->set_asm_name(no
->name());
6225 else if (this->enclosing_
!= NULL
)
6227 // Rewrite the nested name to use the enclosing function name.
6228 // We don't do this earlier because we just store simple names
6229 // in a Named_object, not Backend_names.
6231 // The name was set by nested_function_name, which always
6232 // appends ..funcNNN. We want that to be our suffix.
6233 size_t pos
= no
->name().find("..func");
6234 go_assert(pos
!= std::string::npos
);
6236 Named_object
* enclosing
= this->enclosing_
;
6239 Named_object
* parent
= enclosing
->func_value()->enclosing();
6246 if (enclosing
->func_value()->type()->is_method())
6247 rtype
= enclosing
->func_value()->type()->receiver()->type();
6248 gogo
->function_backend_name(enclosing
->name(), enclosing
->package(),
6250 bname
->append_suffix(no
->name().substr(pos
));
6255 if (this->type_
->is_method())
6256 rtype
= this->type_
->receiver()->type();
6257 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6261 // Get the backend representation.
6264 Function::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6266 if (this->fndecl_
== NULL
)
6268 unsigned int flags
= 0;
6269 if (no
->package() != NULL
)
6271 // Functions defined in other packages must be visible.
6272 flags
|= Backend::function_is_visible
;
6274 else if (this->enclosing_
!= NULL
|| Gogo::is_thunk(no
))
6276 else if (Gogo::unpack_hidden_name(no
->name()) == "init"
6277 && !this->type_
->is_method())
6279 else if (no
->name() == gogo
->get_init_fn_name())
6280 flags
|= Backend::function_is_visible
;
6281 else if (Gogo::unpack_hidden_name(no
->name()) == "main"
6282 && gogo
->is_main_package())
6283 flags
|= Backend::function_is_visible
;
6284 // Methods have to be public even if they are hidden because
6285 // they can be pulled into type descriptors when using
6286 // anonymous fields.
6287 else if (!Gogo::is_hidden_name(no
->name())
6288 || this->type_
->is_method())
6290 if (!this->is_unnamed_type_stub_method_
)
6291 flags
|= Backend::function_is_visible
;
6294 if (!this->asm_name_
.empty())
6296 // If an assembler name is explicitly specified, there must
6297 // be some reason to refer to the symbol from a different
6299 flags
|= Backend::function_is_visible
;
6302 // If an inline body refers to this function, then it
6303 // needs to be visible in the symbol table.
6304 if (this->is_referenced_by_inline_
)
6305 flags
|= Backend::function_is_visible
;
6307 // A go:linkname directive can be used to force a function to be
6309 if (this->is_exported_by_linkname_
)
6310 flags
|= Backend::function_is_visible
;
6312 // If a function calls the predeclared recover function, we
6313 // can't inline it, because recover behaves differently in a
6314 // function passed directly to defer. If this is a recover
6315 // thunk that we built to test whether a function can be
6316 // recovered, we can't inline it, because that will mess up
6317 // our return address comparison.
6318 bool is_inlinable
= !(this->calls_recover_
|| this->is_recover_thunk_
);
6320 // If a function calls __go_set_defer_retaddr, then mark it as
6321 // uninlinable. This prevents the GCC backend from splitting
6322 // the function; splitting the function is a bad idea because we
6323 // want the return address label to be in the same function as
6325 if (this->calls_defer_retaddr_
)
6326 is_inlinable
= false;
6328 // Check the //go:noinline compiler directive.
6329 if ((this->pragmas_
& GOPRAGMA_NOINLINE
) != 0)
6330 is_inlinable
= false;
6333 flags
|= Backend::function_is_inlinable
;
6335 // If this is a thunk created to call a function which calls
6336 // the predeclared recover function, we need to disable
6337 // stack splitting for the thunk.
6338 bool disable_split_stack
= this->is_recover_thunk_
;
6340 // Check the //go:nosplit compiler directive.
6341 if ((this->pragmas_
& GOPRAGMA_NOSPLIT
) != 0)
6342 disable_split_stack
= true;
6344 if (disable_split_stack
)
6345 flags
|= Backend::function_no_split_stack
;
6347 // This should go into a unique section if that has been
6348 // requested elsewhere, or if this is a nointerface function.
6349 // We want to put a nointerface function into a unique section
6350 // because there is a good chance that the linker garbage
6351 // collection can discard it.
6352 if (this->in_unique_section_
6353 || (this->is_method() && this->nointerface()))
6354 flags
|= Backend::function_in_unique_section
;
6356 if (this->is_inline_only_
)
6357 flags
|= Backend::function_only_inline
;
6359 Btype
* functype
= this->type_
->get_backend_fntype(gogo
);
6362 this->backend_name(gogo
, no
, &bname
);
6364 this->fndecl_
= gogo
->backend()->function(functype
,
6366 bname
.optional_asm_name(),
6370 return this->fndecl_
;
6373 // Get the backend name.
6376 Function_declaration::backend_name(Gogo
* gogo
, Named_object
* no
,
6377 Backend_name
* bname
)
6379 if (!this->asm_name_
.empty())
6380 bname
->set_asm_name(this->asm_name_
);
6384 if (this->fntype_
->is_method())
6385 rtype
= this->fntype_
->receiver()->type();
6386 gogo
->function_backend_name(no
->name(), no
->package(), rtype
, bname
);
6390 // Get the backend representation.
6393 Function_declaration::get_or_make_decl(Gogo
* gogo
, Named_object
* no
)
6395 if (this->fndecl_
== NULL
)
6397 unsigned int flags
=
6398 (Backend::function_is_visible
6399 | Backend::function_is_declaration
6400 | Backend::function_is_inlinable
);
6402 // Let Go code use an asm declaration to pick up a builtin
6404 if (!this->asm_name_
.empty())
6406 Bfunction
* builtin_decl
=
6407 gogo
->backend()->lookup_builtin(this->asm_name_
);
6408 if (builtin_decl
!= NULL
)
6410 this->fndecl_
= builtin_decl
;
6411 return this->fndecl_
;
6414 if (this->asm_name_
== "runtime.gopanic"
6415 || this->asm_name_
.compare(0, 13, "runtime.panic") == 0
6416 || this->asm_name_
.compare(0, 15, "runtime.goPanic") == 0
6417 || this->asm_name_
== "runtime.block")
6418 flags
|= Backend::function_does_not_return
;
6421 Btype
* functype
= this->fntype_
->get_backend_fntype(gogo
);
6424 this->backend_name(gogo
, no
, &bname
);
6426 this->fndecl_
= gogo
->backend()->function(functype
,
6428 bname
.optional_asm_name(),
6433 return this->fndecl_
;
6436 // Build the descriptor for a function declaration. This won't
6437 // necessarily happen if the package has just a declaration for the
6438 // function and no other reference to it, but we may still need the
6439 // descriptor for references from other packages.
6441 Function_declaration::build_backend_descriptor(Gogo
* gogo
)
6443 if (this->descriptor_
!= NULL
)
6445 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
6446 this->descriptor_
->get_backend(&context
);
6450 // Check that the types used in this declaration's signature are defined.
6451 // Reports errors for any undefined type.
6454 Function_declaration::check_types() const
6456 // Calling Type::base will give errors for any undefined types.
6457 Function_type
* fntype
= this->type();
6458 if (fntype
->receiver() != NULL
)
6459 fntype
->receiver()->type()->base();
6460 if (fntype
->parameters() != NULL
)
6462 const Typed_identifier_list
* params
= fntype
->parameters();
6463 for (Typed_identifier_list::const_iterator p
= params
->begin();
6470 // Return the function's decl after it has been built.
6473 Function::get_decl() const
6475 go_assert(this->fndecl_
!= NULL
);
6476 return this->fndecl_
;
6479 // Build the backend representation for the function code.
6482 Function::build(Gogo
* gogo
, Named_object
* named_function
)
6484 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6486 // A list of parameter variables for this function.
6487 std::vector
<Bvariable
*> param_vars
;
6489 // Variables that need to be declared for this function and their
6491 std::vector
<Bvariable
*> vars
;
6492 std::vector
<Expression
*> var_inits
;
6493 std::vector
<Statement
*> var_decls_stmts
;
6494 for (Bindings::const_definitions_iterator p
=
6495 this->block_
->bindings()->begin_definitions();
6496 p
!= this->block_
->bindings()->end_definitions();
6499 Location loc
= (*p
)->location();
6500 if ((*p
)->is_variable() && (*p
)->var_value()->is_parameter())
6502 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6503 Bvariable
* parm_bvar
= bvar
;
6505 // We always pass the receiver to a method as a pointer. If
6506 // the receiver is declared as a non-pointer type, then we
6507 // copy the value into a local variable. For direct interface
6508 // type we pack the pointer into the type.
6509 if ((*p
)->var_value()->is_receiver()
6510 && (*p
)->var_value()->type()->points_to() == NULL
)
6512 std::string name
= (*p
)->name() + ".pointer";
6513 Type
* var_type
= (*p
)->var_value()->type();
6514 Variable
* parm_var
=
6515 new Variable(Type::make_pointer_type(var_type
), NULL
, false,
6517 Named_object
* parm_no
=
6518 Named_object::make_variable(name
, NULL
, parm_var
);
6519 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6521 vars
.push_back(bvar
);
6523 Expression
* parm_ref
=
6524 Expression::make_var_reference(parm_no
, loc
);
6525 Type
* recv_type
= (*p
)->var_value()->type();
6526 if (recv_type
->is_direct_iface_type())
6527 parm_ref
= Expression::pack_direct_iface(recv_type
, parm_ref
, loc
);
6530 Expression::make_dereference(parm_ref
,
6531 Expression::NIL_CHECK_NEEDED
,
6533 if ((*p
)->var_value()->is_in_heap())
6534 parm_ref
= Expression::make_heap_expression(parm_ref
, loc
);
6535 var_inits
.push_back(parm_ref
);
6537 else if ((*p
)->var_value()->is_in_heap())
6539 // If we take the address of a parameter, then we need
6540 // to copy it into the heap.
6541 std::string parm_name
= (*p
)->name() + ".param";
6542 Variable
* parm_var
= new Variable((*p
)->var_value()->type(), NULL
,
6543 false, true, false, loc
);
6544 Named_object
* parm_no
=
6545 Named_object::make_variable(parm_name
, NULL
, parm_var
);
6546 parm_bvar
= parm_no
->get_backend_variable(gogo
, named_function
);
6548 vars
.push_back(bvar
);
6549 Expression
* var_ref
=
6550 Expression::make_var_reference(parm_no
, loc
);
6551 var_ref
= Expression::make_heap_expression(var_ref
, loc
);
6552 var_inits
.push_back(var_ref
);
6554 param_vars
.push_back(parm_bvar
);
6556 else if ((*p
)->is_result_variable())
6558 Bvariable
* bvar
= (*p
)->get_backend_variable(gogo
, named_function
);
6560 Type
* type
= (*p
)->result_var_value()->type();
6562 if (!(*p
)->result_var_value()->is_in_heap())
6564 Btype
* btype
= type
->get_backend(gogo
);
6565 Bexpression
* binit
= gogo
->backend()->zero_expression(btype
);
6566 init
= Expression::make_backend(binit
, type
, loc
);
6569 init
= Expression::make_allocation(type
, loc
);
6571 vars
.push_back(bvar
);
6572 var_inits
.push_back(init
);
6574 else if (this->defer_stack_
!= NULL
6575 && (*p
)->is_variable()
6576 && (*p
)->var_value()->is_non_escaping_address_taken()
6577 && !(*p
)->var_value()->is_in_heap())
6579 // Local variable captured by deferred closure needs to be live
6580 // until the end of the function. We create a top-level
6581 // declaration for it.
6582 // TODO: we don't need to do this if the variable is not captured
6583 // by the defer closure. There is no easy way to check it here,
6584 // so we do this for all address-taken variables for now.
6585 Variable
* var
= (*p
)->var_value();
6586 Temporary_statement
* ts
=
6587 Statement::make_temporary(var
->type(), NULL
, var
->location());
6588 ts
->set_is_address_taken();
6589 var
->set_toplevel_decl(ts
);
6590 var_decls_stmts
.push_back(ts
);
6593 if (!gogo
->backend()->function_set_parameters(this->fndecl_
, param_vars
))
6595 go_assert(saw_errors());
6599 // If we need a closure variable, make sure to create it.
6600 // It gets installed in the function as a side effect of creation.
6601 if (this->closure_var_
!= NULL
)
6603 go_assert(this->closure_var_
->var_value()->is_closure());
6604 this->closure_var_
->get_backend_variable(gogo
, named_function
);
6607 if (this->block_
!= NULL
)
6609 // Declare variables if necessary.
6610 Bblock
* var_decls
= NULL
;
6611 std::vector
<Bstatement
*> var_decls_bstmt_list
;
6612 Bstatement
* defer_init
= NULL
;
6613 if (!vars
.empty() || this->defer_stack_
!= NULL
)
6616 gogo
->backend()->block(this->fndecl_
, NULL
, vars
,
6617 this->block_
->start_location(),
6618 this->block_
->end_location());
6620 if (this->defer_stack_
!= NULL
)
6622 Translate_context
dcontext(gogo
, named_function
, this->block_
,
6624 defer_init
= this->defer_stack_
->get_backend(&dcontext
);
6625 var_decls_bstmt_list
.push_back(defer_init
);
6626 for (std::vector
<Statement
*>::iterator p
= var_decls_stmts
.begin();
6627 p
!= var_decls_stmts
.end();
6630 Bstatement
* bstmt
= (*p
)->get_backend(&dcontext
);
6631 var_decls_bstmt_list
.push_back(bstmt
);
6636 // Build the backend representation for all the statements in the
6638 Translate_context
bcontext(gogo
, named_function
, NULL
, NULL
);
6639 Bblock
* code_block
= this->block_
->get_backend(&bcontext
);
6641 // Initialize variables if necessary.
6642 Translate_context
icontext(gogo
, named_function
, this->block_
,
6644 std::vector
<Bstatement
*> init
;
6645 go_assert(vars
.size() == var_inits
.size());
6646 for (size_t i
= 0; i
< vars
.size(); ++i
)
6648 Bexpression
* binit
= var_inits
[i
]->get_backend(&icontext
);
6649 Bstatement
* init_stmt
=
6650 gogo
->backend()->init_statement(this->fndecl_
, vars
[i
],
6652 init
.push_back(init_stmt
);
6654 Bstatement
* var_init
= gogo
->backend()->statement_list(init
);
6656 // Initialize all variables before executing this code block.
6657 Bstatement
* code_stmt
= gogo
->backend()->block_statement(code_block
);
6658 code_stmt
= gogo
->backend()->compound_statement(var_init
, code_stmt
);
6660 // If we have a defer stack, initialize it at the start of a
6662 Bstatement
* except
= NULL
;
6663 Bstatement
* fini
= NULL
;
6664 if (defer_init
!= NULL
)
6666 // Clean up the defer stack when we leave the function.
6667 this->build_defer_wrapper(gogo
, named_function
, &except
, &fini
);
6669 // Wrap the code for this function in an exception handler to handle
6672 gogo
->backend()->exception_handler_statement(code_stmt
,
6677 // Stick the code into the block we built for the receiver, if
6679 if (var_decls
!= NULL
)
6681 var_decls_bstmt_list
.push_back(code_stmt
);
6682 gogo
->backend()->block_add_statements(var_decls
, var_decls_bstmt_list
);
6683 code_stmt
= gogo
->backend()->block_statement(var_decls
);
6686 if (!gogo
->backend()->function_set_body(this->fndecl_
, code_stmt
))
6688 go_assert(saw_errors());
6693 // If we created a descriptor for the function, make sure we emit it.
6694 if (this->descriptor_
!= NULL
)
6696 Translate_context
dcontext(gogo
, NULL
, NULL
, NULL
);
6697 this->descriptor_
->get_backend(&dcontext
);
6701 // Build the wrappers around function code needed if the function has
6702 // any defer statements. This sets *EXCEPT to an exception handler
6703 // and *FINI to a finally handler.
6706 Function::build_defer_wrapper(Gogo
* gogo
, Named_object
* named_function
,
6707 Bstatement
** except
, Bstatement
** fini
)
6709 Location end_loc
= this->block_
->end_location();
6711 // Add an exception handler. This is used if a panic occurs. Its
6712 // purpose is to stop the stack unwinding if a deferred function
6713 // calls recover. There are more details in
6714 // libgo/runtime/go-unwind.c.
6716 std::vector
<Bstatement
*> stmts
;
6717 Expression
* call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6718 this->defer_stack(end_loc
));
6719 Translate_context
context(gogo
, named_function
, NULL
, NULL
);
6720 Bexpression
* defer
= call
->get_backend(&context
);
6721 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, defer
));
6723 Bstatement
* ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6724 if (ret_bstmt
!= NULL
)
6725 stmts
.push_back(ret_bstmt
);
6727 go_assert(*except
== NULL
);
6728 *except
= gogo
->backend()->statement_list(stmts
);
6730 call
= Runtime::make_call(Runtime::CHECKDEFER
, end_loc
, 1,
6731 this->defer_stack(end_loc
));
6732 defer
= call
->get_backend(&context
);
6734 call
= Runtime::make_call(Runtime::DEFERRETURN
, end_loc
, 1,
6735 this->defer_stack(end_loc
));
6736 Bexpression
* undefer
= call
->get_backend(&context
);
6737 Bstatement
* function_defer
=
6738 gogo
->backend()->function_defer_statement(this->fndecl_
, undefer
, defer
,
6740 stmts
= std::vector
<Bstatement
*>(1, function_defer
);
6741 if (this->type_
->results() != NULL
6742 && !this->type_
->results()->empty()
6743 && !this->type_
->results()->front().name().empty())
6745 // If the result variables are named, and we are returning from
6746 // this function rather than panicing through it, we need to
6747 // return them again, because they might have been changed by a
6748 // defer function. The runtime routines set the defer_stack
6749 // variable to true if we are returning from this function.
6751 ret_bstmt
= this->return_value(gogo
, named_function
, end_loc
);
6752 Bexpression
* nil
= Expression::make_nil(end_loc
)->get_backend(&context
);
6754 gogo
->backend()->compound_expression(ret_bstmt
, nil
, end_loc
);
6756 Expression::make_temporary_reference(this->defer_stack_
, end_loc
);
6757 Bexpression
* bref
= ref
->get_backend(&context
);
6758 ret
= gogo
->backend()->conditional_expression(this->fndecl_
,
6759 NULL
, bref
, ret
, NULL
,
6761 stmts
.push_back(gogo
->backend()->expression_statement(this->fndecl_
, ret
));
6764 go_assert(*fini
== NULL
);
6765 *fini
= gogo
->backend()->statement_list(stmts
);
6768 // Return the statement that assigns values to this function's result struct.
6771 Function::return_value(Gogo
* gogo
, Named_object
* named_function
,
6772 Location location
) const
6774 const Typed_identifier_list
* results
= this->type_
->results();
6775 if (results
== NULL
|| results
->empty())
6778 go_assert(this->results_
!= NULL
);
6779 if (this->results_
->size() != results
->size())
6781 go_assert(saw_errors());
6782 return gogo
->backend()->error_statement();
6785 std::vector
<Bexpression
*> vals(results
->size());
6786 for (size_t i
= 0; i
< vals
.size(); ++i
)
6788 Named_object
* no
= (*this->results_
)[i
];
6789 Bvariable
* bvar
= no
->get_backend_variable(gogo
, named_function
);
6790 Bexpression
* val
= gogo
->backend()->var_expression(bvar
, location
);
6791 if (no
->result_var_value()->is_in_heap())
6793 Btype
* bt
= no
->result_var_value()->type()->get_backend(gogo
);
6794 val
= gogo
->backend()->indirect_expression(bt
, val
, true, location
);
6798 return gogo
->backend()->return_statement(this->fndecl_
, vals
, location
);
6803 Block::Block(Block
* enclosing
, Location location
)
6804 : enclosing_(enclosing
), statements_(),
6805 bindings_(new Bindings(enclosing
== NULL
6807 : enclosing
->bindings())),
6808 start_location_(location
),
6809 end_location_(Linemap::unknown_location())
6813 // Add a statement to a block.
6816 Block::add_statement(Statement
* statement
)
6818 this->statements_
.push_back(statement
);
6821 // Add a statement to the front of a block. This is slow but is only
6822 // used for reference counts of parameters.
6825 Block::add_statement_at_front(Statement
* statement
)
6827 this->statements_
.insert(this->statements_
.begin(), statement
);
6830 // Replace a statement in a block.
6833 Block::replace_statement(size_t index
, Statement
* s
)
6835 go_assert(index
< this->statements_
.size());
6836 this->statements_
[index
] = s
;
6839 // Add a statement before another statement.
6842 Block::insert_statement_before(size_t index
, Statement
* s
)
6844 go_assert(index
< this->statements_
.size());
6845 this->statements_
.insert(this->statements_
.begin() + index
, s
);
6848 // Add a statement after another statement.
6851 Block::insert_statement_after(size_t index
, Statement
* s
)
6853 go_assert(index
< this->statements_
.size());
6854 this->statements_
.insert(this->statements_
.begin() + index
+ 1, s
);
6857 // Traverse the tree.
6860 Block::traverse(Traverse
* traverse
)
6862 unsigned int traverse_mask
= traverse
->traverse_mask();
6864 if ((traverse_mask
& Traverse::traverse_blocks
) != 0)
6866 int t
= traverse
->block(this);
6867 if (t
== TRAVERSE_EXIT
)
6868 return TRAVERSE_EXIT
;
6869 else if (t
== TRAVERSE_SKIP_COMPONENTS
)
6870 return TRAVERSE_CONTINUE
;
6874 & (Traverse::traverse_variables
6875 | Traverse::traverse_constants
6876 | Traverse::traverse_expressions
6877 | Traverse::traverse_types
)) != 0)
6879 for (Bindings::const_definitions_iterator pb
=
6880 this->bindings_
->begin_definitions();
6881 pb
!= this->bindings_
->end_definitions();
6884 if ((*pb
)->traverse(traverse
, false) == TRAVERSE_EXIT
)
6885 return TRAVERSE_EXIT
;
6889 // No point in checking traverse_mask here--if we got here we always
6890 // want to walk the statements. The traversal can insert new
6891 // statements before or after the current statement. Inserting
6892 // statements before the current statement requires updating I via
6893 // the pointer; those statements will not be traversed. Any new
6894 // statements inserted after the current statement will be traversed
6896 for (size_t i
= 0; i
< this->statements_
.size(); ++i
)
6898 if (this->statements_
[i
]->traverse(this, &i
, traverse
) == TRAVERSE_EXIT
)
6899 return TRAVERSE_EXIT
;
6902 return TRAVERSE_CONTINUE
;
6905 // Work out types for unspecified variables and constants.
6908 Block::determine_types()
6910 for (Bindings::const_definitions_iterator pb
=
6911 this->bindings_
->begin_definitions();
6912 pb
!= this->bindings_
->end_definitions();
6915 if ((*pb
)->is_variable())
6916 (*pb
)->var_value()->determine_type();
6917 else if ((*pb
)->is_const())
6918 (*pb
)->const_value()->determine_type();
6921 for (std::vector
<Statement
*>::const_iterator ps
= this->statements_
.begin();
6922 ps
!= this->statements_
.end();
6924 (*ps
)->determine_types();
6927 // Return true if the statements in this block may fall through.
6930 Block::may_fall_through() const
6932 if (this->statements_
.empty())
6934 return this->statements_
.back()->may_fall_through();
6937 // Write export data for a block.
6940 Block::export_block(Export_function_body
* efb
)
6942 for (Block::iterator p
= this->begin();
6948 efb
->increment_indent();
6949 (*p
)->export_statement(efb
);
6950 efb
->decrement_indent();
6952 Location loc
= (*p
)->location();
6953 if ((*p
)->is_block_statement())
6955 // For a block we put the start location on the first brace
6956 // in Block_statement::do_export_statement. Here we put the
6957 // end location on the final brace.
6958 loc
= (*p
)->block_statement()->block()->end_location();
6961 snprintf(buf
, sizeof buf
, " //%d\n", Linemap::location_to_line(loc
));
6962 efb
->write_c_string(buf
);
6966 // Add exported block data to SET, reading from BODY starting at OFF.
6967 // Returns whether the import succeeded.
6970 Block::import_block(Block
* set
, Import_function_body
*ifb
, Location loc
)
6972 Location eloc
= ifb
->location();
6973 Location sloc
= loc
;
6974 const std::string
& body(ifb
->body());
6975 size_t off
= ifb
->off();
6976 while (off
< body
.length())
6978 int indent
= ifb
->indent();
6979 if (off
+ indent
>= body
.length())
6982 "invalid export data for %qs: insufficient indentation",
6983 ifb
->name().c_str());
6986 for (int i
= 0; i
< indent
- 1; i
++)
6988 if (body
[off
+ i
] != ' ')
6991 "invalid export data for %qs: bad indentation",
6992 ifb
->name().c_str());
6997 bool at_end
= false;
6998 if (body
[off
+ indent
- 1] == '}')
7000 else if (body
[off
+ indent
- 1] != ' ')
7003 "invalid export data for %qs: bad indentation",
7004 ifb
->name().c_str());
7010 size_t nl
= body
.find('\n', off
);
7011 if (nl
== std::string::npos
)
7013 go_error_at(eloc
, "invalid export data for %qs: missing newline",
7014 ifb
->name().c_str());
7018 size_t lineno_pos
= body
.find(" //", off
);
7019 if (lineno_pos
== std::string::npos
|| lineno_pos
>= nl
)
7021 go_error_at(eloc
, "invalid export data for %qs: missing line number",
7022 ifb
->name().c_str());
7026 unsigned int lineno
= 0;
7027 for (size_t i
= lineno_pos
+ 3; i
< nl
; ++i
)
7030 if (c
< '0' || c
> '9')
7033 "invalid export data for %qs: invalid line number",
7034 ifb
->name().c_str());
7037 lineno
= lineno
* 10 + c
- '0';
7040 ifb
->gogo()->linemap()->start_line(lineno
, 1);
7041 sloc
= ifb
->gogo()->linemap()->get_location(0);
7045 // An if statement can have an "else" following the "}", in
7046 // which case we want to leave the offset where it is, just
7047 // after the "}". We don't get the block ending location
7048 // quite right for if statements.
7049 if (body
.compare(off
, 6, " else ") != 0)
7055 Statement
* s
= Statement::import_statement(ifb
, sloc
);
7059 set
->add_statement(s
);
7061 size_t at
= ifb
->off();
7069 set
->set_end_location(sloc
);
7073 // Convert a block to the backend representation.
7076 Block::get_backend(Translate_context
* context
)
7078 Gogo
* gogo
= context
->gogo();
7079 Named_object
* function
= context
->function();
7080 std::vector
<Bvariable
*> vars
;
7081 vars
.reserve(this->bindings_
->size_definitions());
7082 for (Bindings::const_definitions_iterator pv
=
7083 this->bindings_
->begin_definitions();
7084 pv
!= this->bindings_
->end_definitions();
7087 if ((*pv
)->is_variable() && !(*pv
)->var_value()->is_parameter())
7088 vars
.push_back((*pv
)->get_backend_variable(gogo
, function
));
7091 go_assert(function
!= NULL
);
7092 Bfunction
* bfunction
=
7093 function
->func_value()->get_or_make_decl(gogo
, function
);
7094 Bblock
* ret
= context
->backend()->block(bfunction
, context
->bblock(),
7095 vars
, this->start_location_
,
7096 this->end_location_
);
7098 Translate_context
subcontext(gogo
, function
, this, ret
);
7099 std::vector
<Bstatement
*> bstatements
;
7100 bstatements
.reserve(this->statements_
.size());
7101 for (std::vector
<Statement
*>::const_iterator p
= this->statements_
.begin();
7102 p
!= this->statements_
.end();
7104 bstatements
.push_back((*p
)->get_backend(&subcontext
));
7106 context
->backend()->block_add_statements(ret
, bstatements
);
7111 // Class Bindings_snapshot.
7113 Bindings_snapshot::Bindings_snapshot(const Block
* b
, Location location
)
7114 : block_(b
), counts_(), location_(location
)
7118 this->counts_
.push_back(b
->bindings()->size_definitions());
7123 // Report errors appropriate for a goto from B to this.
7126 Bindings_snapshot::check_goto_from(const Block
* b
, Location loc
)
7129 if (!this->check_goto_block(loc
, b
, this->block_
, &dummy
))
7131 this->check_goto_defs(loc
, this->block_
,
7132 this->block_
->bindings()->size_definitions(),
7136 // Report errors appropriate for a goto from this to B.
7139 Bindings_snapshot::check_goto_to(const Block
* b
)
7142 if (!this->check_goto_block(this->location_
, this->block_
, b
, &index
))
7144 this->check_goto_defs(this->location_
, b
, this->counts_
[index
],
7145 b
->bindings()->size_definitions());
7148 // Report errors appropriate for a goto at LOC from BFROM to BTO.
7149 // Return true if all is well, false if we reported an error. If this
7150 // returns true, it sets *PINDEX to the number of blocks BTO is above
7154 Bindings_snapshot::check_goto_block(Location loc
, const Block
* bfrom
,
7155 const Block
* bto
, size_t* pindex
)
7157 // It is an error if BTO is not either BFROM or above BFROM.
7159 for (const Block
* pb
= bfrom
; pb
!= bto
; pb
= pb
->enclosing(), ++index
)
7163 go_error_at(loc
, "goto jumps into block");
7164 go_inform(bto
->start_location(), "goto target block starts here");
7172 // Report errors appropriate for a goto at LOC ending at BLOCK, where
7173 // CFROM is the number of names defined at the point of the goto and
7174 // CTO is the number of names defined at the point of the label.
7177 Bindings_snapshot::check_goto_defs(Location loc
, const Block
* block
,
7178 size_t cfrom
, size_t cto
)
7182 Bindings::const_definitions_iterator p
=
7183 block
->bindings()->begin_definitions();
7184 for (size_t i
= 0; i
< cfrom
; ++i
)
7186 go_assert(p
!= block
->bindings()->end_definitions());
7189 go_assert(p
!= block
->bindings()->end_definitions());
7191 for (; p
!= block
->bindings()->end_definitions(); ++p
)
7193 if ((*p
)->is_variable())
7195 std::string n
= (*p
)->message_name();
7196 go_error_at(loc
, "goto jumps over declaration of %qs", n
.c_str());
7197 go_inform((*p
)->location(), "%qs defined here", n
.c_str());
7203 // Class Function_declaration.
7205 // Whether this declares a method.
7208 Function_declaration::is_method() const
7210 return this->fntype_
->is_method();
7213 // Whether this method should not be included in the type descriptor.
7216 Function_declaration::nointerface() const
7218 go_assert(this->is_method());
7219 return (this->pragmas_
& GOPRAGMA_NOINTERFACE
) != 0;
7222 // Record that this method should not be included in the type
7226 Function_declaration::set_nointerface()
7228 this->pragmas_
|= GOPRAGMA_NOINTERFACE
;
7231 // Set the receiver type. This is used to remove aliases.
7234 Function_declaration::set_receiver_type(Type
* rtype
)
7236 Function_type
* oft
= this->fntype_
;
7237 Typed_identifier
* rec
= new Typed_identifier(oft
->receiver()->name(),
7239 oft
->receiver()->location());
7240 Typed_identifier_list
* parameters
= NULL
;
7241 if (oft
->parameters() != NULL
)
7242 parameters
= oft
->parameters()->copy();
7243 Typed_identifier_list
* results
= NULL
;
7244 if (oft
->results() != NULL
)
7245 results
= oft
->results()->copy();
7246 Function_type
* nft
= Type::make_function_type(rec
, parameters
, results
,
7248 this->fntype_
= nft
;
7251 // Import an inlinable function. This is used for an inlinable
7252 // function whose body is recorded in the export data. Parse the
7253 // export data into a Block and create a regular function using that
7254 // Block as its body. Redeclare this function declaration as the
7258 Function_declaration::import_function_body(Gogo
* gogo
, Named_object
* no
)
7260 go_assert(no
->func_declaration_value() == this);
7261 go_assert(no
->package() != NULL
);
7262 const std::string
& body(this->imported_body_
);
7263 go_assert(!body
.empty());
7265 // Read the "//FILE:LINE" comment starts the export data.
7268 if (this->is_method())
7271 for (; i
< indent
; i
++)
7273 if (body
.at(i
) != ' ')
7275 go_error_at(this->location_
,
7276 "invalid export body for %qs: bad initial indentation",
7277 no
->message_name().c_str());
7282 if (body
.substr(i
, 2) != "//")
7284 go_error_at(this->location_
,
7285 "invalid export body for %qs: missing file comment",
7286 no
->message_name().c_str());
7290 size_t colon
= body
.find(':', i
+ 2);
7291 size_t nl
= body
.find('\n', i
+ 2);
7292 if (nl
== std::string::npos
)
7294 go_error_at(this->location_
,
7295 "invalid export body for %qs: missing file name",
7296 no
->message_name().c_str());
7299 if (colon
== std::string::npos
|| nl
< colon
)
7301 go_error_at(this->location_
,
7302 "invalid export body for %qs: missing initial line number",
7303 no
->message_name().c_str());
7307 std::string file
= body
.substr(i
+ 2, colon
- (i
+ 2));
7308 std::string linestr
= body
.substr(colon
+ 1, nl
- (colon
+ 1));
7310 long linenol
= strtol(linestr
.c_str(), &end
, 10);
7313 go_error_at(this->location_
,
7314 "invalid export body for %qs: invalid initial line number",
7315 no
->message_name().c_str());
7318 unsigned int lineno
= static_cast<unsigned int>(linenol
);
7320 // Turn the file/line into a location.
7322 char* alc
= new char[file
.length() + 1];
7323 memcpy(alc
, file
.data(), file
.length());
7324 alc
[file
.length()] = '\0';
7325 gogo
->linemap()->start_file(alc
, lineno
);
7326 gogo
->linemap()->start_line(lineno
, 1);
7327 Location start_loc
= gogo
->linemap()->get_location(0);
7329 // Define the function with an outer block that declares the
7332 Function_type
* fntype
= this->fntype_
;
7334 Block
* outer
= new Block(NULL
, start_loc
);
7336 Function
* fn
= new Function(fntype
, NULL
, outer
, start_loc
);
7337 fn
->set_is_inline_only();
7339 if (fntype
->is_method())
7341 if (this->nointerface())
7342 fn
->set_nointerface();
7343 const Typed_identifier
* receiver
= fntype
->receiver();
7344 Variable
* recv_param
= new Variable(receiver
->type(), NULL
, false,
7345 true, true, start_loc
);
7347 std::string rname
= receiver
->name();
7348 unsigned rcounter
= 0;
7350 // We need to give a nameless receiver a name to avoid having it
7351 // clash with some other nameless param. FIXME.
7352 Gogo::rename_if_empty(&rname
, "r", &rcounter
);
7354 outer
->bindings()->add_variable(rname
, NULL
, recv_param
);
7357 const Typed_identifier_list
* params
= fntype
->parameters();
7358 bool is_varargs
= fntype
->is_varargs();
7359 unsigned pcounter
= 0;
7362 for (Typed_identifier_list::const_iterator p
= params
->begin();
7366 Variable
* param
= new Variable(p
->type(), NULL
, false, true, false,
7368 if (is_varargs
&& p
+ 1 == params
->end())
7369 param
->set_is_varargs_parameter();
7371 std::string pname
= p
->name();
7373 // We need to give each nameless parameter a non-empty name to avoid
7374 // having it clash with some other nameless param. FIXME.
7375 Gogo::rename_if_empty(&pname
, "p", &pcounter
);
7377 outer
->bindings()->add_variable(pname
, NULL
, param
);
7381 fn
->create_result_variables(gogo
);
7383 if (!fntype
->is_method())
7385 const Package
* package
= no
->package();
7386 no
= package
->bindings()->add_function(no
->name(), package
, fn
);
7390 Named_type
* rtype
= fntype
->receiver()->type()->deref()->named_type();
7391 go_assert(rtype
!= NULL
);
7392 no
= rtype
->add_method(no
->name(), fn
);
7393 const Package
* package
= rtype
->named_object()->package();
7394 package
->bindings()->add_method(no
);
7397 Import_function_body
ifb(gogo
, this->imp_
, no
, body
, nl
+ 1, outer
, indent
);
7399 if (!Block::import_block(outer
, &ifb
, start_loc
))
7402 gogo
->lower_block(no
, outer
);
7403 outer
->determine_types();
7405 gogo
->add_imported_inline_function(no
);
7408 // Return the function descriptor.
7411 Function_declaration::descriptor(Gogo
*, Named_object
* no
)
7413 go_assert(!this->fntype_
->is_method());
7414 if (this->descriptor_
== NULL
)
7415 this->descriptor_
= Expression::make_func_descriptor(no
);
7416 return this->descriptor_
;
7421 Variable::Variable(Type
* type
, Expression
* init
, bool is_global
,
7422 bool is_parameter
, bool is_receiver
,
7424 : type_(type
), init_(init
), preinit_(NULL
), location_(location
),
7425 embeds_(NULL
), backend_(NULL
), is_global_(is_global
),
7426 is_parameter_(is_parameter
), is_closure_(false), is_receiver_(is_receiver
),
7427 is_varargs_parameter_(false), is_global_sink_(false), is_used_(false),
7428 is_address_taken_(false), is_non_escaping_address_taken_(false),
7429 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
7430 type_from_init_tuple_(false), type_from_range_index_(false),
7431 type_from_range_value_(false), type_from_chan_element_(false),
7432 is_type_switch_var_(false), determined_type_(false),
7433 in_unique_section_(false), is_referenced_by_inline_(false),
7434 toplevel_decl_(NULL
)
7436 go_assert(type
!= NULL
|| init
!= NULL
);
7437 go_assert(!is_parameter
|| init
== NULL
);
7440 // Traverse the initializer expression.
7443 Variable::traverse_expression(Traverse
* traverse
, unsigned int traverse_mask
)
7445 if (this->preinit_
!= NULL
)
7447 if (this->preinit_
->traverse(traverse
) == TRAVERSE_EXIT
)
7448 return TRAVERSE_EXIT
;
7450 if (this->init_
!= NULL
7452 & (Traverse::traverse_expressions
| Traverse::traverse_types
))
7455 if (Expression::traverse(&this->init_
, traverse
) == TRAVERSE_EXIT
)
7456 return TRAVERSE_EXIT
;
7458 return TRAVERSE_CONTINUE
;
7461 // Lower the initialization expression after parsing is complete.
7464 Variable::lower_init_expression(Gogo
* gogo
, Named_object
* function
,
7465 Statement_inserter
* inserter
)
7467 Named_object
* dep
= gogo
->var_depends_on(this);
7468 if (dep
!= NULL
&& dep
->is_variable())
7469 dep
->var_value()->lower_init_expression(gogo
, function
, inserter
);
7471 if (this->embeds_
!= NULL
)
7473 // Now that we have seen any possible type aliases, convert the
7474 // go:embed directives into an initializer.
7475 go_assert(this->init_
== NULL
&& this->type_
!= NULL
);
7476 this->init_
= gogo
->initializer_for_embeds(this->type_
, this->embeds_
,
7478 delete this->embeds_
;
7479 this->embeds_
= NULL
;
7482 if (this->init_
!= NULL
&& !this->init_is_lowered_
)
7486 // We will give an error elsewhere, this is just to prevent
7487 // an infinite loop.
7492 Statement_inserter global_inserter
;
7493 if (this->is_global_
)
7495 global_inserter
= Statement_inserter(gogo
, this);
7496 inserter
= &global_inserter
;
7499 gogo
->lower_expression(function
, inserter
, &this->init_
);
7501 this->seen_
= false;
7503 this->init_is_lowered_
= true;
7507 // Flatten the initialization expression after ordering evaluations.
7510 Variable::flatten_init_expression(Gogo
* gogo
, Named_object
* function
,
7511 Statement_inserter
* inserter
)
7513 Named_object
* dep
= gogo
->var_depends_on(this);
7514 if (dep
!= NULL
&& dep
->is_variable())
7515 dep
->var_value()->flatten_init_expression(gogo
, function
, inserter
);
7517 if (this->init_
!= NULL
&& !this->init_is_flattened_
)
7521 // We will give an error elsewhere, this is just to prevent
7522 // an infinite loop.
7527 Statement_inserter global_inserter
;
7528 if (this->is_global_
)
7530 global_inserter
= Statement_inserter(gogo
, this);
7531 inserter
= &global_inserter
;
7534 gogo
->flatten_expression(function
, inserter
, &this->init_
);
7536 // If an interface conversion is needed, we need a temporary
7538 if (this->type_
!= NULL
7539 && !Type::are_identical(this->type_
, this->init_
->type(),
7540 Type::COMPARE_ERRORS
| Type::COMPARE_TAGS
,
7542 && this->init_
->type()->interface_type() != NULL
7543 && !this->init_
->is_multi_eval_safe())
7545 Temporary_statement
* temp
=
7546 Statement::make_temporary(NULL
, this->init_
, this->location_
);
7547 inserter
->insert(temp
);
7548 this->init_
= Expression::make_temporary_reference(temp
,
7552 this->seen_
= false;
7553 this->init_is_flattened_
= true;
7557 // Get the preinit block.
7560 Variable::preinit_block(Gogo
* gogo
)
7562 go_assert(this->is_global_
);
7563 if (this->preinit_
== NULL
)
7564 this->preinit_
= new Block(NULL
, this->location());
7566 // If a global variable has a preinitialization statement, then we
7567 // need to have an initialization function.
7568 gogo
->set_need_init_fn();
7570 return this->preinit_
;
7573 // Add a statement to be run before the initialization expression.
7576 Variable::add_preinit_statement(Gogo
* gogo
, Statement
* s
)
7578 Block
* b
= this->preinit_block(gogo
);
7579 b
->add_statement(s
);
7580 b
->set_end_location(s
->location());
7583 // Whether this variable has a type.
7586 Variable::has_type() const
7588 if (this->type_
== NULL
)
7591 // A variable created in a type switch case nil does not actually
7592 // have a type yet. It will be changed to use the initializer's
7593 // type in determine_type.
7594 if (this->is_type_switch_var_
7595 && this->type_
->is_nil_constant_as_type())
7601 // In an assignment which sets a variable to a tuple of EXPR, return
7602 // the type of the first element of the tuple.
7605 Variable::type_from_tuple(Expression
* expr
, bool report_error
) const
7607 if (expr
->map_index_expression() != NULL
)
7609 Map_type
* mt
= expr
->map_index_expression()->get_map_type();
7611 return Type::make_error_type();
7612 return mt
->val_type();
7614 else if (expr
->receive_expression() != NULL
)
7616 Expression
* channel
= expr
->receive_expression()->channel();
7617 Type
* channel_type
= channel
->type();
7618 if (channel_type
->channel_type() == NULL
)
7619 return Type::make_error_type();
7620 return channel_type
->channel_type()->element_type();
7625 go_error_at(this->location(), "invalid tuple definition");
7626 return Type::make_error_type();
7630 // Given EXPR used in a range clause, return either the index type or
7631 // the value type of the range, depending upon GET_INDEX_TYPE.
7634 Variable::type_from_range(Expression
* expr
, bool get_index_type
,
7635 bool report_error
) const
7637 Type
* t
= expr
->type();
7638 if (t
->array_type() != NULL
7639 || (t
->points_to() != NULL
7640 && t
->points_to()->array_type() != NULL
7641 && !t
->points_to()->is_slice_type()))
7644 return Type::lookup_integer_type("int");
7646 return t
->deref()->array_type()->element_type();
7648 else if (t
->is_string_type())
7651 return Type::lookup_integer_type("int");
7653 return Type::lookup_integer_type("int32");
7655 else if (t
->map_type() != NULL
)
7658 return t
->map_type()->key_type();
7660 return t
->map_type()->val_type();
7662 else if (t
->channel_type() != NULL
)
7665 return t
->channel_type()->element_type();
7669 go_error_at(this->location(),
7670 ("invalid definition of value variable "
7671 "for channel range"));
7672 return Type::make_error_type();
7678 go_error_at(this->location(), "invalid type for range clause");
7679 return Type::make_error_type();
7683 // EXPR should be a channel. Return the channel's element type.
7686 Variable::type_from_chan_element(Expression
* expr
, bool report_error
) const
7688 Type
* t
= expr
->type();
7689 if (t
->channel_type() != NULL
)
7690 return t
->channel_type()->element_type();
7694 go_error_at(this->location(), "expected channel");
7695 return Type::make_error_type();
7699 // Return the type of the Variable. This may be called before
7700 // Variable::determine_type is called, which means that we may need to
7701 // get the type from the initializer. FIXME: If we combine lowering
7702 // with type determination, then this should be unnecessary.
7707 // A variable in a type switch with a nil case will have the wrong
7708 // type here. This gets fixed up in determine_type, below.
7709 Type
* type
= this->type_
;
7710 Expression
* init
= this->init_
;
7711 if (this->is_type_switch_var_
7713 && this->type_
->is_nil_constant_as_type())
7715 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7716 go_assert(tge
!= NULL
);
7723 if (this->type_
== NULL
|| !this->type_
->is_error_type())
7725 go_error_at(this->location_
, "variable initializer refers to itself");
7726 this->type_
= Type::make_error_type();
7735 else if (this->type_from_init_tuple_
)
7736 type
= this->type_from_tuple(init
, false);
7737 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7738 type
= this->type_from_range(init
, this->type_from_range_index_
, false);
7739 else if (this->type_from_chan_element_
)
7740 type
= this->type_from_chan_element(init
, false);
7743 go_assert(init
!= NULL
);
7744 type
= init
->type();
7745 go_assert(type
!= NULL
);
7747 // Variables should not have abstract types.
7748 if (type
->is_abstract())
7749 type
= type
->make_non_abstract_type();
7751 if (type
->is_void_type())
7752 type
= Type::make_error_type();
7755 this->seen_
= false;
7760 // Fetch the type from a const pointer, in which case it should have
7761 // been set already.
7764 Variable::type() const
7766 go_assert(this->type_
!= NULL
);
7770 // Set the type if necessary.
7773 Variable::determine_type()
7775 if (this->determined_type_
)
7777 this->determined_type_
= true;
7779 if (this->preinit_
!= NULL
)
7780 this->preinit_
->determine_types();
7782 // A variable in a type switch with a nil case will have the wrong
7783 // type here. It will have an initializer which is a type guard.
7784 // We want to initialize it to the value without the type guard, and
7785 // use the type of that value as well.
7786 if (this->is_type_switch_var_
7787 && this->type_
!= NULL
7788 && this->type_
->is_nil_constant_as_type())
7790 Type_guard_expression
* tge
= this->init_
->type_guard_expression();
7791 go_assert(tge
!= NULL
);
7793 this->init_
= tge
->expr();
7796 if (this->init_
== NULL
)
7797 go_assert(this->type_
!= NULL
&& !this->type_
->is_abstract());
7798 else if (this->type_from_init_tuple_
)
7800 Expression
*init
= this->init_
;
7801 init
->determine_type_no_context();
7802 this->type_
= this->type_from_tuple(init
, true);
7805 else if (this->type_from_range_index_
|| this->type_from_range_value_
)
7807 Expression
* init
= this->init_
;
7808 init
->determine_type_no_context();
7809 this->type_
= this->type_from_range(init
, this->type_from_range_index_
,
7813 else if (this->type_from_chan_element_
)
7815 Expression
* init
= this->init_
;
7816 init
->determine_type_no_context();
7817 this->type_
= this->type_from_chan_element(init
, true);
7822 Type_context
context(this->type_
, false);
7823 this->init_
->determine_type(&context
);
7824 if (this->type_
== NULL
)
7826 Type
* type
= this->init_
->type();
7827 go_assert(type
!= NULL
);
7828 if (type
->is_abstract())
7829 type
= type
->make_non_abstract_type();
7831 if (type
->is_void_type())
7833 go_error_at(this->location_
, "variable has no type");
7834 type
= Type::make_error_type();
7836 else if (type
->is_nil_type())
7838 go_error_at(this->location_
, "variable defined to nil type");
7839 type
= Type::make_error_type();
7841 else if (type
->is_call_multiple_result_type())
7843 go_error_at(this->location_
,
7844 "single variable set to multiple-value function call");
7845 type
= Type::make_error_type();
7853 // Get the initial value of a variable. This does not
7854 // consider whether the variable is in the heap--it returns the
7855 // initial value as though it were always stored in the stack.
7858 Variable::get_init(Gogo
* gogo
, Named_object
* function
)
7860 go_assert(this->preinit_
== NULL
);
7861 Location loc
= this->location();
7862 if (this->init_
== NULL
)
7864 go_assert(!this->is_parameter_
);
7865 if (this->is_global_
|| this->is_in_heap())
7867 Btype
* btype
= this->type()->get_backend(gogo
);
7868 return gogo
->backend()->zero_expression(btype
);
7872 Translate_context
context(gogo
, function
, NULL
, NULL
);
7873 Expression
* init
= Expression::make_cast(this->type(), this->init_
, loc
);
7874 return init
->get_backend(&context
);
7878 // Get the initial value of a variable when a block is required.
7879 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
7882 Variable::get_init_block(Gogo
* gogo
, Named_object
* function
,
7883 Bvariable
* var_decl
)
7885 go_assert(this->preinit_
!= NULL
);
7887 // We want to add the variable assignment to the end of the preinit
7890 Translate_context
context(gogo
, function
, NULL
, NULL
);
7891 Bblock
* bblock
= this->preinit_
->get_backend(&context
);
7892 Bfunction
* bfunction
=
7893 function
->func_value()->get_or_make_decl(gogo
, function
);
7895 // It's possible to have pre-init statements without an initializer
7896 // if the pre-init statements set the variable.
7897 Bstatement
* decl_init
= NULL
;
7898 if (this->init_
!= NULL
)
7900 if (var_decl
== NULL
)
7902 Bexpression
* init_bexpr
= this->init_
->get_backend(&context
);
7903 decl_init
= gogo
->backend()->expression_statement(bfunction
,
7908 Location loc
= this->location();
7909 Expression
* val_expr
=
7910 Expression::make_cast(this->type(), this->init_
, loc
);
7911 Bexpression
* val
= val_expr
->get_backend(&context
);
7912 Bexpression
* var_ref
=
7913 gogo
->backend()->var_expression(var_decl
, loc
);
7914 decl_init
= gogo
->backend()->assignment_statement(bfunction
, var_ref
,
7918 Bstatement
* block_stmt
= gogo
->backend()->block_statement(bblock
);
7919 if (decl_init
!= NULL
)
7920 block_stmt
= gogo
->backend()->compound_statement(block_stmt
, decl_init
);
7924 // Export the variable
7927 Variable::export_var(Export
* exp
, const Named_object
* no
) const
7929 go_assert(this->is_global_
);
7930 exp
->write_c_string("var ");
7931 if (no
->package() != NULL
)
7934 snprintf(buf
, sizeof buf
, "<p%d>", exp
->package_index(no
->package()));
7935 exp
->write_c_string(buf
);
7938 if (!Gogo::is_hidden_name(no
->name()))
7939 exp
->write_string(no
->name());
7942 exp
->write_c_string(".");
7943 exp
->write_string(Gogo::unpack_hidden_name(no
->name()));
7946 exp
->write_c_string(" ");
7947 exp
->write_type(this->type());
7948 exp
->write_c_string("\n");
7951 // Import a variable.
7954 Variable::import_var(Import
* imp
, std::string
* pname
, Package
** ppkg
,
7955 bool* pis_exported
, Type
** ptype
)
7957 imp
->require_c_string("var ");
7958 if (!Import::read_qualified_identifier(imp
, pname
, ppkg
, pis_exported
))
7960 go_error_at(imp
->location(),
7961 "import error at %d: bad variable name in export data",
7965 imp
->require_c_string(" ");
7966 *ptype
= imp
->read_type();
7967 imp
->require_semicolon_if_old_version();
7968 imp
->require_c_string("\n");
7972 // Convert a variable to the backend representation.
7975 Variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
7976 const Package
* package
, const std::string
& name
)
7978 if (this->backend_
== NULL
)
7980 Backend
* backend
= gogo
->backend();
7981 Type
* type
= this->type_
;
7982 if (type
->is_error_type()
7983 || (type
->is_undefined()
7984 && (!this->is_global_
|| package
== NULL
)))
7985 this->backend_
= backend
->error_variable();
7988 bool is_parameter
= this->is_parameter_
;
7989 if (this->is_receiver_
&& type
->points_to() == NULL
)
7990 is_parameter
= false;
7991 if (this->is_in_heap())
7993 is_parameter
= false;
7994 type
= Type::make_pointer_type(type
);
7997 Btype
* btype
= type
->get_backend(gogo
);
8000 if (Map_type::is_zero_value(this))
8001 bvar
= Map_type::backend_zero_value(gogo
);
8002 else if (this->is_global_
)
8005 gogo
->global_var_backend_name(name
, package
, &bname
);
8007 bool is_hidden
= Gogo::is_hidden_name(name
);
8008 // Hack to export runtime.writeBarrier. FIXME.
8009 // This is because go:linkname doesn't work on variables.
8010 if (gogo
->compiling_runtime()
8011 && bname
.name() == "runtime.writeBarrier")
8014 // If an inline body refers to this variable, then it
8015 // needs to be visible in the symbol table.
8016 if (this->is_referenced_by_inline_
)
8019 // If this variable is in a different package, then it
8020 // can't be treated as a hidden symbol. This case can
8021 // arise when an inlined function refers to a
8022 // package-scope unexported variable.
8023 if (package
!= NULL
)
8026 unsigned int flags
= 0;
8027 if (this->is_address_taken_
8028 || this->is_non_escaping_address_taken_
)
8029 flags
|= Backend::variable_address_is_taken
;
8030 if (package
!= NULL
)
8031 flags
|= Backend::variable_is_external
;
8033 flags
|= Backend::variable_is_hidden
;
8034 if (this->in_unique_section_
)
8035 flags
|= Backend::variable_in_unique_section
;
8037 // For some reason asm_name can't be the empty string
8038 // for global_variable, so we call asm_name rather than
8039 // optional_asm_name here. FIXME.
8041 bvar
= backend
->global_variable(bname
.name(),
8046 else if (function
== NULL
)
8048 go_assert(saw_errors());
8049 bvar
= backend
->error_variable();
8053 const std::string n
= Gogo::unpack_hidden_name(name
);
8054 Bfunction
* bfunction
= function
->func_value()->get_decl();
8055 unsigned int flags
= 0;
8056 if (this->is_non_escaping_address_taken_
8057 && !this->is_in_heap())
8058 flags
|= Backend::variable_address_is_taken
;
8059 if (this->is_closure())
8060 bvar
= backend
->static_chain_variable(bfunction
, n
, btype
,
8061 flags
, this->location_
);
8062 else if (is_parameter
)
8063 bvar
= backend
->parameter_variable(bfunction
, n
, btype
,
8064 flags
, this->location_
);
8067 Bvariable
* bvar_decl
= NULL
;
8068 if (this->toplevel_decl_
!= NULL
)
8070 Translate_context
context(gogo
, NULL
, NULL
, NULL
);
8071 bvar_decl
= this->toplevel_decl_
->temporary_statement()
8072 ->get_backend_variable(&context
);
8074 bvar
= backend
->local_variable(bfunction
, n
, btype
,
8079 this->backend_
= bvar
;
8082 return this->backend_
;
8085 // Class Result_variable.
8087 // Convert a result variable to the backend representation.
8090 Result_variable::get_backend_variable(Gogo
* gogo
, Named_object
* function
,
8091 const std::string
& name
)
8093 if (this->backend_
== NULL
)
8095 Backend
* backend
= gogo
->backend();
8096 Type
* type
= this->type_
;
8097 if (type
->is_error())
8098 this->backend_
= backend
->error_variable();
8101 if (this->is_in_heap())
8102 type
= Type::make_pointer_type(type
);
8103 Btype
* btype
= type
->get_backend(gogo
);
8104 Bfunction
* bfunction
= function
->func_value()->get_decl();
8105 std::string n
= Gogo::unpack_hidden_name(name
);
8106 unsigned int flags
= 0;
8107 if (this->is_non_escaping_address_taken_
8108 && !this->is_in_heap())
8109 flags
|= Backend::variable_address_is_taken
;
8110 this->backend_
= backend
->local_variable(bfunction
, n
, btype
,
8115 return this->backend_
;
8118 // Class Named_constant.
8120 // Set the type of a named constant. This is only used to set the
8121 // type to an error type.
8124 Named_constant::set_type(Type
* t
)
8126 go_assert(this->type_
== NULL
|| t
->is_error_type());
8130 // Traverse the initializer expression.
8133 Named_constant::traverse_expression(Traverse
* traverse
)
8135 return Expression::traverse(&this->expr_
, traverse
);
8138 // Determine the type of the constant.
8141 Named_constant::determine_type()
8143 if (this->type_
!= NULL
)
8145 Type_context
context(this->type_
, false);
8146 this->expr_
->determine_type(&context
);
8150 // A constant may have an abstract type.
8151 Type_context
context(NULL
, true);
8152 this->expr_
->determine_type(&context
);
8153 this->type_
= this->expr_
->type();
8154 go_assert(this->type_
!= NULL
);
8158 // Indicate that we found and reported an error for this constant.
8161 Named_constant::set_error()
8163 this->type_
= Type::make_error_type();
8164 this->expr_
= Expression::make_error(this->location_
);
8167 // Export a constant.
8170 Named_constant::export_const(Export
* exp
, const std::string
& name
) const
8172 exp
->write_c_string("const ");
8173 exp
->write_string(name
);
8174 exp
->write_c_string(" ");
8175 if (!this->type_
->is_abstract())
8177 exp
->write_type(this->type_
);
8178 exp
->write_c_string(" ");
8180 exp
->write_c_string("= ");
8182 Export_function_body
efb(exp
, 0);
8183 if (!this->type_
->is_abstract())
8184 efb
.set_type_context(this->type_
);
8185 this->expr()->export_expression(&efb
);
8186 exp
->write_string(efb
.body());
8188 exp
->write_c_string("\n");
8191 // Import a constant.
8194 Named_constant::import_const(Import
* imp
, std::string
* pname
, Type
** ptype
,
8197 imp
->require_c_string("const ");
8198 *pname
= imp
->read_identifier();
8199 imp
->require_c_string(" ");
8200 if (imp
->peek_char() == '=')
8204 *ptype
= imp
->read_type();
8205 imp
->require_c_string(" ");
8207 imp
->require_c_string("= ");
8208 *pexpr
= Expression::import_expression(imp
, imp
->location());
8209 imp
->require_semicolon_if_old_version();
8210 imp
->require_c_string("\n");
8213 // Get the backend representation.
8216 Named_constant::get_backend(Gogo
* gogo
, Named_object
* const_no
)
8218 if (this->bconst_
== NULL
)
8220 Translate_context
subcontext(gogo
, NULL
, NULL
, NULL
);
8221 Type
* type
= this->type();
8222 Location loc
= this->location();
8224 Expression
* const_ref
= Expression::make_const_reference(const_no
, loc
);
8225 Bexpression
* const_decl
= const_ref
->get_backend(&subcontext
);
8226 if (type
!= NULL
&& type
->is_numeric_type())
8228 Btype
* btype
= type
->get_backend(gogo
);
8230 if (const_no
->package() == NULL
)
8231 name
= gogo
->pkgpath();
8233 name
= const_no
->package()->pkgpath();
8234 name
.push_back('.');
8235 name
.append(Gogo::unpack_hidden_name(const_no
->name()));
8237 gogo
->backend()->named_constant_expression(btype
, name
,
8240 this->bconst_
= const_decl
;
8242 return this->bconst_
;
8248 Type_declaration::add_method(const std::string
& name
, Function
* function
)
8250 Named_object
* ret
= Named_object::make_function(name
, NULL
, function
);
8251 this->methods_
.push_back(ret
);
8255 // Add a method declaration.
8258 Type_declaration::add_method_declaration(const std::string
& name
,
8260 Function_type
* type
,
8263 Named_object
* ret
= Named_object::make_function_declaration(name
, package
,
8265 this->methods_
.push_back(ret
);
8269 // Return whether any methods are defined.
8272 Type_declaration::has_methods() const
8274 return !this->methods_
.empty();
8277 // Define methods for the real type.
8280 Type_declaration::define_methods(Named_type
* nt
)
8282 if (this->methods_
.empty())
8285 while (nt
->is_alias())
8287 Type
*t
= nt
->real_type()->forwarded();
8288 if (t
->named_type() != NULL
)
8289 nt
= t
->named_type();
8290 else if (t
->forward_declaration_type() != NULL
)
8292 Named_object
* no
= t
->forward_declaration_type()->named_object();
8293 Type_declaration
* td
= no
->type_declaration_value();
8294 td
->methods_
.insert(td
->methods_
.end(), this->methods_
.begin(),
8295 this->methods_
.end());
8296 this->methods_
.clear();
8301 for (std::vector
<Named_object
*>::const_iterator p
=
8302 this->methods_
.begin();
8303 p
!= this->methods_
.end();
8305 go_error_at((*p
)->location(),
8306 ("invalid receiver type "
8307 "(receiver must be a named type)"));
8312 for (std::vector
<Named_object
*>::const_iterator p
= this->methods_
.begin();
8313 p
!= this->methods_
.end();
8316 if ((*p
)->is_function_declaration()
8317 || !(*p
)->func_value()->is_sink())
8318 nt
->add_existing_method(*p
);
8322 // We are using the type. Return true if we should issue a warning.
8325 Type_declaration::using_type()
8327 bool ret
= !this->issued_warning_
;
8328 this->issued_warning_
= true;
8332 // Class Unknown_name.
8334 // Set the real named object.
8337 Unknown_name::set_real_named_object(Named_object
* no
)
8339 go_assert(this->real_named_object_
== NULL
);
8340 go_assert(!no
->is_unknown());
8341 this->real_named_object_
= no
;
8344 // Class Named_object.
8346 Named_object::Named_object(const std::string
& name
,
8347 const Package
* package
,
8348 Classification classification
)
8349 : name_(name
), package_(package
), classification_(classification
),
8350 is_redefinition_(false)
8352 if (Gogo::is_sink_name(name
))
8353 go_assert(classification
== NAMED_OBJECT_SINK
);
8356 // Make an unknown name. This is used by the parser. The name must
8357 // be resolved later. Unknown names are only added in the current
8361 Named_object::make_unknown_name(const std::string
& name
,
8364 Named_object
* named_object
= new Named_object(name
, NULL
,
8365 NAMED_OBJECT_UNKNOWN
);
8366 Unknown_name
* value
= new Unknown_name(location
);
8367 named_object
->u_
.unknown_value
= value
;
8368 return named_object
;
8374 Named_object::make_constant(const Typed_identifier
& tid
,
8375 const Package
* package
, Expression
* expr
,
8378 Named_object
* named_object
= new Named_object(tid
.name(), package
,
8379 NAMED_OBJECT_CONST
);
8380 Named_constant
* named_constant
= new Named_constant(tid
.type(), expr
,
8383 named_object
->u_
.const_value
= named_constant
;
8384 return named_object
;
8387 // Make a named type.
8390 Named_object::make_type(const std::string
& name
, const Package
* package
,
8391 Type
* type
, Location location
)
8393 Named_object
* named_object
= new Named_object(name
, package
,
8395 Named_type
* named_type
= Type::make_named_type(named_object
, type
, location
);
8396 named_object
->u_
.type_value
= named_type
;
8397 return named_object
;
8400 // Make a type declaration.
8403 Named_object::make_type_declaration(const std::string
& name
,
8404 const Package
* package
,
8407 Named_object
* named_object
= new Named_object(name
, package
,
8408 NAMED_OBJECT_TYPE_DECLARATION
);
8409 Type_declaration
* type_declaration
= new Type_declaration(location
);
8410 named_object
->u_
.type_declaration
= type_declaration
;
8411 return named_object
;
8417 Named_object::make_variable(const std::string
& name
, const Package
* package
,
8420 Named_object
* named_object
= new Named_object(name
, package
,
8422 named_object
->u_
.var_value
= variable
;
8423 return named_object
;
8426 // Make a result variable.
8429 Named_object::make_result_variable(const std::string
& name
,
8430 Result_variable
* result
)
8432 Named_object
* named_object
= new Named_object(name
, NULL
,
8433 NAMED_OBJECT_RESULT_VAR
);
8434 named_object
->u_
.result_var_value
= result
;
8435 return named_object
;
8438 // Make a sink. This is used for the special blank identifier _.
8441 Named_object::make_sink()
8443 return new Named_object("_", NULL
, NAMED_OBJECT_SINK
);
8446 // Make a named function.
8449 Named_object::make_function(const std::string
& name
, const Package
* package
,
8452 Named_object
* named_object
= new Named_object(name
, package
,
8454 named_object
->u_
.func_value
= function
;
8455 return named_object
;
8458 // Make a function declaration.
8461 Named_object::make_function_declaration(const std::string
& name
,
8462 const Package
* package
,
8463 Function_type
* fntype
,
8466 Named_object
* named_object
= new Named_object(name
, package
,
8467 NAMED_OBJECT_FUNC_DECLARATION
);
8468 Function_declaration
*func_decl
= new Function_declaration(fntype
, location
);
8469 named_object
->u_
.func_declaration_value
= func_decl
;
8470 return named_object
;
8476 Named_object::make_package(const std::string
& alias
, Package
* package
)
8478 Named_object
* named_object
= new Named_object(alias
, NULL
,
8479 NAMED_OBJECT_PACKAGE
);
8480 named_object
->u_
.package_value
= package
;
8481 return named_object
;
8484 // Return the name to use in an error message.
8487 Named_object::message_name() const
8489 if (this->package_
== NULL
)
8490 return Gogo::message_name(this->name_
);
8492 if (this->package_
->has_package_name())
8493 ret
= this->package_
->package_name();
8495 ret
= this->package_
->pkgpath();
8496 ret
= Gogo::message_name(ret
);
8498 ret
+= Gogo::message_name(this->name_
);
8502 // Set the type when a declaration is defined.
8505 Named_object::set_type_value(Named_type
* named_type
)
8507 go_assert(this->classification_
== NAMED_OBJECT_TYPE_DECLARATION
);
8508 Type_declaration
* td
= this->u_
.type_declaration
;
8509 td
->define_methods(named_type
);
8511 Named_object
* in_function
= td
->in_function(&index
);
8512 if (in_function
!= NULL
)
8513 named_type
->set_in_function(in_function
, index
);
8515 this->classification_
= NAMED_OBJECT_TYPE
;
8516 this->u_
.type_value
= named_type
;
8519 // Define a function which was previously declared.
8522 Named_object::set_function_value(Function
* function
)
8524 go_assert(this->classification_
== NAMED_OBJECT_FUNC_DECLARATION
);
8525 if (this->func_declaration_value()->has_descriptor())
8527 Expression
* descriptor
=
8528 this->func_declaration_value()->descriptor(NULL
, NULL
);
8529 function
->set_descriptor(descriptor
);
8531 this->classification_
= NAMED_OBJECT_FUNC
;
8532 // FIXME: We should free the old value.
8533 this->u_
.func_value
= function
;
8536 // Declare an unknown object as a type declaration.
8539 Named_object::declare_as_type()
8541 go_assert(this->classification_
== NAMED_OBJECT_UNKNOWN
);
8542 Unknown_name
* unk
= this->u_
.unknown_value
;
8543 this->classification_
= NAMED_OBJECT_TYPE_DECLARATION
;
8544 this->u_
.type_declaration
= new Type_declaration(unk
->location());
8548 // Return the location of a named object.
8551 Named_object::location() const
8553 switch (this->classification_
)
8556 case NAMED_OBJECT_UNINITIALIZED
:
8559 case NAMED_OBJECT_ERRONEOUS
:
8560 return Linemap::unknown_location();
8562 case NAMED_OBJECT_UNKNOWN
:
8563 return this->unknown_value()->location();
8565 case NAMED_OBJECT_CONST
:
8566 return this->const_value()->location();
8568 case NAMED_OBJECT_TYPE
:
8569 return this->type_value()->location();
8571 case NAMED_OBJECT_TYPE_DECLARATION
:
8572 return this->type_declaration_value()->location();
8574 case NAMED_OBJECT_VAR
:
8575 return this->var_value()->location();
8577 case NAMED_OBJECT_RESULT_VAR
:
8578 return this->result_var_value()->location();
8580 case NAMED_OBJECT_SINK
:
8583 case NAMED_OBJECT_FUNC
:
8584 return this->func_value()->location();
8586 case NAMED_OBJECT_FUNC_DECLARATION
:
8587 return this->func_declaration_value()->location();
8589 case NAMED_OBJECT_PACKAGE
:
8590 return this->package_value()->location();
8594 // Traverse a Named_object.
8597 Named_object::traverse(Traverse
* traverse
, bool is_global
)
8599 const unsigned int traverse_mask
= traverse
->traverse_mask();
8600 const unsigned int e_or_t
= (Traverse::traverse_expressions
8601 | Traverse::traverse_types
);
8602 const unsigned int e_or_t_or_s
= (e_or_t
8603 | Traverse::traverse_statements
);
8605 int t
= TRAVERSE_CONTINUE
;
8606 switch (this->classification_
)
8608 case Named_object::NAMED_OBJECT_CONST
:
8609 if ((traverse_mask
& Traverse::traverse_constants
) != 0)
8610 t
= traverse
->constant(this, is_global
);
8611 if (t
== TRAVERSE_CONTINUE
8612 && (traverse_mask
& e_or_t
) != 0)
8614 Type
* tc
= this->const_value()->type();
8617 if (Type::traverse(tc
, traverse
) == TRAVERSE_EXIT
)
8618 return TRAVERSE_EXIT
;
8620 t
= this->const_value()->traverse_expression(traverse
);
8624 case Named_object::NAMED_OBJECT_VAR
:
8625 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8626 if ((traverse_mask
& Traverse::traverse_variables
) != 0)
8627 t
= traverse
->variable(this);
8628 if (t
== TRAVERSE_CONTINUE
8629 && (traverse_mask
& e_or_t
) != 0)
8631 if (this->is_result_variable() || this->var_value()->has_type())
8633 Type
* tv
= (this->is_variable()
8634 ? this->var_value()->type()
8635 : this->result_var_value()->type());
8638 if (Type::traverse(tv
, traverse
) == TRAVERSE_EXIT
)
8639 return TRAVERSE_EXIT
;
8643 if (t
== TRAVERSE_CONTINUE
8644 && (traverse_mask
& e_or_t_or_s
) != 0
8645 && this->is_variable())
8646 t
= this->var_value()->traverse_expression(traverse
,
8650 case Named_object::NAMED_OBJECT_FUNC
:
8651 if ((traverse_mask
& Traverse::traverse_functions
) != 0)
8652 t
= traverse
->function(this);
8653 if (t
== TRAVERSE_CONTINUE
8655 & (Traverse::traverse_variables
8656 | Traverse::traverse_constants
8657 | Traverse::traverse_functions
8658 | Traverse::traverse_blocks
8659 | Traverse::traverse_statements
8660 | Traverse::traverse_expressions
8661 | Traverse::traverse_types
)) != 0)
8662 t
= this->func_value()->traverse(traverse
);
8665 case Named_object::NAMED_OBJECT_TYPE
:
8666 if ((traverse_mask
& e_or_t
) != 0)
8667 t
= Type::traverse(this->type_value(), traverse
);
8670 case Named_object::NAMED_OBJECT_PACKAGE
:
8671 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8672 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8673 case Named_object::NAMED_OBJECT_UNKNOWN
:
8674 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8677 case Named_object::NAMED_OBJECT_SINK
:
8687 // Export a named object.
8690 Named_object::export_named_object(Export
* exp
) const
8692 switch (this->classification_
)
8695 case NAMED_OBJECT_UNINITIALIZED
:
8696 case NAMED_OBJECT_UNKNOWN
:
8699 case NAMED_OBJECT_ERRONEOUS
:
8702 case NAMED_OBJECT_CONST
:
8703 this->const_value()->export_const(exp
, this->name_
);
8706 case NAMED_OBJECT_TYPE
:
8707 // Types are handled by export::write_types.
8710 case NAMED_OBJECT_TYPE_DECLARATION
:
8711 go_error_at(this->type_declaration_value()->location(),
8712 "attempt to export %<%s%> which was declared but not defined",
8713 this->message_name().c_str());
8716 case NAMED_OBJECT_FUNC_DECLARATION
:
8717 this->func_declaration_value()->export_func(exp
, this);
8720 case NAMED_OBJECT_VAR
:
8721 this->var_value()->export_var(exp
, this);
8724 case NAMED_OBJECT_RESULT_VAR
:
8725 case NAMED_OBJECT_SINK
:
8728 case NAMED_OBJECT_FUNC
:
8729 this->func_value()->export_func(exp
, this);
8734 // Convert a variable to the backend representation.
8737 Named_object::get_backend_variable(Gogo
* gogo
, Named_object
* function
)
8739 if (this->classification_
== NAMED_OBJECT_VAR
)
8740 return this->var_value()->get_backend_variable(gogo
, function
,
8741 this->package_
, this->name_
);
8742 else if (this->classification_
== NAMED_OBJECT_RESULT_VAR
)
8743 return this->result_var_value()->get_backend_variable(gogo
, function
,
8750 debug_go_named_object(Named_object
* no
)
8754 std::cerr
<< "<null>";
8757 std::cerr
<< "'" << no
->name() << "': ";
8759 switch (no
->classification())
8761 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
8762 tag
= "uninitialized";
8764 case Named_object::NAMED_OBJECT_ERRONEOUS
:
8767 case Named_object::NAMED_OBJECT_UNKNOWN
:
8770 case Named_object::NAMED_OBJECT_CONST
:
8773 case Named_object::NAMED_OBJECT_TYPE
:
8776 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
8779 case Named_object::NAMED_OBJECT_VAR
:
8782 case Named_object::NAMED_OBJECT_RESULT_VAR
:
8785 case Named_object::NAMED_OBJECT_SINK
:
8788 case Named_object::NAMED_OBJECT_FUNC
:
8791 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
8794 case Named_object::NAMED_OBJECT_PACKAGE
:
8798 tag
= "<unknown named object classification>";
8801 std::cerr
<< tag
<< "\n";
8804 // Get the backend representation for this named object.
8807 Named_object::get_backend(Gogo
* gogo
, std::vector
<Bexpression
*>& const_decls
,
8808 std::vector
<Btype
*>& type_decls
,
8809 std::vector
<Bfunction
*>& func_decls
)
8811 // If this is a definition, avoid trying to get the backend
8812 // representation, as that can crash.
8813 if (this->is_redefinition_
)
8815 go_assert(saw_errors());
8819 switch (this->classification_
)
8821 case NAMED_OBJECT_CONST
:
8822 if (!Gogo::is_erroneous_name(this->name_
))
8823 const_decls
.push_back(this->u_
.const_value
->get_backend(gogo
, this));
8826 case NAMED_OBJECT_TYPE
:
8828 Named_type
* named_type
= this->u_
.type_value
;
8830 // No need to do anything for aliases-- whatever has to be done
8831 // can be done for the alias target.
8832 if (named_type
->is_alias())
8835 if (!Gogo::is_erroneous_name(this->name_
))
8836 type_decls
.push_back(named_type
->get_backend(gogo
));
8838 // We need to produce a type descriptor for every named
8839 // type, and for a pointer to every named type, since
8840 // other files or packages might refer to them. We need
8841 // to do this even for hidden types, because they might
8842 // still be returned by some function. Simply calling the
8843 // type_descriptor method is enough to create the type
8844 // descriptor, even though we don't do anything with it.
8845 if (this->package_
== NULL
&& !saw_errors())
8848 type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8849 Type
* pn
= Type::make_pointer_type(named_type
);
8850 pn
->type_descriptor_pointer(gogo
, Linemap::predeclared_location());
8851 if (named_type
->in_heap())
8853 named_type
->gc_symbol_pointer(gogo
);
8854 pn
->gc_symbol_pointer(gogo
);
8860 case NAMED_OBJECT_TYPE_DECLARATION
:
8861 go_error_at(Linemap::unknown_location(),
8862 "reference to undefined type %qs",
8863 this->message_name().c_str());
8866 case NAMED_OBJECT_VAR
:
8867 case NAMED_OBJECT_RESULT_VAR
:
8868 case NAMED_OBJECT_SINK
:
8871 case NAMED_OBJECT_FUNC
:
8873 Function
* func
= this->u_
.func_value
;
8874 if (!Gogo::is_erroneous_name(this->name_
))
8875 func_decls
.push_back(func
->get_or_make_decl(gogo
, this));
8877 if (func
->block() != NULL
)
8878 func
->build(gogo
, this);
8882 case NAMED_OBJECT_ERRONEOUS
:
8892 Bindings::Bindings(Bindings
* enclosing
)
8893 : enclosing_(enclosing
), named_objects_(), bindings_()
8900 Bindings::clear_file_scope(Gogo
* gogo
)
8902 Contour::iterator p
= this->bindings_
.begin();
8903 while (p
!= this->bindings_
.end())
8906 if (p
->second
->package() != NULL
)
8908 else if (p
->second
->is_package())
8910 else if (p
->second
->is_function()
8911 && !p
->second
->func_value()->type()->is_method()
8912 && Gogo::unpack_hidden_name(p
->second
->name()) == "init")
8921 gogo
->add_file_block_name(p
->second
->name(), p
->second
->location());
8922 p
= this->bindings_
.erase(p
);
8927 // Look up a symbol.
8930 Bindings::lookup(const std::string
& name
) const
8932 Contour::const_iterator p
= this->bindings_
.find(name
);
8933 if (p
!= this->bindings_
.end())
8934 return p
->second
->resolve();
8935 else if (this->enclosing_
!= NULL
)
8936 return this->enclosing_
->lookup(name
);
8941 // Look up a symbol locally.
8944 Bindings::lookup_local(const std::string
& name
) const
8946 Contour::const_iterator p
= this->bindings_
.find(name
);
8947 if (p
== this->bindings_
.end())
8952 // Remove an object from a set of bindings. This is used for a
8953 // special case in thunks for functions which call recover.
8956 Bindings::remove_binding(Named_object
* no
)
8958 Contour::iterator pb
= this->bindings_
.find(no
->name());
8959 go_assert(pb
!= this->bindings_
.end());
8960 this->bindings_
.erase(pb
);
8961 for (std::vector
<Named_object
*>::iterator pn
= this->named_objects_
.begin();
8962 pn
!= this->named_objects_
.end();
8967 this->named_objects_
.erase(pn
);
8974 // Add a method to the list of objects. This is not added to the
8975 // lookup table. This is so that we have a single list of objects
8976 // declared at the top level, which we walk through when it's time to
8977 // convert to trees.
8980 Bindings::add_method(Named_object
* method
)
8982 this->named_objects_
.push_back(method
);
8985 // Add a generic Named_object to a Contour.
8988 Bindings::add_named_object_to_contour(Contour
* contour
,
8989 Named_object
* named_object
)
8991 go_assert(named_object
== named_object
->resolve());
8992 const std::string
& name(named_object
->name());
8993 go_assert(!Gogo::is_sink_name(name
));
8995 std::pair
<Contour::iterator
, bool> ins
=
8996 contour
->insert(std::make_pair(name
, named_object
));
8999 // The name was already there.
9000 if (named_object
->package() != NULL
9001 && ins
.first
->second
->package() == named_object
->package()
9002 && (ins
.first
->second
->classification()
9003 == named_object
->classification()))
9005 // This is a second import of the same object.
9006 return ins
.first
->second
;
9008 ins
.first
->second
= this->new_definition(ins
.first
->second
,
9010 return ins
.first
->second
;
9014 // Don't push declarations on the list. We push them on when
9015 // and if we find the definitions. That way we genericize the
9016 // functions in order.
9017 if (!named_object
->is_type_declaration()
9018 && !named_object
->is_function_declaration()
9019 && !named_object
->is_unknown())
9020 this->named_objects_
.push_back(named_object
);
9021 return named_object
;
9025 // We had an existing named object OLD_OBJECT, and we've seen a new
9026 // one NEW_OBJECT with the same name. FIXME: This does not free the
9027 // new object when we don't need it.
9030 Bindings::new_definition(Named_object
* old_object
, Named_object
* new_object
)
9032 if (new_object
->is_erroneous() && !old_object
->is_erroneous())
9036 switch (old_object
->classification())
9039 case Named_object::NAMED_OBJECT_UNINITIALIZED
:
9042 case Named_object::NAMED_OBJECT_ERRONEOUS
:
9045 case Named_object::NAMED_OBJECT_UNKNOWN
:
9047 Named_object
* real
= old_object
->unknown_value()->real_named_object();
9049 return this->new_definition(real
, new_object
);
9050 go_assert(!new_object
->is_unknown());
9051 old_object
->unknown_value()->set_real_named_object(new_object
);
9052 if (!new_object
->is_type_declaration()
9053 && !new_object
->is_function_declaration())
9054 this->named_objects_
.push_back(new_object
);
9058 case Named_object::NAMED_OBJECT_CONST
:
9061 case Named_object::NAMED_OBJECT_TYPE
:
9062 if (new_object
->is_type_declaration())
9066 case Named_object::NAMED_OBJECT_TYPE_DECLARATION
:
9067 if (new_object
->is_type_declaration())
9069 if (new_object
->is_type())
9071 old_object
->set_type_value(new_object
->type_value());
9072 new_object
->type_value()->set_named_object(old_object
);
9073 this->named_objects_
.push_back(old_object
);
9078 case Named_object::NAMED_OBJECT_VAR
:
9079 case Named_object::NAMED_OBJECT_RESULT_VAR
:
9080 // We have already given an error in the parser for cases where
9081 // one parameter or result variable redeclares another one.
9082 if ((new_object
->is_variable()
9083 && new_object
->var_value()->is_parameter())
9084 || new_object
->is_result_variable())
9088 case Named_object::NAMED_OBJECT_SINK
:
9091 case Named_object::NAMED_OBJECT_FUNC
:
9094 case Named_object::NAMED_OBJECT_FUNC_DECLARATION
:
9096 // We declare the hash and equality functions before defining
9097 // them, because we sometimes see that we need the declaration
9098 // while we are in the middle of a different function.
9100 // We declare the main function before the user defines it, to
9101 // give better error messages.
9103 // We declare inline functions before we define them, as we
9104 // only define them if we need them.
9105 if (new_object
->is_function()
9106 && ((Linemap::is_predeclared_location(old_object
->location())
9107 && Linemap::is_predeclared_location(new_object
->location()))
9108 || (Gogo::unpack_hidden_name(old_object
->name()) == "main"
9109 && Linemap::is_unknown_location(old_object
->location()))
9110 || (new_object
->package() != NULL
9111 && old_object
->func_declaration_value()->has_imported_body()
9112 && new_object
->func_value()->is_inline_only())))
9114 Function_type
* old_type
=
9115 old_object
->func_declaration_value()->type();
9116 Function_type
* new_type
= new_object
->func_value()->type();
9117 if (old_type
->is_valid_redeclaration(new_type
, &reason
))
9119 Function_declaration
* fd
=
9120 old_object
->func_declaration_value();
9121 go_assert(fd
->asm_name().empty());
9122 old_object
->set_function_value(new_object
->func_value());
9123 this->named_objects_
.push_back(old_object
);
9130 case Named_object::NAMED_OBJECT_PACKAGE
:
9134 std::string n
= old_object
->message_name();
9136 go_error_at(new_object
->location(), "redefinition of %qs", n
.c_str());
9138 go_error_at(new_object
->location(), "redefinition of %qs: %s", n
.c_str(),
9140 old_object
->set_is_redefinition();
9141 new_object
->set_is_redefinition();
9143 if (!Linemap::is_unknown_location(old_object
->location())
9144 && !Linemap::is_predeclared_location(old_object
->location()))
9145 go_inform(old_object
->location(), "previous definition of %qs was here",
9151 // Add a named type.
9154 Bindings::add_named_type(Named_type
* named_type
)
9156 return this->add_named_object(named_type
->named_object());
9162 Bindings::add_function(const std::string
& name
, const Package
* package
,
9165 return this->add_named_object(Named_object::make_function(name
, package
,
9169 // Add a function declaration.
9172 Bindings::add_function_declaration(const std::string
& name
,
9173 const Package
* package
,
9174 Function_type
* type
,
9177 Named_object
* no
= Named_object::make_function_declaration(name
, package
,
9179 return this->add_named_object(no
);
9182 // Define a type which was previously declared.
9185 Bindings::define_type(Named_object
* no
, Named_type
* type
)
9187 no
->set_type_value(type
);
9188 this->named_objects_
.push_back(no
);
9191 // Mark all local variables as used. This is used for some types of
9195 Bindings::mark_locals_used()
9197 for (std::vector
<Named_object
*>::iterator p
= this->named_objects_
.begin();
9198 p
!= this->named_objects_
.end();
9200 if ((*p
)->is_variable())
9201 (*p
)->var_value()->set_is_used();
9204 // Traverse bindings.
9207 Bindings::traverse(Traverse
* traverse
, bool is_global
)
9209 unsigned int traverse_mask
= traverse
->traverse_mask();
9211 // We don't use an iterator because we permit the traversal to add
9212 // new global objects.
9213 const unsigned int e_or_t
= (Traverse::traverse_expressions
9214 | Traverse::traverse_types
);
9215 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9217 Named_object
* p
= this->named_objects_
[i
];
9218 if (p
->traverse(traverse
, is_global
) == TRAVERSE_EXIT
)
9219 return TRAVERSE_EXIT
;
9222 // If we need to traverse types, check the function declarations,
9223 // which have types. Also check any methods of a type declaration.
9224 if ((traverse_mask
& e_or_t
) != 0)
9226 for (Bindings::const_declarations_iterator p
=
9227 this->begin_declarations();
9228 p
!= this->end_declarations();
9231 if (p
->second
->is_function_declaration())
9233 if (Type::traverse(p
->second
->func_declaration_value()->type(),
9236 return TRAVERSE_EXIT
;
9238 else if (p
->second
->is_type_declaration())
9240 const std::vector
<Named_object
*>* methods
=
9241 p
->second
->type_declaration_value()->methods();
9242 for (std::vector
<Named_object
*>::const_iterator pm
=
9244 pm
!= methods
->end();
9247 Named_object
* no
= *pm
;
9249 if (no
->is_function())
9250 t
= no
->func_value()->type();
9251 else if (no
->is_function_declaration())
9252 t
= no
->func_declaration_value()->type();
9255 if (Type::traverse(t
, traverse
) == TRAVERSE_EXIT
)
9256 return TRAVERSE_EXIT
;
9262 // Traverse function declarations when needed.
9263 if ((traverse_mask
& Traverse::traverse_func_declarations
) != 0)
9265 for (Bindings::const_declarations_iterator p
= this->begin_declarations();
9266 p
!= this->end_declarations();
9269 if (p
->second
->is_function_declaration())
9271 if (traverse
->function_declaration(p
->second
) == TRAVERSE_EXIT
)
9272 return TRAVERSE_EXIT
;
9277 return TRAVERSE_CONTINUE
;
9281 Bindings::debug_dump()
9283 std::set
<Named_object
*> defs
;
9284 for (size_t i
= 0; i
< this->named_objects_
.size(); ++i
)
9285 defs
.insert(this->named_objects_
[i
]);
9286 for (Contour::iterator p
= this->bindings_
.begin();
9287 p
!= this->bindings_
.end();
9290 const char* tag
= " ";
9291 if (defs
.find(p
->second
) != defs
.end())
9294 debug_go_named_object(p
->second
);
9299 debug_go_bindings(Bindings
* bindings
)
9301 if (bindings
!= NULL
)
9302 bindings
->debug_dump();
9307 // Clear any references to this label.
9312 for (std::vector
<Bindings_snapshot
*>::iterator p
= this->refs_
.begin();
9313 p
!= this->refs_
.end();
9316 this->refs_
.clear();
9319 // Get the backend representation for a label.
9322 Label::get_backend_label(Translate_context
* context
)
9324 if (this->blabel_
== NULL
)
9326 Function
* function
= context
->function()->func_value();
9327 Bfunction
* bfunction
= function
->get_decl();
9328 this->blabel_
= context
->backend()->label(bfunction
, this->name_
,
9331 return this->blabel_
;
9334 // Return an expression for the address of this label.
9337 Label::get_addr(Translate_context
* context
, Location location
)
9339 Blabel
* label
= this->get_backend_label(context
);
9340 return context
->backend()->label_address(label
, location
);
9343 // Return the dummy label that represents any instance of the blank label.
9346 Label::create_dummy_label()
9348 static Label
* dummy_label
;
9349 if (dummy_label
== NULL
)
9351 dummy_label
= new Label("_");
9352 dummy_label
->set_is_used();
9357 // Class Unnamed_label.
9359 // Get the backend representation for an unnamed label.
9362 Unnamed_label::get_blabel(Translate_context
* context
)
9364 if (this->blabel_
== NULL
)
9366 Function
* function
= context
->function()->func_value();
9367 Bfunction
* bfunction
= function
->get_decl();
9368 this->blabel_
= context
->backend()->label(bfunction
, "",
9371 return this->blabel_
;
9374 // Return a statement which defines this unnamed label.
9377 Unnamed_label::get_definition(Translate_context
* context
)
9379 Blabel
* blabel
= this->get_blabel(context
);
9380 return context
->backend()->label_definition_statement(blabel
);
9383 // Return a goto statement to this unnamed label.
9386 Unnamed_label::get_goto(Translate_context
* context
, Location location
)
9388 Blabel
* blabel
= this->get_blabel(context
);
9389 return context
->backend()->goto_statement(blabel
, location
);
9394 Package::Package(const std::string
& pkgpath
,
9395 const std::string
& pkgpath_symbol
, Location location
)
9396 : pkgpath_(pkgpath
), pkgpath_symbol_(pkgpath_symbol
),
9397 package_name_(), bindings_(new Bindings(NULL
)),
9400 go_assert(!pkgpath
.empty());
9403 // Set the package name.
9406 Package::set_package_name(const std::string
& package_name
, Location location
)
9408 go_assert(!package_name
.empty());
9409 if (this->package_name_
.empty())
9410 this->package_name_
= package_name
;
9411 else if (this->package_name_
!= package_name
)
9412 go_error_at(location
,
9413 ("saw two different packages with "
9414 "the same package path %s: %s, %s"),
9415 this->pkgpath_
.c_str(), this->package_name_
.c_str(),
9416 package_name
.c_str());
9419 // Return the pkgpath symbol, which is a prefix for symbols defined in
9423 Package::pkgpath_symbol() const
9425 if (this->pkgpath_symbol_
.empty())
9426 return Gogo::pkgpath_for_symbol(this->pkgpath_
);
9427 return this->pkgpath_symbol_
;
9430 // Set the package path symbol.
9433 Package::set_pkgpath_symbol(const std::string
& pkgpath_symbol
)
9435 go_assert(!pkgpath_symbol
.empty());
9436 if (this->pkgpath_symbol_
.empty())
9437 this->pkgpath_symbol_
= pkgpath_symbol
;
9439 go_assert(this->pkgpath_symbol_
== pkgpath_symbol
);
9442 // Note that symbol from this package was and qualified by ALIAS.
9445 Package::note_usage(const std::string
& alias
) const
9447 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9448 go_assert(p
!= this->aliases_
.end());
9449 p
->second
->note_usage();
9452 // Forget a given usage. If forgetting this usage means this package becomes
9453 // unused, report that error.
9456 Package::forget_usage(Expression
* usage
) const
9458 if (this->fake_uses_
.empty())
9461 std::set
<Expression
*>::iterator p
= this->fake_uses_
.find(usage
);
9462 go_assert(p
!= this->fake_uses_
.end());
9463 this->fake_uses_
.erase(p
);
9465 if (this->fake_uses_
.empty())
9466 go_error_at(this->location(), "imported and not used: %s",
9467 Gogo::message_name(this->package_name()).c_str());
9470 // Clear the used field for the next file. If the only usages of this package
9471 // are possibly fake, keep the fake usages for lowering.
9474 Package::clear_used()
9476 std::string dot_alias
= "." + this->package_name();
9477 Aliases::const_iterator p
= this->aliases_
.find(dot_alias
);
9478 if (p
!= this->aliases_
.end() && p
->second
->used() > this->fake_uses_
.size())
9479 this->fake_uses_
.clear();
9481 this->aliases_
.clear();
9485 Package::add_alias(const std::string
& alias
, Location location
)
9487 Aliases::const_iterator p
= this->aliases_
.find(alias
);
9488 if (p
== this->aliases_
.end())
9490 std::pair
<Aliases::iterator
, bool> ret
;
9491 ret
= this->aliases_
.insert(std::make_pair(alias
,
9492 new Package_alias(location
)));
9498 // Determine types of constants. Everything else in a package
9499 // (variables, function declarations) should already have a fixed
9500 // type. Constants may have abstract types.
9503 Package::determine_types()
9505 Bindings
* bindings
= this->bindings_
;
9506 for (Bindings::const_definitions_iterator p
= bindings
->begin_definitions();
9507 p
!= bindings
->end_definitions();
9510 if ((*p
)->is_const())
9511 (*p
)->const_value()->determine_type();
9519 Traverse::~Traverse()
9521 if (this->types_seen_
!= NULL
)
9522 delete this->types_seen_
;
9523 if (this->expressions_seen_
!= NULL
)
9524 delete this->expressions_seen_
;
9527 // Record that we are looking at a type, and return true if we have
9531 Traverse::remember_type(const Type
* type
)
9533 if (type
->is_error_type())
9535 go_assert((this->traverse_mask() & traverse_types
) != 0
9536 || (this->traverse_mask() & traverse_expressions
) != 0);
9537 // We mostly only have to remember named types. But it turns out
9538 // that an interface type can refer to itself without using a name
9539 // by relying on interface inheritance, as in
9541 // type I interface { F() interface{I} }
9543 // Similarly it is possible for array types to refer to themselves
9544 // without a name, e.g.
9546 // var x [uintptr(unsafe.Sizeof(&x))]byte
9548 if (type
->classification() != Type::TYPE_NAMED
9549 && type
->classification() != Type::TYPE_ARRAY
9550 && type
->classification() != Type::TYPE_INTERFACE
)
9552 if (this->types_seen_
== NULL
)
9553 this->types_seen_
= new Types_seen();
9554 std::pair
<Types_seen::iterator
, bool> ins
= this->types_seen_
->insert(type
);
9558 // Record that we are looking at an expression, and return true if we
9559 // have already seen it. NB: this routine used to assert if the traverse
9560 // mask did not include expressions/types -- this is no longer the case,
9561 // since it can be useful to remember specific expressions during
9562 // walks that only cover statements.
9565 Traverse::remember_expression(const Expression
* expression
)
9567 if (this->expressions_seen_
== NULL
)
9568 this->expressions_seen_
= new Expressions_seen();
9569 std::pair
<Expressions_seen::iterator
, bool> ins
=
9570 this->expressions_seen_
->insert(expression
);
9574 // The default versions of these functions should never be called: the
9575 // traversal mask indicates which functions may be called.
9578 Traverse::variable(Named_object
*)
9584 Traverse::constant(Named_object
*, bool)
9590 Traverse::function(Named_object
*)
9596 Traverse::block(Block
*)
9602 Traverse::statement(Block
*, size_t*, Statement
*)
9608 Traverse::expression(Expression
**)
9614 Traverse::type(Type
*)
9620 Traverse::function_declaration(Named_object
*)
9625 // Class Statement_inserter.
9628 Statement_inserter::insert(Statement
* s
)
9630 if (this->statements_added_
!= NULL
)
9631 this->statements_added_
->insert(s
);
9633 if (this->block_
!= NULL
)
9635 go_assert(this->pindex_
!= NULL
);
9636 this->block_
->insert_statement_before(*this->pindex_
, s
);
9639 else if (this->var_
!= NULL
)
9640 this->var_
->add_preinit_statement(this->gogo_
, s
);
9642 go_assert(saw_errors());