1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
11 #include "filenames.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
17 #include "go-optimize.h"
20 #include "statements.h"
21 #include "expressions.h"
30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
35 globals_(new Bindings(NULL)),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
60 specific_type_functions_(),
61 specific_type_functions_are_written_(false),
62 named_types_are_converted_(false),
66 const Location loc = Linemap::predeclared_location();
68 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
69 RUNTIME_TYPE_KIND_UINT8);
70 this->add_named_type(uint8_type);
71 this->add_named_type(Type::make_integer_type("uint16", true, 16,
72 RUNTIME_TYPE_KIND_UINT16));
73 this->add_named_type(Type::make_integer_type("uint32", true, 32,
74 RUNTIME_TYPE_KIND_UINT32));
75 this->add_named_type(Type::make_integer_type("uint64", true, 64,
76 RUNTIME_TYPE_KIND_UINT64));
78 this->add_named_type(Type::make_integer_type("int8", false, 8,
79 RUNTIME_TYPE_KIND_INT8));
80 this->add_named_type(Type::make_integer_type("int16", false, 16,
81 RUNTIME_TYPE_KIND_INT16));
82 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
83 RUNTIME_TYPE_KIND_INT32);
84 this->add_named_type(int32_type);
85 this->add_named_type(Type::make_integer_type("int64", false, 64,
86 RUNTIME_TYPE_KIND_INT64));
88 this->add_named_type(Type::make_float_type("float32", 32,
89 RUNTIME_TYPE_KIND_FLOAT32));
90 this->add_named_type(Type::make_float_type("float64", 64,
91 RUNTIME_TYPE_KIND_FLOAT64));
93 this->add_named_type(Type::make_complex_type("complex64", 64,
94 RUNTIME_TYPE_KIND_COMPLEX64));
95 this->add_named_type(Type::make_complex_type("complex128", 128,
96 RUNTIME_TYPE_KIND_COMPLEX128));
98 int int_type_size = pointer_size;
99 if (int_type_size < 32)
101 this->add_named_type(Type::make_integer_type("uint", true,
103 RUNTIME_TYPE_KIND_UINT));
104 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
105 RUNTIME_TYPE_KIND_INT);
106 this->add_named_type(int_type);
108 this->add_named_type(Type::make_integer_type("uintptr", true,
110 RUNTIME_TYPE_KIND_UINTPTR));
112 // "byte" is an alias for "uint8".
113 uint8_type->integer_type()->set_is_byte();
114 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
116 byte_type->type_value()->set_is_alias();
117 this->add_named_type(byte_type->type_value());
119 // "rune" is an alias for "int32".
120 int32_type->integer_type()->set_is_rune();
121 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
123 rune_type->type_value()->set_is_alias();
124 this->add_named_type(rune_type->type_value());
126 this->add_named_type(Type::make_named_bool_type());
128 this->add_named_type(Type::make_named_string_type());
130 // "error" is interface { Error() string }.
132 Typed_identifier_list *methods = new Typed_identifier_list;
133 Typed_identifier_list *results = new Typed_identifier_list;
134 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
135 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
136 methods->push_back(Typed_identifier("Error", method_type, loc));
137 Interface_type *error_iface = Type::make_interface_type(methods, loc);
138 error_iface->finalize_methods();
139 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
140 this->add_named_type(error_type);
143 this->globals_->add_constant(Typed_identifier("true",
144 Type::make_boolean_type(),
147 Expression::make_boolean(true, loc),
149 this->globals_->add_constant(Typed_identifier("false",
150 Type::make_boolean_type(),
153 Expression::make_boolean(false, loc),
156 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
159 Expression::make_nil(loc),
162 Type* abstract_int_type = Type::make_abstract_integer_type();
163 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
166 Expression::make_iota(),
169 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
170 new_type->set_is_varargs();
171 new_type->set_is_builtin();
172 this->globals_->add_function_declaration("new", NULL, new_type, loc);
174 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
175 make_type->set_is_varargs();
176 make_type->set_is_builtin();
177 this->globals_->add_function_declaration("make", NULL, make_type, loc);
179 Typed_identifier_list* len_result = new Typed_identifier_list();
180 len_result->push_back(Typed_identifier("", int_type, loc));
181 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
183 len_type->set_is_builtin();
184 this->globals_->add_function_declaration("len", NULL, len_type, loc);
186 Typed_identifier_list* cap_result = new Typed_identifier_list();
187 cap_result->push_back(Typed_identifier("", int_type, loc));
188 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
190 cap_type->set_is_builtin();
191 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
193 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
194 print_type->set_is_varargs();
195 print_type->set_is_builtin();
196 this->globals_->add_function_declaration("print", NULL, print_type, loc);
198 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
199 print_type->set_is_varargs();
200 print_type->set_is_builtin();
201 this->globals_->add_function_declaration("println", NULL, print_type, loc);
203 Type *empty = Type::make_empty_interface_type(loc);
204 Typed_identifier_list* panic_parms = new Typed_identifier_list();
205 panic_parms->push_back(Typed_identifier("e", empty, loc));
206 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
208 panic_type->set_is_builtin();
209 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
211 Typed_identifier_list* recover_result = new Typed_identifier_list();
212 recover_result->push_back(Typed_identifier("", empty, loc));
213 Function_type* recover_type = Type::make_function_type(NULL, NULL,
216 recover_type->set_is_builtin();
217 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
219 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
220 close_type->set_is_varargs();
221 close_type->set_is_builtin();
222 this->globals_->add_function_declaration("close", NULL, close_type, loc);
224 Typed_identifier_list* copy_result = new Typed_identifier_list();
225 copy_result->push_back(Typed_identifier("", int_type, loc));
226 Function_type* copy_type = Type::make_function_type(NULL, NULL,
228 copy_type->set_is_varargs();
229 copy_type->set_is_builtin();
230 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
232 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
233 append_type->set_is_varargs();
234 append_type->set_is_builtin();
235 this->globals_->add_function_declaration("append", NULL, append_type, loc);
237 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
238 complex_type->set_is_varargs();
239 complex_type->set_is_builtin();
240 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
242 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
243 real_type->set_is_varargs();
244 real_type->set_is_builtin();
245 this->globals_->add_function_declaration("real", NULL, real_type, loc);
247 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
248 imag_type->set_is_varargs();
249 imag_type->set_is_builtin();
250 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
252 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
253 delete_type->set_is_varargs();
254 delete_type->set_is_builtin();
255 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
258 // Convert a pkgpath into a string suitable for a symbol. Note that
259 // this transformation is convenient but imperfect. A -fgo-pkgpath
260 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
261 // possibly leading to link time errors.
264 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
266 std::string s = pkgpath;
267 for (size_t i = 0; i < s.length(); ++i)
270 if ((c >= 'a' && c <= 'z')
271 || (c >= 'A' && c <= 'Z')
272 || (c >= '0' && c <= '9'))
280 // Get the package path to use for type reflection data. This should
281 // ideally be unique across the entire link.
284 Gogo::pkgpath() const
286 go_assert(this->pkgpath_set_);
287 return this->pkgpath_;
290 // Set the package path from the -fgo-pkgpath command line option.
293 Gogo::set_pkgpath(const std::string& arg)
295 go_assert(!this->pkgpath_set_);
296 this->pkgpath_ = arg;
297 this->pkgpath_set_ = true;
298 this->pkgpath_from_option_ = true;
301 // Get the package path to use for symbol names.
304 Gogo::pkgpath_symbol() const
306 go_assert(this->pkgpath_set_);
307 return this->pkgpath_symbol_;
310 // Set the unique prefix to use to determine the package path, from
311 // the -fgo-prefix command line option.
314 Gogo::set_prefix(const std::string& arg)
316 go_assert(!this->prefix_from_option_);
318 this->prefix_from_option_ = true;
321 // Munge name for use in an error message.
324 Gogo::message_name(const std::string& name)
326 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
329 // Get the package name.
332 Gogo::package_name() const
334 go_assert(this->package_ != NULL);
335 return this->package_->package_name();
338 // Set the package name.
341 Gogo::set_package_name(const std::string& package_name,
344 if (this->package_ != NULL)
346 if (this->package_->package_name() != package_name)
347 go_error_at(location, "expected package %<%s%>",
348 Gogo::message_name(this->package_->package_name()).c_str());
352 // Now that we know the name of the package we are compiling, set
353 // the package path to use for reflect.Type.PkgPath and global
355 if (this->pkgpath_set_)
356 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
359 if (!this->prefix_from_option_ && package_name == "main")
361 this->pkgpath_ = package_name;
362 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
366 if (!this->prefix_from_option_)
367 this->prefix_ = "go";
368 this->pkgpath_ = this->prefix_ + '.' + package_name;
369 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
370 + Gogo::pkgpath_for_symbol(package_name));
372 this->pkgpath_set_ = true;
375 this->package_ = this->register_package(this->pkgpath_,
376 this->pkgpath_symbol_, location);
377 this->package_->set_package_name(package_name, location);
379 if (this->is_main_package())
381 // Declare "main" as a function which takes no parameters and
383 Location uloc = Linemap::unknown_location();
384 this->declare_function(Gogo::pack_hidden_name("main", false),
385 Type::make_function_type (NULL, NULL, NULL, uloc),
390 // Return whether this is the "main" package. This is not true if
391 // -fgo-pkgpath or -fgo-prefix was used.
394 Gogo::is_main_package() const
396 return (this->package_name() == "main"
397 && !this->pkgpath_from_option_
398 && !this->prefix_from_option_);
404 Gogo::import_package(const std::string& filename,
405 const std::string& local_name,
406 bool is_local_name_exported,
410 if (filename.empty())
412 go_error_at(location, "import path is empty");
416 const char *pf = filename.data();
417 const char *pend = pf + filename.length();
421 int adv = Lex::fetch_char(pf, &c);
424 go_error_at(location, "import path contains invalid UTF-8 sequence");
429 go_error_at(location, "import path contains NUL");
432 if (c < 0x20 || c == 0x7f)
434 go_error_at(location, "import path contains control character");
439 go_error_at(location, "import path contains backslash; use slash");
442 if (Lex::is_unicode_space(c))
444 go_error_at(location, "import path contains space character");
447 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
449 go_error_at(location,
450 "import path contains invalid character '%c'", c);
456 if (IS_ABSOLUTE_PATH(filename.c_str()))
458 go_error_at(location, "import path cannot be absolute path");
462 if (local_name == "init")
463 go_error_at(location, "cannot import package as init");
465 if (filename == "unsafe")
467 this->import_unsafe(local_name, is_local_name_exported, location);
468 this->current_file_imported_unsafe_ = true;
472 Imports::const_iterator p = this->imports_.find(filename);
473 if (p != this->imports_.end())
475 Package* package = p->second;
476 package->set_location(location);
477 std::string ln = local_name;
478 bool is_ln_exported = is_local_name_exported;
481 ln = package->package_name();
482 go_assert(!ln.empty());
483 is_ln_exported = Lex::is_exported_name(ln);
489 Bindings* bindings = package->bindings();
490 for (Bindings::const_declarations_iterator p =
491 bindings->begin_declarations();
492 p != bindings->end_declarations();
494 this->add_dot_import_object(p->second);
495 std::string dot_alias = "." + package->package_name();
496 package->add_alias(dot_alias, location);
500 package->add_alias(ln, location);
501 ln = this->pack_hidden_name(ln, is_ln_exported);
502 this->package_->bindings()->add_package(ln, package);
507 Import::Stream* stream = Import::open_package(filename, location,
508 this->relative_import_path_);
512 go_error_at(location, "import file %qs not found", filename.c_str());
516 Import imp(stream, location);
517 imp.register_builtin_types(this);
518 Package* package = imp.import(this, local_name, is_local_name_exported);
521 if (package->pkgpath() == this->pkgpath())
522 go_error_at(location,
523 ("imported package uses same package path as package "
524 "being compiled (see -fgo-pkgpath option)"));
526 this->imports_.insert(std::make_pair(filename, package));
533 Gogo::lookup_init(const std::string& init_name)
535 Import_init tmp("", init_name, -1);
536 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
537 return (it != this->imported_init_fns_.end()) ? *it : NULL;
540 // Add an import control function for an imported package to the list.
543 Gogo::add_import_init_fn(const std::string& package_name,
544 const std::string& init_name, int prio)
546 for (Import_init_set::iterator p =
547 this->imported_init_fns_.begin();
548 p != this->imported_init_fns_.end();
551 Import_init *ii = (*p);
552 if (ii->init_name() == init_name)
554 // If a test of package P1, built as part of package P1,
555 // imports package P2, and P2 imports P1 (perhaps
556 // indirectly), then we will see the same import name with
557 // different import priorities. That is OK, so don't give
558 // an error about it.
559 if (ii->package_name() != package_name)
561 go_error_at(Linemap::unknown_location(),
562 "duplicate package initialization name %qs",
563 Gogo::message_name(init_name).c_str());
564 go_inform(Linemap::unknown_location(), "used by package %qs",
565 Gogo::message_name(ii->package_name()).c_str());
566 go_inform(Linemap::unknown_location(), " and by package %qs",
567 Gogo::message_name(package_name).c_str());
569 ii->set_priority(prio);
574 Import_init* nii = new Import_init(package_name, init_name, prio);
575 this->imported_init_fns_.insert(nii);
578 // Return whether we are at the global binding level.
581 Gogo::in_global_scope() const
583 return this->functions_.empty();
586 // Return the current binding contour.
589 Gogo::current_bindings()
591 if (!this->functions_.empty())
592 return this->functions_.back().blocks.back()->bindings();
593 else if (this->package_ != NULL)
594 return this->package_->bindings();
596 return this->globals_;
600 Gogo::current_bindings() const
602 if (!this->functions_.empty())
603 return this->functions_.back().blocks.back()->bindings();
604 else if (this->package_ != NULL)
605 return this->package_->bindings();
607 return this->globals_;
611 Gogo::update_init_priority(Import_init* ii,
612 std::set<const Import_init *>* visited)
617 for (std::set<std::string>::const_iterator pci =
618 ii->precursors().begin();
619 pci != ii->precursors().end();
622 Import_init* succ = this->lookup_init(*pci);
623 if (visited->find(succ) == visited->end())
624 update_init_priority(succ, visited);
625 succ_prior = std::max(succ_prior, succ->priority());
627 if (ii->priority() <= succ_prior)
628 ii->set_priority(succ_prior + 1);
632 Gogo::recompute_init_priorities()
634 std::set<Import_init *> nonroots;
636 for (Import_init_set::const_iterator p =
637 this->imported_init_fns_.begin();
638 p != this->imported_init_fns_.end();
641 const Import_init *ii = *p;
642 for (std::set<std::string>::const_iterator pci =
643 ii->precursors().begin();
644 pci != ii->precursors().end();
647 Import_init* ii = this->lookup_init(*pci);
652 // Recursively update priorities starting at roots.
653 std::set<const Import_init*> visited;
654 for (Import_init_set::iterator p =
655 this->imported_init_fns_.begin();
656 p != this->imported_init_fns_.end();
659 Import_init* ii = *p;
660 if (nonroots.find(ii) != nonroots.end())
662 update_init_priority(ii, &visited);
666 // Add statements to INIT_STMTS which run the initialization
667 // functions for imported packages. This is only used for the "main"
671 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
673 go_assert(this->is_main_package());
675 if (this->imported_init_fns_.empty())
678 Location unknown_loc = Linemap::unknown_location();
679 Function_type* func_type =
680 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
681 Btype* fntype = func_type->get_backend_fntype(this);
683 // Recompute init priorities based on a walk of the init graph.
684 recompute_init_priorities();
686 // We must call them in increasing priority order.
687 std::vector<const Import_init*> v;
688 for (Import_init_set::const_iterator p =
689 this->imported_init_fns_.begin();
690 p != this->imported_init_fns_.end();
693 if ((*p)->priority() < 0)
694 go_error_at(Linemap::unknown_location(),
695 "internal error: failed to set init priority for %s",
696 (*p)->package_name().c_str());
699 std::sort(v.begin(), v.end(), priority_compare);
701 // We build calls to the init functions, which take no arguments.
702 std::vector<Bexpression*> empty_args;
703 for (std::vector<const Import_init*>::const_iterator p = v.begin();
707 const Import_init* ii = *p;
708 std::string user_name = ii->package_name() + ".init";
709 const std::string& init_name(ii->init_name());
711 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
712 true, true, true, false,
714 Bexpression* pfunc_code =
715 this->backend()->function_code_expression(pfunc, unknown_loc);
716 Bexpression* pfunc_call =
717 this->backend()->call_expression(bfunction, pfunc_code, empty_args,
719 init_stmts.push_back(this->backend()->expression_statement(bfunction,
724 // Register global variables with the garbage collector. We need to
725 // register all variables which can hold a pointer value. They become
726 // roots during the mark phase. We build a struct that is easy to
727 // hook into a list of roots.
729 // type gcRoot struct {
730 // decl unsafe.Pointer // Pointer to variable.
731 // size uintptr // Total size of variable.
732 // ptrdata uintptr // Length of variable's gcdata.
733 // gcdata *byte // Pointer mask.
736 // type gcRootList struct {
742 // The last entry in the roots array has a NULL decl field.
745 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
746 std::vector<Bstatement*>& init_stmts,
749 if (var_gc.empty() && this->gc_roots_.empty())
752 Type* pvt = Type::make_pointer_type(Type::make_void_type());
753 Type* uintptr_type = Type::lookup_integer_type("uintptr");
754 Type* byte_type = this->lookup_global("byte")->type_value();
755 Type* pointer_byte_type = Type::make_pointer_type(byte_type);
756 Struct_type* root_type =
757 Type::make_builtin_struct_type(4,
759 "size", uintptr_type,
760 "ptrdata", uintptr_type,
761 "gcdata", pointer_byte_type);
763 Location builtin_loc = Linemap::predeclared_location();
764 unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
765 Expression* length = Expression::make_integer_ul(roots_len, NULL,
767 Array_type* root_array_type = Type::make_array_type(root_type, length);
768 root_array_type->set_is_array_incomparable();
770 Type* int_type = Type::lookup_integer_type("int");
771 Struct_type* root_list_type =
772 Type::make_builtin_struct_type(3,
775 "roots", root_array_type);
777 // Build an initializer for the roots array.
779 Expression_list* roots_init = new Expression_list();
781 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
785 Expression_list* init = new Expression_list();
787 Location no_loc = (*p)->location();
788 Expression* decl = Expression::make_var_reference(*p, no_loc);
789 Expression* decl_addr =
790 Expression::make_unary(OPERATOR_AND, decl, no_loc);
791 decl_addr->unary_expression()->set_does_not_escape();
792 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
793 init->push_back(decl_addr);
796 Expression::make_type_info(decl->type(),
797 Expression::TYPE_INFO_SIZE);
798 init->push_back(size);
800 Expression* ptrdata =
801 Expression::make_type_info(decl->type(),
802 Expression::TYPE_INFO_BACKEND_PTRDATA);
803 init->push_back(ptrdata);
805 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
806 init->push_back(gcdata);
808 Expression* root_ctor =
809 Expression::make_struct_composite_literal(root_type, init, no_loc);
810 roots_init->push_back(root_ctor);
813 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
814 p != this->gc_roots_.end();
817 Expression_list *init = new Expression_list();
819 Expression* expr = *p;
820 Location eloc = expr->location();
821 init->push_back(Expression::make_cast(pvt, expr, eloc));
823 Type* type = expr->type()->points_to();
824 go_assert(type != NULL);
827 Expression::make_type_info(type,
828 Expression::TYPE_INFO_SIZE);
829 init->push_back(size);
831 Expression* ptrdata =
832 Expression::make_type_info(type,
833 Expression::TYPE_INFO_BACKEND_PTRDATA);
834 init->push_back(ptrdata);
836 Expression* gcdata = Expression::make_ptrmask_symbol(type);
837 init->push_back(gcdata);
839 Expression* root_ctor =
840 Expression::make_struct_composite_literal(root_type, init, eloc);
841 roots_init->push_back(root_ctor);
844 // Build a constructor for the struct.
846 Expression_list* root_list_init = new Expression_list();
847 root_list_init->push_back(Expression::make_nil(builtin_loc));
848 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
851 Expression* roots_ctor =
852 Expression::make_array_composite_literal(root_array_type, roots_init,
854 root_list_init->push_back(roots_ctor);
856 Expression* root_list_ctor =
857 Expression::make_struct_composite_literal(root_list_type, root_list_init,
860 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
862 root_addr->unary_expression()->set_is_gc_root();
863 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
864 builtin_loc, 1, root_addr);
866 Translate_context context(this, NULL, NULL, NULL);
867 Bexpression* bcall = register_roots->get_backend(&context);
868 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
871 // Get the name to use for the import control function. If there is a
872 // global function or variable, then we know that that name must be
873 // unique in the link, and we use it as the basis for our name.
876 Gogo::get_init_fn_name()
878 if (this->init_fn_name_.empty())
880 go_assert(this->package_ != NULL);
881 if (this->is_main_package())
883 // Use a name which the runtime knows.
884 this->init_fn_name_ = "__go_init_main";
888 std::string s = this->pkgpath_symbol();
889 s.append("..import");
890 this->init_fn_name_ = s;
894 return this->init_fn_name_;
897 // Build the decl for the initialization function.
900 Gogo::initialization_function_decl()
902 std::string name = this->get_init_fn_name();
903 Location loc = this->package_->location();
905 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
906 Function* initfn = new Function(fntype, NULL, NULL, loc);
907 return Named_object::make_function(name, NULL, initfn);
910 // Create the magic initialization function. CODE_STMT is the
911 // code that it needs to run.
914 Gogo::create_initialization_function(Named_object* initfn,
915 Bstatement* code_stmt)
917 // Make sure that we thought we needed an initialization function,
918 // as otherwise we will not have reported it in the export data.
919 go_assert(this->is_main_package() || this->need_init_fn_);
922 initfn = this->initialization_function_decl();
924 // Bind the initialization function code to a block.
925 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
926 Location pkg_loc = this->package_->location();
927 std::vector<Bvariable*> vars;
928 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
930 if (!this->backend()->function_set_body(fndecl, code_stmt))
932 go_assert(saw_errors());
938 // Search for references to VAR in any statements or called functions.
940 class Find_var : public Traverse
943 // A hash table we use to avoid looping. The index is the name of a
944 // named object. We only look through objects defined in this
946 typedef Unordered_set(const void*) Seen_objects;
948 Find_var(Named_object* var, Seen_objects* seen_objects)
949 : Traverse(traverse_expressions),
950 var_(var), seen_objects_(seen_objects), found_(false)
953 // Whether the variable was found.
956 { return this->found_; }
959 expression(Expression**);
962 // The variable we are looking for.
964 // Names of objects we have already seen.
965 Seen_objects* seen_objects_;
966 // True if the variable was found.
970 // See if EXPR refers to VAR, looking through function calls and
971 // variable initializations.
974 Find_var::expression(Expression** pexpr)
976 Expression* e = *pexpr;
978 Var_expression* ve = e->var_expression();
981 Named_object* v = ve->named_object();
985 return TRAVERSE_EXIT;
988 if (v->is_variable() && v->package() == NULL)
990 Expression* init = v->var_value()->init();
993 std::pair<Seen_objects::iterator, bool> ins =
994 this->seen_objects_->insert(v);
997 // This is the first time we have seen this name.
998 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
999 return TRAVERSE_EXIT;
1005 // We traverse the code of any function or bound method we see. Note that
1006 // this means that we will traverse the code of a function or bound method
1007 // whose address is taken even if it is not called.
1008 Func_expression* fe = e->func_expression();
1009 Bound_method_expression* bme = e->bound_method_expression();
1010 if (fe != NULL || bme != NULL)
1012 const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
1013 if (f->is_function() && f->package() == NULL)
1015 std::pair<Seen_objects::iterator, bool> ins =
1016 this->seen_objects_->insert(f);
1019 // This is the first time we have seen this name.
1020 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
1021 return TRAVERSE_EXIT;
1026 Temporary_reference_expression* tre = e->temporary_reference_expression();
1029 Temporary_statement* ts = tre->statement();
1030 Expression* init = ts->init();
1033 std::pair<Seen_objects::iterator, bool> ins =
1034 this->seen_objects_->insert(ts);
1037 // This is the first time we have seen this temporary
1039 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1040 return TRAVERSE_EXIT;
1045 return TRAVERSE_CONTINUE;
1048 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1051 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1054 Find_var::Seen_objects seen_objects;
1055 Find_var find_var(var, &seen_objects);
1057 Expression::traverse(&expr, &find_var);
1058 if (preinit != NULL)
1059 preinit->traverse(&find_var);
1062 Expression* init = dep->var_value()->init();
1064 Expression::traverse(&init, &find_var);
1065 if (dep->var_value()->has_pre_init())
1066 dep->var_value()->preinit()->traverse(&find_var);
1069 return find_var.found();
1072 // Sort variable initializations. If the initialization expression
1073 // for variable A refers directly or indirectly to the initialization
1074 // expression for variable B, then we must initialize B before A.
1080 : var_(NULL), init_(NULL), dep_count_(0)
1083 Var_init(Named_object* var, Bstatement* init)
1084 : var_(var), init_(init), dep_count_(0)
1087 // Return the variable.
1090 { return this->var_; }
1092 // Return the initialization expression.
1095 { return this->init_; }
1097 // Return the number of remaining dependencies.
1100 { return this->dep_count_; }
1102 // Increment the number of dependencies.
1105 { ++this->dep_count_; }
1107 // Decrement the number of dependencies.
1110 { --this->dep_count_; }
1113 // The variable being initialized.
1115 // The initialization statement.
1117 // The number of initializations this is dependent on. A variable
1118 // initialization should not be emitted if any of its dependencies
1119 // have not yet been resolved.
1123 // For comparing Var_init keys in a map.
1126 operator<(const Var_init& v1, const Var_init& v2)
1127 { return v1.var()->name() < v2.var()->name(); }
1129 typedef std::list<Var_init> Var_inits;
1131 // Sort the variable initializations. The rule we follow is that we
1132 // emit them in the order they appear in the array, except that if the
1133 // initialization expression for a variable V1 depends upon another
1134 // variable V2 then we initialize V1 after V2.
1137 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1139 if (var_inits->empty())
1142 typedef std::pair<Named_object*, Named_object*> No_no;
1143 typedef std::map<No_no, bool> Cache;
1146 // A mapping from a variable initialization to a set of
1147 // variable initializations that depend on it.
1148 typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1149 Init_deps init_deps;
1150 bool init_loop = false;
1151 for (Var_inits::iterator p1 = var_inits->begin();
1152 p1 != var_inits->end();
1155 Named_object* var = p1->var();
1156 Expression* init = var->var_value()->init();
1157 Block* preinit = var->var_value()->preinit();
1158 Named_object* dep = gogo->var_depends_on(var->var_value());
1160 // Start walking through the list to see which variables VAR
1161 // needs to wait for.
1162 for (Var_inits::iterator p2 = var_inits->begin();
1163 p2 != var_inits->end();
1166 if (var == p2->var())
1169 Named_object* p2var = p2->var();
1170 No_no key(var, p2var);
1171 std::pair<Cache::iterator, bool> ins =
1172 cache.insert(std::make_pair(key, false));
1174 ins.first->second = expression_requires(init, preinit, dep, p2var);
1175 if (ins.first->second)
1177 // VAR depends on P2VAR.
1178 init_deps[*p2].insert(&(*p1));
1179 p1->add_dependency();
1181 // Check for cycles.
1182 key = std::make_pair(p2var, var);
1183 ins = cache.insert(std::make_pair(key, false));
1186 expression_requires(p2var->var_value()->init(),
1187 p2var->var_value()->preinit(),
1188 gogo->var_depends_on(p2var->var_value()),
1190 if (ins.first->second)
1192 go_error_at(var->location(),
1193 ("initialization expressions for %qs and "
1194 "%qs depend upon each other"),
1195 var->message_name().c_str(),
1196 p2var->message_name().c_str());
1197 go_inform(p2->var()->location(), "%qs defined here",
1198 p2var->message_name().c_str());
1206 // If there are no dependencies then the declaration order is sorted.
1207 if (!init_deps.empty() && !init_loop)
1209 // Otherwise, sort variable initializations by emitting all variables with
1210 // no dependencies in declaration order. VAR_INITS is already in
1211 // declaration order.
1213 while (!var_inits->empty())
1215 Var_inits::iterator v1;;
1216 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1218 if (v1->dep_count() == 0)
1221 go_assert(v1 != var_inits->end());
1223 // V1 either has no dependencies or its dependencies have already
1224 // been emitted, add it to READY next. When V1 is emitted, remove
1225 // a dependency from each V that depends on V1.
1226 ready.splice(ready.end(), *var_inits, v1);
1228 Init_deps::iterator p1 = init_deps.find(*v1);
1229 if (p1 != init_deps.end())
1231 std::set<Var_init*> resolved = p1->second;
1232 for (std::set<Var_init*>::iterator pv = resolved.begin();
1233 pv != resolved.end();
1235 (*pv)->remove_dependency();
1236 init_deps.erase(p1);
1239 var_inits->swap(ready);
1240 go_assert(init_deps.empty());
1243 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1244 // check for a loop of VAR on itself.
1245 // interpret as a loop.
1246 for (Var_inits::const_iterator p = var_inits->begin();
1247 p != var_inits->end();
1249 gogo->check_self_dep(p->var());
1252 // Give an error if the initialization expression for VAR depends on
1253 // itself. We only check if INIT is not NULL and there is no
1254 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1255 // which we will interpret as a loop.
1258 Gogo::check_self_dep(Named_object* var)
1260 Expression* init = var->var_value()->init();
1261 Block* preinit = var->var_value()->preinit();
1262 Named_object* dep = this->var_depends_on(var->var_value());
1265 && expression_requires(init, preinit, NULL, var))
1266 go_error_at(var->location(),
1267 "initialization expression for %qs depends upon itself",
1268 var->message_name().c_str());
1271 // Write out the global definitions.
1274 Gogo::write_globals()
1276 this->build_interface_method_tables();
1278 Bindings* bindings = this->current_bindings();
1280 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1281 p != bindings->end_declarations();
1284 // If any function declarations needed a descriptor, make sure
1286 Named_object* no = p->second;
1287 if (no->is_function_declaration())
1288 no->func_declaration_value()->build_backend_descriptor(this);
1291 // Lists of globally declared types, variables, constants, and functions
1292 // that must be defined.
1293 std::vector<Btype*> type_decls;
1294 std::vector<Bvariable*> var_decls;
1295 std::vector<Bexpression*> const_decls;
1296 std::vector<Bfunction*> func_decls;
1298 // The init function declaration and associated Bfunction, if necessary.
1299 Named_object* init_fndecl = NULL;
1300 Bfunction* init_bfn = NULL;
1302 std::vector<Bstatement*> init_stmts;
1303 std::vector<Bstatement*> var_init_stmts;
1305 if (this->is_main_package())
1307 init_fndecl = this->initialization_function_decl();
1308 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1309 this->init_imports(init_stmts, init_bfn);
1312 // A list of variable initializations.
1313 Var_inits var_inits;
1315 // A list of variables which need to be registered with the garbage
1317 size_t count_definitions = bindings->size_definitions();
1318 std::vector<Named_object*> var_gc;
1319 var_gc.reserve(count_definitions);
1321 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1322 p != bindings->end_definitions();
1325 Named_object* no = *p;
1326 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1328 // There is nothing to do for a package.
1329 if (no->is_package())
1332 // There is nothing to do for an object which was imported from
1333 // a different package into the global scope.
1334 if (no->package() != NULL)
1337 // Skip blank named functions and constants.
1338 if ((no->is_function() && no->func_value()->is_sink())
1339 || (no->is_const() && no->const_value()->is_sink()))
1342 // There is nothing useful we can output for constants which
1343 // have ideal or non-integral type.
1346 Type* type = no->const_value()->type();
1348 type = no->const_value()->expr()->type();
1349 if (type->is_abstract() || !type->is_numeric_type())
1353 if (!no->is_variable())
1354 no->get_backend(this, const_decls, type_decls, func_decls);
1357 Variable* var = no->var_value();
1358 Bvariable* bvar = no->get_backend_variable(this, NULL);
1359 var_decls.push_back(bvar);
1361 // Check for a sink variable, which may be used to run an
1362 // initializer purely for its side effects.
1363 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1365 Bstatement* var_init_stmt = NULL;
1366 if (!var->has_pre_init())
1368 // If the backend representation of the variable initializer is
1369 // constant, we can just set the initial value using
1370 // global_var_set_init instead of during the init() function.
1371 // The initializer is constant if it is the zero-value of the
1372 // variable's type or if the initial value is an immutable value
1373 // that is not copied to the heap.
1374 bool is_static_initializer = false;
1375 if (var->init() == NULL)
1376 is_static_initializer = true;
1379 Type* var_type = var->type();
1380 Expression* init = var->init();
1381 Expression* init_cast =
1382 Expression::make_cast(var_type, init, var->location());
1383 is_static_initializer = init_cast->is_static_initializer();
1386 // Non-constant variable initializations might need to create
1387 // temporary variables, which will need the initialization
1388 // function as context.
1389 Named_object* var_init_fn;
1390 if (is_static_initializer)
1394 if (init_fndecl == NULL)
1396 init_fndecl = this->initialization_function_decl();
1397 Function* func = init_fndecl->func_value();
1398 init_bfn = func->get_or_make_decl(this, init_fndecl);
1400 var_init_fn = init_fndecl;
1402 Bexpression* var_binit = var->get_init(this, var_init_fn);
1404 if (var_binit == NULL)
1406 else if (is_static_initializer)
1408 if (expression_requires(var->init(), NULL,
1409 this->var_depends_on(var), no))
1410 go_error_at(no->location(),
1411 "initialization expression for %qs depends "
1413 no->message_name().c_str());
1414 this->backend()->global_variable_set_init(bvar, var_binit);
1418 this->backend()->expression_statement(init_bfn, var_binit);
1421 Location loc = var->location();
1422 Bexpression* var_expr =
1423 this->backend()->var_expression(bvar, VE_lvalue, loc);
1425 this->backend()->assignment_statement(init_bfn, var_expr,
1431 // We are going to create temporary variables which
1432 // means that we need an fndecl.
1433 if (init_fndecl == NULL)
1434 init_fndecl = this->initialization_function_decl();
1436 Bvariable* var_decl = is_sink ? NULL : bvar;
1437 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1440 if (var_init_stmt != NULL)
1442 if (var->init() == NULL && !var->has_pre_init())
1443 var_init_stmts.push_back(var_init_stmt);
1445 var_inits.push_back(Var_init(no, var_init_stmt));
1447 else if (this->var_depends_on(var) != NULL)
1449 // This variable is initialized from something that is
1450 // not in its init or preinit. This variable needs to
1451 // participate in dependency analysis sorting, in case
1452 // some other variable depends on this one.
1453 Btype* btype = no->var_value()->type()->get_backend(this);
1454 Bexpression* zero = this->backend()->zero_expression(btype);
1455 Bstatement* zero_stmt =
1456 this->backend()->expression_statement(init_bfn, zero);
1457 var_inits.push_back(Var_init(no, zero_stmt));
1460 // Collect a list of all global variables with pointers,
1461 // to register them for the garbage collector.
1462 if (!is_sink && var->type()->has_pointer())
1464 // Avoid putting runtime.gcRoots itself on the list.
1465 if (this->compiling_runtime()
1466 && this->package_name() == "runtime"
1467 && Gogo::unpack_hidden_name(no->name()) == "gcRoots")
1470 var_gc.push_back(no);
1475 // Register global variables with the garbage collector.
1476 this->register_gc_vars(var_gc, init_stmts, init_bfn);
1478 // Simple variable initializations, after all variables are
1480 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1482 // Complete variable initializations, first sorting them into a
1484 if (!var_inits.empty())
1486 sort_var_inits(this, &var_inits);
1487 for (Var_inits::const_iterator p = var_inits.begin();
1488 p != var_inits.end();
1490 init_stmts.push_back(p->init());
1493 // After all the variables are initialized, call the init
1494 // functions if there are any. Init functions take no arguments, so
1495 // we pass in EMPTY_ARGS to call them.
1496 std::vector<Bexpression*> empty_args;
1497 for (std::vector<Named_object*>::const_iterator p =
1498 this->init_functions_.begin();
1499 p != this->init_functions_.end();
1502 Location func_loc = (*p)->location();
1503 Function* func = (*p)->func_value();
1504 Bfunction* initfn = func->get_or_make_decl(this, *p);
1505 Bexpression* func_code =
1506 this->backend()->function_code_expression(initfn, func_loc);
1507 Bexpression* call = this->backend()->call_expression(initfn, func_code,
1510 Bstatement* ist = this->backend()->expression_statement(initfn, call);
1511 init_stmts.push_back(ist);
1514 // Set up a magic function to do all the initialization actions.
1515 // This will be called if this package is imported.
1516 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1517 if (this->need_init_fn_ || this->is_main_package())
1520 this->create_initialization_function(init_fndecl, init_fncode);
1521 if (init_fndecl != NULL)
1522 func_decls.push_back(init_fndecl->func_value()->get_decl());
1525 // We should not have seen any new bindings created during the conversion.
1526 go_assert(count_definitions == this->current_bindings()->size_definitions());
1528 // Define all globally declared values.
1530 this->backend()->write_global_definitions(type_decls, const_decls,
1531 func_decls, var_decls);
1534 // Return the current block.
1537 Gogo::current_block()
1539 if (this->functions_.empty())
1542 return this->functions_.back().blocks.back();
1545 // Look up a name in the current binding contour. If PFUNCTION is not
1546 // NULL, set it to the function in which the name is defined, or NULL
1547 // if the name is defined in global scope.
1550 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1552 if (pfunction != NULL)
1555 if (Gogo::is_sink_name(name))
1556 return Named_object::make_sink();
1558 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1559 p != this->functions_.rend();
1562 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1565 if (pfunction != NULL)
1566 *pfunction = p->function;
1571 if (this->package_ != NULL)
1573 Named_object* ret = this->package_->bindings()->lookup(name);
1576 if (ret->package() != NULL)
1578 std::string dot_alias = "." + ret->package()->package_name();
1579 ret->package()->note_usage(dot_alias);
1585 // We do not look in the global namespace. If we did, the global
1586 // namespace would effectively hide names which were defined in
1587 // package scope which we have not yet seen. Instead,
1588 // define_global_names is called after parsing is over to connect
1589 // undefined names at package scope with names defined at global
1595 // Look up a name in the current block, without searching enclosing
1599 Gogo::lookup_in_block(const std::string& name) const
1601 go_assert(!this->functions_.empty());
1602 go_assert(!this->functions_.back().blocks.empty());
1603 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1606 // Look up a name in the global namespace.
1609 Gogo::lookup_global(const char* name) const
1611 return this->globals_->lookup(name);
1614 // Add an imported package.
1617 Gogo::add_imported_package(const std::string& real_name,
1618 const std::string& alias_arg,
1619 bool is_alias_exported,
1620 const std::string& pkgpath,
1621 const std::string& pkgpath_symbol,
1623 bool* padd_to_globals)
1625 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1626 ret->set_package_name(real_name, location);
1628 *padd_to_globals = false;
1630 if (alias_arg == "_")
1632 else if (alias_arg == ".")
1634 *padd_to_globals = true;
1635 std::string dot_alias = "." + real_name;
1636 ret->add_alias(dot_alias, location);
1640 std::string alias = alias_arg;
1644 is_alias_exported = Lex::is_exported_name(alias);
1646 ret->add_alias(alias, location);
1647 alias = this->pack_hidden_name(alias, is_alias_exported);
1648 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1649 if (!no->is_package())
1656 // Register a package. This package may or may not be imported. This
1657 // returns the Package structure for the package, creating if it
1658 // necessary. LOCATION is the location of the import statement that
1659 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1660 // for names in the package; it may be the empty string, in which case
1661 // we either get it later or make a guess when we need it.
1664 Gogo::register_package(const std::string& pkgpath,
1665 const std::string& pkgpath_symbol, Location location)
1667 Package* package = NULL;
1668 std::pair<Packages::iterator, bool> ins =
1669 this->packages_.insert(std::make_pair(pkgpath, package));
1672 // We have seen this package name before.
1673 package = ins.first->second;
1674 go_assert(package != NULL && package->pkgpath() == pkgpath);
1675 if (!pkgpath_symbol.empty())
1676 package->set_pkgpath_symbol(pkgpath_symbol);
1677 if (Linemap::is_unknown_location(package->location()))
1678 package->set_location(location);
1682 // First time we have seen this package name.
1683 package = new Package(pkgpath, pkgpath_symbol, location);
1684 go_assert(ins.first->second == NULL);
1685 ins.first->second = package;
1691 // Start compiling a function.
1694 Gogo::start_function(const std::string& name, Function_type* type,
1695 bool add_method_to_type, Location location)
1697 bool at_top_level = this->functions_.empty();
1699 Block* block = new Block(NULL, location);
1701 Named_object* enclosing = (at_top_level
1703 : this->functions_.back().function);
1705 Function* function = new Function(type, enclosing, block, location);
1707 if (type->is_method())
1709 const Typed_identifier* receiver = type->receiver();
1710 Variable* this_param = new Variable(receiver->type(), NULL, false,
1711 true, true, location);
1712 std::string rname = receiver->name();
1713 if (rname.empty() || Gogo::is_sink_name(rname))
1715 // We need to give receivers a name since they wind up in
1716 // DECL_ARGUMENTS. FIXME.
1717 static unsigned int count;
1719 snprintf(buf, sizeof buf, "r.%u", count);
1723 block->bindings()->add_variable(rname, NULL, this_param);
1726 const Typed_identifier_list* parameters = type->parameters();
1727 bool is_varargs = type->is_varargs();
1728 if (parameters != NULL)
1730 for (Typed_identifier_list::const_iterator p = parameters->begin();
1731 p != parameters->end();
1734 Variable* param = new Variable(p->type(), NULL, false, true, false,
1736 if (is_varargs && p + 1 == parameters->end())
1737 param->set_is_varargs_parameter();
1739 std::string pname = p->name();
1740 if (pname.empty() || Gogo::is_sink_name(pname))
1742 // We need to give parameters a name since they wind up
1743 // in DECL_ARGUMENTS. FIXME.
1744 static unsigned int count;
1746 snprintf(buf, sizeof buf, "p.%u", count);
1750 block->bindings()->add_variable(pname, NULL, param);
1754 function->create_result_variables(this);
1756 const std::string* pname;
1757 std::string nested_name;
1758 bool is_init = false;
1759 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1761 if ((type->parameters() != NULL && !type->parameters()->empty())
1762 || (type->results() != NULL && !type->results()->empty()))
1763 go_error_at(location,
1764 "func init must have no arguments and no return values");
1765 // There can be multiple "init" functions, so give them each a
1767 static int init_count;
1769 snprintf(buf, sizeof buf, ".$init%d", init_count);
1772 pname = &nested_name;
1775 else if (!name.empty())
1779 // Invent a name for a nested function.
1780 static int nested_count;
1782 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
1785 pname = &nested_name;
1789 if (Gogo::is_sink_name(*pname))
1791 static int sink_count;
1793 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
1795 ret = Named_object::make_function(buf, NULL, function);
1796 ret->func_value()->set_is_sink();
1798 if (!type->is_method())
1799 ret = this->package_->bindings()->add_named_object(ret);
1800 else if (add_method_to_type)
1802 // We should report errors even for sink methods.
1803 Type* rtype = type->receiver()->type();
1804 // Avoid points_to and deref to avoid getting an error if
1805 // the type is not yet defined.
1806 if (rtype->classification() == Type::TYPE_POINTER)
1807 rtype = rtype->points_to();
1808 while (rtype->named_type() != NULL
1809 && rtype->named_type()->is_alias())
1810 rtype = rtype->named_type()->real_type()->forwarded();
1811 if (rtype->is_error_type())
1813 else if (rtype->named_type() != NULL)
1815 if (rtype->named_type()->named_object()->package() != NULL)
1816 go_error_at(type->receiver()->location(),
1817 "may not define methods on non-local type");
1819 else if (rtype->forward_declaration_type() != NULL)
1821 // Go ahead and add the method in case we need to report
1822 // an error when we see the definition.
1823 rtype->forward_declaration_type()->add_existing_method(ret);
1826 go_error_at(type->receiver()->location(),
1827 ("invalid receiver type "
1828 "(receiver must be a named type)"));
1831 else if (!type->is_method())
1833 ret = this->package_->bindings()->add_function(*pname, NULL, function);
1834 if (!ret->is_function() || ret->func_value() != function)
1836 // Redefinition error. Invent a name to avoid knockon
1838 static int redefinition_count;
1840 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
1841 ++redefinition_count;
1842 ret = this->package_->bindings()->add_function(buf, NULL, function);
1847 if (!add_method_to_type)
1848 ret = Named_object::make_function(name, NULL, function);
1851 go_assert(at_top_level);
1852 Type* rtype = type->receiver()->type();
1854 // We want to look through the pointer created by the
1855 // parser, without getting an error if the type is not yet
1857 if (rtype->classification() == Type::TYPE_POINTER)
1858 rtype = rtype->points_to();
1860 while (rtype->named_type() != NULL
1861 && rtype->named_type()->is_alias())
1862 rtype = rtype->named_type()->real_type()->forwarded();
1864 if (rtype->is_error_type())
1865 ret = Named_object::make_function(name, NULL, function);
1866 else if (rtype->named_type() != NULL)
1868 if (rtype->named_type()->named_object()->package() != NULL)
1870 go_error_at(type->receiver()->location(),
1871 "may not define methods on non-local type");
1872 ret = Named_object::make_function(name, NULL, function);
1876 ret = rtype->named_type()->add_method(name, function);
1877 if (!ret->is_function())
1879 // Redefinition error.
1880 ret = Named_object::make_function(name, NULL, function);
1884 else if (rtype->forward_declaration_type() != NULL)
1886 Named_object* type_no =
1887 rtype->forward_declaration_type()->named_object();
1888 if (type_no->is_unknown())
1890 // If we are seeing methods it really must be a
1891 // type. Declare it as such. An alternative would
1892 // be to support lists of methods for unknown
1893 // expressions. Either way the error messages if
1894 // this is not a type are going to get confusing.
1895 Named_object* declared =
1896 this->declare_package_type(type_no->name(),
1897 type_no->location());
1899 == type_no->unknown_value()->real_named_object());
1901 ret = rtype->forward_declaration_type()->add_method(name,
1906 go_error_at(type->receiver()->location(),
1907 ("invalid receiver type (receiver must "
1908 "be a named type)"));
1909 ret = Named_object::make_function(name, NULL, function);
1912 this->package_->bindings()->add_method(ret);
1915 this->functions_.resize(this->functions_.size() + 1);
1916 Open_function& of(this->functions_.back());
1918 of.blocks.push_back(block);
1922 this->init_functions_.push_back(ret);
1923 this->need_init_fn_ = true;
1929 // Finish compiling a function.
1932 Gogo::finish_function(Location location)
1934 this->finish_block(location);
1935 go_assert(this->functions_.back().blocks.empty());
1936 this->functions_.pop_back();
1939 // Return the current function.
1942 Gogo::current_function() const
1944 go_assert(!this->functions_.empty());
1945 return this->functions_.back().function;
1948 // Start a new block.
1951 Gogo::start_block(Location location)
1953 go_assert(!this->functions_.empty());
1954 Block* block = new Block(this->current_block(), location);
1955 this->functions_.back().blocks.push_back(block);
1961 Gogo::finish_block(Location location)
1963 go_assert(!this->functions_.empty());
1964 go_assert(!this->functions_.back().blocks.empty());
1965 Block* block = this->functions_.back().blocks.back();
1966 this->functions_.back().blocks.pop_back();
1967 block->set_end_location(location);
1971 // Add an erroneous name.
1974 Gogo::add_erroneous_name(const std::string& name)
1976 return this->package_->bindings()->add_erroneous_name(name);
1979 // Add an unknown name.
1982 Gogo::add_unknown_name(const std::string& name, Location location)
1984 return this->package_->bindings()->add_unknown_name(name, location);
1987 // Declare a function.
1990 Gogo::declare_function(const std::string& name, Function_type* type,
1993 if (!type->is_method())
1994 return this->current_bindings()->add_function_declaration(name, NULL, type,
1998 // We don't bother to add this to the list of global
2000 Type* rtype = type->receiver()->type();
2002 // We want to look through the pointer created by the
2003 // parser, without getting an error if the type is not yet
2005 if (rtype->classification() == Type::TYPE_POINTER)
2006 rtype = rtype->points_to();
2008 if (rtype->is_error_type())
2010 else if (rtype->named_type() != NULL)
2011 return rtype->named_type()->add_method_declaration(name, NULL, type,
2013 else if (rtype->forward_declaration_type() != NULL)
2015 Forward_declaration_type* ftype = rtype->forward_declaration_type();
2016 return ftype->add_method_declaration(name, NULL, type, location);
2020 go_error_at(type->receiver()->location(),
2021 "invalid receiver type (receiver must be a named type)");
2022 return Named_object::make_erroneous_name(name);
2027 // Add a label definition.
2030 Gogo::add_label_definition(const std::string& label_name,
2033 go_assert(!this->functions_.empty());
2034 Function* func = this->functions_.back().function->func_value();
2035 Label* label = func->add_label_definition(this, label_name, location);
2036 this->add_statement(Statement::make_label_statement(label, location));
2040 // Add a label reference.
2043 Gogo::add_label_reference(const std::string& label_name,
2044 Location location, bool issue_goto_errors)
2046 go_assert(!this->functions_.empty());
2047 Function* func = this->functions_.back().function->func_value();
2048 return func->add_label_reference(this, label_name, location,
2052 // Return the current binding state.
2055 Gogo::bindings_snapshot(Location location)
2057 return new Bindings_snapshot(this->current_block(), location);
2063 Gogo::add_statement(Statement* statement)
2065 go_assert(!this->functions_.empty()
2066 && !this->functions_.back().blocks.empty());
2067 this->functions_.back().blocks.back()->add_statement(statement);
2073 Gogo::add_block(Block* block, Location location)
2075 go_assert(!this->functions_.empty()
2076 && !this->functions_.back().blocks.empty());
2077 Statement* statement = Statement::make_block_statement(block, location);
2078 this->functions_.back().blocks.back()->add_statement(statement);
2084 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2087 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2093 Gogo::add_type(const std::string& name, Type* type, Location location)
2095 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2097 if (!this->in_global_scope() && no->is_type())
2099 Named_object* f = this->functions_.back().function;
2101 if (f->is_function())
2102 index = f->func_value()->new_local_type_index();
2105 no->type_value()->set_in_function(f, index);
2109 // Add a named type.
2112 Gogo::add_named_type(Named_type* type)
2114 go_assert(this->in_global_scope());
2115 this->current_bindings()->add_named_type(type);
2121 Gogo::declare_type(const std::string& name, Location location)
2123 Bindings* bindings = this->current_bindings();
2124 Named_object* no = bindings->add_type_declaration(name, NULL, location);
2125 if (!this->in_global_scope() && no->is_type_declaration())
2127 Named_object* f = this->functions_.back().function;
2129 if (f->is_function())
2130 index = f->func_value()->new_local_type_index();
2133 no->type_declaration_value()->set_in_function(f, index);
2138 // Declare a type at the package level.
2141 Gogo::declare_package_type(const std::string& name, Location location)
2143 return this->package_->bindings()->add_type_declaration(name, NULL, location);
2146 // Declare a function at the package level.
2149 Gogo::declare_package_function(const std::string& name, Function_type* type,
2152 return this->package_->bindings()->add_function_declaration(name, NULL, type,
2156 // Define a type which was already declared.
2159 Gogo::define_type(Named_object* no, Named_type* type)
2161 this->current_bindings()->define_type(no, type);
2167 Gogo::add_variable(const std::string& name, Variable* variable)
2169 Named_object* no = this->current_bindings()->add_variable(name, NULL,
2172 // In a function the middle-end wants to see a DECL_EXPR node.
2174 && no->is_variable()
2175 && !no->var_value()->is_parameter()
2176 && !this->functions_.empty())
2177 this->add_statement(Statement::make_variable_declaration(no));
2182 // Add a sink--a reference to the blank identifier _.
2187 return Named_object::make_sink();
2190 // Add a named object for a dot import.
2193 Gogo::add_dot_import_object(Named_object* no)
2195 // If the name already exists, then it was defined in some file seen
2196 // earlier. If the earlier name is just a declaration, don't add
2197 // this name, because that will cause the previous declaration to
2198 // merge to this imported name, which should not happen. Just add
2199 // this name to the list of file block names to get appropriate
2200 // errors if we see a later definition.
2201 Named_object* e = this->package_->bindings()->lookup(no->name());
2202 if (e != NULL && e->package() == NULL)
2204 if (e->is_unknown())
2206 if (e->package() == NULL
2207 && (e->is_type_declaration()
2208 || e->is_function_declaration()
2209 || e->is_unknown()))
2211 this->add_file_block_name(no->name(), no->location());
2216 this->current_bindings()->add_named_object(no);
2219 // Add a linkname. This implements the go:linkname compiler directive.
2220 // We only support this for functions and function declarations.
2223 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2224 const std::string& ext_name, Location loc)
2227 this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2230 go_error_at(loc, "%s is not defined", go_name.c_str());
2231 else if (no->is_function())
2232 no->func_value()->set_asm_name(ext_name);
2233 else if (no->is_function_declaration())
2234 no->func_declaration_value()->set_asm_name(ext_name);
2237 ("%s is not a function; "
2238 "//go:linkname is only supported for functions"),
2242 // Mark all local variables used. This is used when some types of
2243 // parse error occur.
2246 Gogo::mark_locals_used()
2248 for (Open_functions::iterator pf = this->functions_.begin();
2249 pf != this->functions_.end();
2252 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2253 pb != pf->blocks.end();
2255 (*pb)->bindings()->mark_locals_used();
2259 // Record that we've seen an interface type.
2262 Gogo::record_interface_type(Interface_type* itype)
2264 this->interface_types_.push_back(itype);
2267 // Return an erroneous name that indicates that an error has already
2271 Gogo::erroneous_name()
2273 static int erroneous_count;
2275 snprintf(name, sizeof name, "$erroneous%d", erroneous_count);
2280 // Return whether a name is an erroneous name.
2283 Gogo::is_erroneous_name(const std::string& name)
2285 return name.compare(0, 10, "$erroneous") == 0;
2288 // Return a name for a thunk object.
2293 static int thunk_count;
2294 char thunk_name[50];
2295 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
2300 // Return whether a function is a thunk.
2303 Gogo::is_thunk(const Named_object* no)
2305 return no->name().compare(0, 6, "$thunk") == 0;
2308 // Define the global names. We do this only after parsing all the
2309 // input files, because the program might define the global names
2313 Gogo::define_global_names()
2315 if (this->is_main_package())
2317 // Every Go program has to import the runtime package, so that
2318 // it is properly initialized.
2319 this->import_package("runtime", "_", false, false,
2320 Linemap::predeclared_location());
2323 for (Bindings::const_declarations_iterator p =
2324 this->globals_->begin_declarations();
2325 p != this->globals_->end_declarations();
2328 Named_object* global_no = p->second;
2329 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2330 Named_object* no = this->package_->bindings()->lookup(name);
2334 if (no->is_type_declaration())
2336 if (global_no->is_type())
2338 if (no->type_declaration_value()->has_methods())
2340 for (std::vector<Named_object*>::const_iterator p =
2341 no->type_declaration_value()->methods()->begin();
2342 p != no->type_declaration_value()->methods()->end();
2344 go_error_at((*p)->location(),
2345 "may not define methods on non-local type");
2347 no->set_type_value(global_no->type_value());
2351 go_error_at(no->location(), "expected type");
2352 Type* errtype = Type::make_error_type();
2354 Named_object::make_type("erroneous_type", NULL, errtype,
2355 Linemap::predeclared_location());
2356 no->set_type_value(err->type_value());
2359 else if (no->is_unknown())
2360 no->unknown_value()->set_real_named_object(global_no);
2363 // Give an error if any name is defined in both the package block
2364 // and the file block. For example, this can happen if one file
2365 // imports "fmt" and another file defines a global variable fmt.
2366 for (Bindings::const_declarations_iterator p =
2367 this->package_->bindings()->begin_declarations();
2368 p != this->package_->bindings()->end_declarations();
2371 if (p->second->is_unknown()
2372 && p->second->unknown_value()->real_named_object() == NULL)
2374 // No point in warning about an undefined name, as we will
2375 // get other errors later anyhow.
2378 File_block_names::const_iterator pf =
2379 this->file_block_names_.find(p->second->name());
2380 if (pf != this->file_block_names_.end())
2382 std::string n = p->second->message_name();
2383 go_error_at(p->second->location(),
2384 "%qs defined as both imported name and global name",
2386 go_inform(pf->second, "%qs imported here", n.c_str());
2389 // No package scope identifier may be named "init".
2390 if (!p->second->is_function()
2391 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2393 go_error_at(p->second->location(),
2394 "cannot declare init - must be func");
2399 // Clear out names in file scope.
2402 Gogo::clear_file_scope()
2404 this->package_->bindings()->clear_file_scope(this);
2406 // Warn about packages which were imported but not used.
2407 bool quiet = saw_errors();
2408 for (Packages::iterator p = this->packages_.begin();
2409 p != this->packages_.end();
2412 Package* package = p->second;
2413 if (package != this->package_ && !quiet)
2415 for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2416 p1 != package->aliases().end();
2419 if (!p1->second->used())
2421 // Give a more refined error message if the alias name is known.
2422 std::string pkg_name = package->package_name();
2423 if (p1->first != pkg_name && p1->first[0] != '.')
2425 go_error_at(p1->second->location(),
2426 "imported and not used: %s as %s",
2427 Gogo::message_name(pkg_name).c_str(),
2428 Gogo::message_name(p1->first).c_str());
2431 go_error_at(p1->second->location(),
2432 "imported and not used: %s",
2433 Gogo::message_name(pkg_name).c_str());
2437 package->clear_used();
2440 this->current_file_imported_unsafe_ = false;
2443 // Queue up a type specific function for later writing. These are
2444 // written out in write_specific_type_functions, called after the
2445 // parse tree is lowered.
2448 Gogo::queue_specific_type_function(Type* type, Named_type* name, int64_t size,
2449 const std::string& hash_name,
2450 Function_type* hash_fntype,
2451 const std::string& equal_name,
2452 Function_type* equal_fntype)
2454 go_assert(!this->specific_type_functions_are_written_);
2455 go_assert(!this->in_global_scope());
2456 Specific_type_function* tsf = new Specific_type_function(type, name, size,
2461 this->specific_type_functions_.push_back(tsf);
2464 // Look for types which need specific hash or equality functions.
2466 class Specific_type_functions : public Traverse
2469 Specific_type_functions(Gogo* gogo)
2470 : Traverse(traverse_types),
2482 Specific_type_functions::type(Type* t)
2484 Named_object* hash_fn;
2485 Named_object* equal_fn;
2486 switch (t->classification())
2488 case Type::TYPE_NAMED:
2490 Named_type* nt = t->named_type();
2491 if (t->needs_specific_type_functions(this->gogo_))
2492 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2494 // If this is a struct type, we don't want to make functions
2495 // for the unnamed struct.
2496 Type* rt = nt->real_type();
2497 if (rt->struct_type() == NULL)
2499 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2500 return TRAVERSE_EXIT;
2504 // If this type is defined in another package, then we don't
2505 // need to worry about the unexported fields.
2506 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2507 const Struct_field_list* fields = rt->struct_type()->fields();
2508 for (Struct_field_list::const_iterator p = fields->begin();
2512 if (is_defined_elsewhere
2513 && Gogo::is_hidden_name(p->field_name()))
2515 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2516 return TRAVERSE_EXIT;
2520 return TRAVERSE_SKIP_COMPONENTS;
2523 case Type::TYPE_STRUCT:
2524 case Type::TYPE_ARRAY:
2525 if (t->needs_specific_type_functions(this->gogo_))
2526 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2533 return TRAVERSE_CONTINUE;
2536 // Write out type specific functions.
2539 Gogo::write_specific_type_functions()
2541 Specific_type_functions stf(this);
2542 this->traverse(&stf);
2544 while (!this->specific_type_functions_.empty())
2546 Specific_type_function* tsf = this->specific_type_functions_.back();
2547 this->specific_type_functions_.pop_back();
2548 tsf->type->write_specific_type_functions(this, tsf->name, tsf->size,
2555 this->specific_type_functions_are_written_ = true;
2558 // Traverse the tree.
2561 Gogo::traverse(Traverse* traverse)
2563 // Traverse the current package first for consistency. The other
2564 // packages will only contain imported types, constants, and
2566 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2568 for (Packages::const_iterator p = this->packages_.begin();
2569 p != this->packages_.end();
2572 if (p->second != this->package_)
2574 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2580 // Add a type to verify. This is used for types of sink variables, in
2581 // order to give appropriate error messages.
2584 Gogo::add_type_to_verify(Type* type)
2586 this->verify_types_.push_back(type);
2589 // Traversal class used to verify types.
2591 class Verify_types : public Traverse
2595 : Traverse(traverse_types)
2602 // Verify that a type is correct.
2605 Verify_types::type(Type* t)
2608 return TRAVERSE_SKIP_COMPONENTS;
2609 return TRAVERSE_CONTINUE;
2612 // Verify that all types are correct.
2615 Gogo::verify_types()
2617 Verify_types traverse;
2618 this->traverse(&traverse);
2620 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2621 p != this->verify_types_.end();
2624 this->verify_types_.clear();
2627 // Traversal class used to lower parse tree.
2629 class Lower_parse_tree : public Traverse
2632 Lower_parse_tree(Gogo* gogo, Named_object* function)
2633 : Traverse(traverse_variables
2634 | traverse_constants
2635 | traverse_functions
2636 | traverse_statements
2637 | traverse_expressions),
2638 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2642 set_inserter(const Statement_inserter* inserter)
2643 { this->inserter_ = *inserter; }
2646 variable(Named_object*);
2649 constant(Named_object*, bool);
2652 function(Named_object*);
2655 statement(Block*, size_t* pindex, Statement*);
2658 expression(Expression**);
2663 // The function we are traversing.
2664 Named_object* function_;
2665 // Value to use for the predeclared constant iota.
2667 // Current statement inserter for use by expressions.
2668 Statement_inserter inserter_;
2674 Lower_parse_tree::variable(Named_object* no)
2676 if (!no->is_variable())
2677 return TRAVERSE_CONTINUE;
2679 if (no->is_variable() && no->var_value()->is_global())
2681 // Global variables can have loops in their initialization
2682 // expressions. This is handled in lower_init_expression.
2683 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2685 return TRAVERSE_CONTINUE;
2688 // This is a local variable. We are going to return
2689 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2690 // initialization expression when we reach the variable declaration
2691 // statement. However, that means that we need to traverse the type
2693 if (no->var_value()->has_type())
2695 Type* type = no->var_value()->type();
2698 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2699 return TRAVERSE_EXIT;
2702 go_assert(!no->var_value()->has_pre_init());
2704 return TRAVERSE_SKIP_COMPONENTS;
2707 // Lower constants. We handle constants specially so that we can set
2708 // the right value for the predeclared constant iota. This works in
2709 // conjunction with the way we lower Const_expression objects.
2712 Lower_parse_tree::constant(Named_object* no, bool)
2714 Named_constant* nc = no->const_value();
2716 // Don't get into trouble if the constant's initializer expression
2717 // refers to the constant itself.
2719 return TRAVERSE_CONTINUE;
2722 go_assert(this->iota_value_ == -1);
2723 this->iota_value_ = nc->iota_value();
2724 nc->traverse_expression(this);
2725 this->iota_value_ = -1;
2727 nc->clear_lowering();
2729 // We will traverse the expression a second time, but that will be
2732 return TRAVERSE_CONTINUE;
2735 // Lower the body of a function, and set the closure type. Record the
2736 // function while lowering it, so that we can pass it down when
2737 // lowering an expression.
2740 Lower_parse_tree::function(Named_object* no)
2742 no->func_value()->set_closure_type();
2744 go_assert(this->function_ == NULL);
2745 this->function_ = no;
2746 int t = no->func_value()->traverse(this);
2747 this->function_ = NULL;
2749 if (t == TRAVERSE_EXIT)
2751 return TRAVERSE_SKIP_COMPONENTS;
2754 // Lower statement parse trees.
2757 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2759 // Because we explicitly traverse the statement's contents
2760 // ourselves, we want to skip block statements here. There is
2761 // nothing to lower in a block statement.
2762 if (sorig->is_block_statement())
2763 return TRAVERSE_CONTINUE;
2765 Statement_inserter hold_inserter(this->inserter_);
2766 this->inserter_ = Statement_inserter(block, pindex);
2768 // Lower the expressions first.
2769 int t = sorig->traverse_contents(this);
2770 if (t == TRAVERSE_EXIT)
2772 this->inserter_ = hold_inserter;
2776 // Keep lowering until nothing changes.
2777 Statement* s = sorig;
2780 Statement* snew = s->lower(this->gogo_, this->function_, block,
2785 t = s->traverse_contents(this);
2786 if (t == TRAVERSE_EXIT)
2788 this->inserter_ = hold_inserter;
2794 block->replace_statement(*pindex, s);
2796 this->inserter_ = hold_inserter;
2797 return TRAVERSE_SKIP_COMPONENTS;
2800 // Lower expression parse trees.
2803 Lower_parse_tree::expression(Expression** pexpr)
2805 // We have to lower all subexpressions first, so that we can get
2806 // their type if necessary. This is awkward, because we don't have
2807 // a postorder traversal pass.
2808 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2809 return TRAVERSE_EXIT;
2810 // Keep lowering until nothing changes.
2813 Expression* e = *pexpr;
2814 Expression* enew = e->lower(this->gogo_, this->function_,
2815 &this->inserter_, this->iota_value_);
2818 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2819 return TRAVERSE_EXIT;
2822 return TRAVERSE_SKIP_COMPONENTS;
2825 // Lower the parse tree. This is called after the parse is complete,
2826 // when all names should be resolved.
2829 Gogo::lower_parse_tree()
2831 Lower_parse_tree lower_parse_tree(this, NULL);
2832 this->traverse(&lower_parse_tree);
2834 // There might be type definitions that involve expressions such as the
2835 // array length. Make sure to lower these expressions as well. Otherwise,
2836 // errors hidden within a type can introduce unexpected errors into later
2838 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2839 p != this->verify_types_.end();
2841 Type::traverse(*p, &lower_parse_tree);
2847 Gogo::lower_block(Named_object* function, Block* block)
2849 Lower_parse_tree lower_parse_tree(this, function);
2850 block->traverse(&lower_parse_tree);
2853 // Lower an expression. INSERTER may be NULL, in which case the
2854 // expression had better not need to create any temporaries.
2857 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2860 Lower_parse_tree lower_parse_tree(this, function);
2861 if (inserter != NULL)
2862 lower_parse_tree.set_inserter(inserter);
2863 lower_parse_tree.expression(pexpr);
2866 // Lower a constant. This is called when lowering a reference to a
2867 // constant. We have to make sure that the constant has already been
2871 Gogo::lower_constant(Named_object* no)
2873 go_assert(no->is_const());
2874 Lower_parse_tree lower(this, NULL);
2875 lower.constant(no, false);
2878 // Traverse the tree to create function descriptors as needed.
2880 class Create_function_descriptors : public Traverse
2883 Create_function_descriptors(Gogo* gogo)
2884 : Traverse(traverse_functions | traverse_expressions),
2889 function(Named_object*);
2892 expression(Expression**);
2898 // Create a descriptor for every top-level exported function.
2901 Create_function_descriptors::function(Named_object* no)
2903 if (no->is_function()
2904 && no->func_value()->enclosing() == NULL
2905 && !no->func_value()->is_method()
2906 && !Gogo::is_hidden_name(no->name())
2907 && !Gogo::is_thunk(no))
2908 no->func_value()->descriptor(this->gogo_, no);
2910 return TRAVERSE_CONTINUE;
2913 // If we see a function referenced in any way other than calling it,
2914 // create a descriptor for it.
2917 Create_function_descriptors::expression(Expression** pexpr)
2919 Expression* expr = *pexpr;
2921 Func_expression* fe = expr->func_expression();
2924 // We would not get here for a call to this function, so this is
2925 // a reference to a function other than calling it. We need a
2927 if (fe->closure() != NULL)
2928 return TRAVERSE_CONTINUE;
2929 Named_object* no = fe->named_object();
2930 if (no->is_function() && !no->func_value()->is_method())
2931 no->func_value()->descriptor(this->gogo_, no);
2932 else if (no->is_function_declaration()
2933 && !no->func_declaration_value()->type()->is_method()
2934 && !Linemap::is_predeclared_location(no->location()))
2935 no->func_declaration_value()->descriptor(this->gogo_, no);
2936 return TRAVERSE_CONTINUE;
2939 Bound_method_expression* bme = expr->bound_method_expression();
2942 // We would not get here for a call to this method, so this is a
2943 // method value. We need to create a thunk.
2944 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
2946 return TRAVERSE_CONTINUE;
2949 Interface_field_reference_expression* ifre =
2950 expr->interface_field_reference_expression();
2953 // We would not get here for a call to this interface method, so
2954 // this is a method value. We need to create a thunk.
2955 Interface_type* type = ifre->expr()->type()->interface_type();
2957 Interface_field_reference_expression::create_thunk(this->gogo_, type,
2959 return TRAVERSE_CONTINUE;
2962 Call_expression* ce = expr->call_expression();
2965 Expression* fn = ce->fn();
2966 if (fn->func_expression() != NULL
2967 || fn->bound_method_expression() != NULL
2968 || fn->interface_field_reference_expression() != NULL)
2970 // Traverse the arguments but not the function.
2971 Expression_list* args = ce->args();
2974 if (args->traverse(this) == TRAVERSE_EXIT)
2975 return TRAVERSE_EXIT;
2977 return TRAVERSE_SKIP_COMPONENTS;
2981 return TRAVERSE_CONTINUE;
2984 // Create function descriptors as needed. We need a function
2985 // descriptor for all exported functions and for all functions that
2986 // are referenced without being called.
2989 Gogo::create_function_descriptors()
2991 // Create a function descriptor for any exported function that is
2992 // declared in this package. This is so that we have a descriptor
2993 // for functions written in assembly. Gather the descriptors first
2994 // so that we don't add declarations while looping over them.
2995 std::vector<Named_object*> fndecls;
2996 Bindings* b = this->package_->bindings();
2997 for (Bindings::const_declarations_iterator p = b->begin_declarations();
2998 p != b->end_declarations();
3001 Named_object* no = p->second;
3002 if (no->is_function_declaration()
3003 && !no->func_declaration_value()->type()->is_method()
3004 && !Linemap::is_predeclared_location(no->location())
3005 && !Gogo::is_hidden_name(no->name()))
3006 fndecls.push_back(no);
3008 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
3011 (*p)->func_declaration_value()->descriptor(this, *p);
3014 Create_function_descriptors cfd(this);
3015 this->traverse(&cfd);
3018 // Look for interface types to finalize methods of inherited
3021 class Finalize_methods : public Traverse
3024 Finalize_methods(Gogo* gogo)
3025 : Traverse(traverse_types),
3036 // Finalize the methods of an interface type.
3039 Finalize_methods::type(Type* t)
3041 // Check the classification so that we don't finalize the methods
3042 // twice for a named interface type.
3043 switch (t->classification())
3045 case Type::TYPE_INTERFACE:
3046 t->interface_type()->finalize_methods();
3049 case Type::TYPE_NAMED:
3051 // We have to finalize the methods of the real type first.
3052 // But if the real type is a struct type, then we only want to
3053 // finalize the methods of the field types, not of the struct
3054 // type itself. We don't want to add methods to the struct,
3055 // since it has a name.
3056 Named_type* nt = t->named_type();
3057 Type* rt = nt->real_type();
3058 if (rt->classification() != Type::TYPE_STRUCT)
3060 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
3061 return TRAVERSE_EXIT;
3065 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3066 return TRAVERSE_EXIT;
3069 nt->finalize_methods(this->gogo_);
3071 // If this type is defined in a different package, then finalize the
3072 // types of all the methods, since we won't see them otherwise.
3073 if (nt->named_object()->package() != NULL && nt->has_any_methods())
3075 const Methods* methods = nt->methods();
3076 for (Methods::const_iterator p = methods->begin();
3077 p != methods->end();
3080 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3081 return TRAVERSE_EXIT;
3085 // Finalize the types of all methods that are declared but not
3086 // defined, since we won't see the declarations otherwise.
3087 if (nt->named_object()->package() == NULL
3088 && nt->local_methods() != NULL)
3090 const Bindings* methods = nt->local_methods();
3091 for (Bindings::const_declarations_iterator p =
3092 methods->begin_declarations();
3093 p != methods->end_declarations();
3096 if (p->second->is_function_declaration())
3098 Type* mt = p->second->func_declaration_value()->type();
3099 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3100 return TRAVERSE_EXIT;
3105 return TRAVERSE_SKIP_COMPONENTS;
3108 case Type::TYPE_STRUCT:
3109 // Traverse the field types first in case there is an embedded
3110 // field with methods that the struct should inherit.
3111 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3112 return TRAVERSE_EXIT;
3113 t->struct_type()->finalize_methods(this->gogo_);
3114 return TRAVERSE_SKIP_COMPONENTS;
3120 return TRAVERSE_CONTINUE;
3123 // Finalize method lists and build stub methods for types.
3126 Gogo::finalize_methods()
3128 Finalize_methods finalize(this);
3129 this->traverse(&finalize);
3132 // Set types for unspecified variables and constants.
3135 Gogo::determine_types()
3137 Bindings* bindings = this->current_bindings();
3138 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3139 p != bindings->end_definitions();
3142 if ((*p)->is_function())
3143 (*p)->func_value()->determine_types();
3144 else if ((*p)->is_variable())
3145 (*p)->var_value()->determine_type();
3146 else if ((*p)->is_const())
3147 (*p)->const_value()->determine_type();
3149 // See if a variable requires us to build an initialization
3150 // function. We know that we will see all global variables
3152 if (!this->need_init_fn_ && (*p)->is_variable())
3154 Variable* variable = (*p)->var_value();
3156 // If this is a global variable which requires runtime
3157 // initialization, we need an initialization function.
3158 if (!variable->is_global())
3160 else if (variable->init() == NULL)
3162 else if (variable->type()->interface_type() != NULL)
3163 this->need_init_fn_ = true;
3164 else if (variable->init()->is_constant())
3166 else if (!variable->init()->is_composite_literal())
3167 this->need_init_fn_ = true;
3168 else if (variable->init()->is_nonconstant_composite_literal())
3169 this->need_init_fn_ = true;
3171 // If this is a global variable which holds a pointer value,
3172 // then we need an initialization function to register it as a
3174 if (variable->is_global() && variable->type()->has_pointer())
3175 this->need_init_fn_ = true;
3179 // Determine the types of constants in packages.
3180 for (Packages::const_iterator p = this->packages_.begin();
3181 p != this->packages_.end();
3183 p->second->determine_types();
3186 // Traversal class used for type checking.
3188 class Check_types_traverse : public Traverse
3191 Check_types_traverse(Gogo* gogo)
3192 : Traverse(traverse_variables
3193 | traverse_constants
3194 | traverse_functions
3195 | traverse_statements
3196 | traverse_expressions),
3201 variable(Named_object*);
3204 constant(Named_object*, bool);
3207 function(Named_object*);
3210 statement(Block*, size_t* pindex, Statement*);
3213 expression(Expression**);
3220 // Check that a variable initializer has the right type.
3223 Check_types_traverse::variable(Named_object* named_object)
3225 if (named_object->is_variable())
3227 Variable* var = named_object->var_value();
3229 // Give error if variable type is not defined.
3230 var->type()->base();
3232 Expression* init = var->init();
3235 && !Type::are_assignable(var->type(), init->type(), &reason))
3238 go_error_at(var->location(), "incompatible type in initialization");
3240 go_error_at(var->location(),
3241 "incompatible type in initialization (%s)",
3243 init = Expression::make_error(named_object->location());
3246 else if (init != NULL
3247 && init->func_expression() != NULL)
3249 Named_object* no = init->func_expression()->named_object();
3250 Function_type* fntype;
3251 if (no->is_function())
3252 fntype = no->func_value()->type();
3253 else if (no->is_function_declaration())
3254 fntype = no->func_declaration_value()->type();
3258 // Builtin functions cannot be used as function values for variable
3260 if (fntype->is_builtin())
3262 go_error_at(init->location(),
3263 "invalid use of special builtin function %qs; "
3265 no->message_name().c_str());
3269 && !var->is_global()
3270 && !var->is_parameter()
3271 && !var->is_receiver()
3272 && !var->type()->is_error()
3273 && (init == NULL || !init->is_error_expression())
3274 && !Lex::is_invalid_identifier(named_object->name()))
3275 go_error_at(var->location(), "%qs declared and not used",
3276 named_object->message_name().c_str());
3278 return TRAVERSE_CONTINUE;
3281 // Check that a constant initializer has the right type.
3284 Check_types_traverse::constant(Named_object* named_object, bool)
3286 Named_constant* constant = named_object->const_value();
3287 Type* ctype = constant->type();
3288 if (ctype->integer_type() == NULL
3289 && ctype->float_type() == NULL
3290 && ctype->complex_type() == NULL
3291 && !ctype->is_boolean_type()
3292 && !ctype->is_string_type())
3294 if (ctype->is_nil_type())
3295 go_error_at(constant->location(), "const initializer cannot be nil");
3296 else if (!ctype->is_error())
3297 go_error_at(constant->location(), "invalid constant type");
3298 constant->set_error();
3300 else if (!constant->expr()->is_constant())
3302 go_error_at(constant->expr()->location(), "expression is not constant");
3303 constant->set_error();
3305 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3308 go_error_at(constant->location(),
3309 "initialization expression has wrong type");
3310 constant->set_error();
3312 return TRAVERSE_CONTINUE;
3315 // There are no types to check in a function, but this is where we
3316 // issue warnings about labels which are defined but not referenced.
3319 Check_types_traverse::function(Named_object* no)
3321 no->func_value()->check_labels();
3322 return TRAVERSE_CONTINUE;
3325 // Check that types are valid in a statement.
3328 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3330 s->check_types(this->gogo_);
3331 return TRAVERSE_CONTINUE;
3334 // Check that types are valid in an expression.
3337 Check_types_traverse::expression(Expression** expr)
3339 (*expr)->check_types(this->gogo_);
3340 return TRAVERSE_CONTINUE;
3343 // Check that types are valid.
3348 Check_types_traverse traverse(this);
3349 this->traverse(&traverse);
3351 Bindings* bindings = this->current_bindings();
3352 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3353 p != bindings->end_declarations();
3356 // Also check the types in a function declaration's signature.
3357 Named_object* no = p->second;
3358 if (no->is_function_declaration())
3359 no->func_declaration_value()->check_types();
3363 // Check the types in a single block.
3366 Gogo::check_types_in_block(Block* block)
3368 Check_types_traverse traverse(this);
3369 block->traverse(&traverse);
3372 // A traversal class used to find a single shortcut operator within an
3375 class Find_shortcut : public Traverse
3379 : Traverse(traverse_blocks
3380 | traverse_statements
3381 | traverse_expressions),
3385 // A pointer to the expression which was found, or NULL if none was
3389 { return this->found_; }
3394 { return TRAVERSE_SKIP_COMPONENTS; }
3397 statement(Block*, size_t*, Statement*)
3398 { return TRAVERSE_SKIP_COMPONENTS; }
3401 expression(Expression**);
3404 Expression** found_;
3407 // Find a shortcut expression.
3410 Find_shortcut::expression(Expression** pexpr)
3412 Expression* expr = *pexpr;
3413 Binary_expression* be = expr->binary_expression();
3415 return TRAVERSE_CONTINUE;
3416 Operator op = be->op();
3417 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3418 return TRAVERSE_CONTINUE;
3419 go_assert(this->found_ == NULL);
3420 this->found_ = pexpr;
3421 return TRAVERSE_EXIT;
3424 // A traversal class used to turn shortcut operators into explicit if
3427 class Shortcuts : public Traverse
3430 Shortcuts(Gogo* gogo)
3431 : Traverse(traverse_variables
3432 | traverse_statements),
3438 variable(Named_object*);
3441 statement(Block*, size_t*, Statement*);
3444 // Convert a shortcut operator.
3446 convert_shortcut(Block* enclosing, Expression** pshortcut);
3452 // Remove shortcut operators in a single statement.
3455 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3457 // FIXME: This approach doesn't work for switch statements, because
3458 // we add the new statements before the whole switch when we need to
3459 // instead add them just before the switch expression. The right
3460 // fix is probably to lower switch statements with nonconstant cases
3461 // to a series of conditionals.
3462 if (s->switch_statement() != NULL)
3463 return TRAVERSE_CONTINUE;
3467 Find_shortcut find_shortcut;
3469 // If S is a variable declaration, then ordinary traversal won't
3470 // do anything. We want to explicitly traverse the
3471 // initialization expression if there is one.
3472 Variable_declaration_statement* vds = s->variable_declaration_statement();
3473 Expression* init = NULL;
3475 s->traverse_contents(&find_shortcut);
3478 init = vds->var()->var_value()->init();
3480 return TRAVERSE_CONTINUE;
3481 init->traverse(&init, &find_shortcut);
3483 Expression** pshortcut = find_shortcut.found();
3484 if (pshortcut == NULL)
3485 return TRAVERSE_CONTINUE;
3487 Statement* snew = this->convert_shortcut(block, pshortcut);
3488 block->insert_statement_before(*pindex, snew);
3491 if (pshortcut == &init)
3492 vds->var()->var_value()->set_init(init);
3496 // Remove shortcut operators in the initializer of a global variable.
3499 Shortcuts::variable(Named_object* no)
3501 if (no->is_result_variable())
3502 return TRAVERSE_CONTINUE;
3503 Variable* var = no->var_value();
3504 Expression* init = var->init();
3505 if (!var->is_global() || init == NULL)
3506 return TRAVERSE_CONTINUE;
3510 Find_shortcut find_shortcut;
3511 init->traverse(&init, &find_shortcut);
3512 Expression** pshortcut = find_shortcut.found();
3513 if (pshortcut == NULL)
3514 return TRAVERSE_CONTINUE;
3516 Statement* snew = this->convert_shortcut(NULL, pshortcut);
3517 var->add_preinit_statement(this->gogo_, snew);
3518 if (pshortcut == &init)
3519 var->set_init(init);
3523 // Given an expression which uses a shortcut operator, return a
3524 // statement which implements it, and update *PSHORTCUT accordingly.
3527 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3529 Binary_expression* shortcut = (*pshortcut)->binary_expression();
3530 Expression* left = shortcut->left();
3531 Expression* right = shortcut->right();
3532 Location loc = shortcut->location();
3534 Block* retblock = new Block(enclosing, loc);
3535 retblock->set_end_location(loc);
3537 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3539 retblock->add_statement(ts);
3541 Block* block = new Block(retblock, loc);
3542 block->set_end_location(loc);
3543 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
3544 Statement* assign = Statement::make_assignment(tmpref, right, loc);
3545 block->add_statement(assign);
3547 Expression* cond = Expression::make_temporary_reference(ts, loc);
3548 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
3549 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3551 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
3553 retblock->add_statement(if_statement);
3555 *pshortcut = Expression::make_temporary_reference(ts, loc);
3559 // Now convert any shortcut operators in LEFT and RIGHT.
3560 Shortcuts shortcuts(this->gogo_);
3561 retblock->traverse(&shortcuts);
3563 return Statement::make_block_statement(retblock, loc);
3566 // Turn shortcut operators into explicit if statements. Doing this
3567 // considerably simplifies the order of evaluation rules.
3570 Gogo::remove_shortcuts()
3572 Shortcuts shortcuts(this);
3573 this->traverse(&shortcuts);
3576 // A traversal class which finds all the expressions which must be
3577 // evaluated in order within a statement or larger expression. This
3578 // is used to implement the rules about order of evaluation.
3580 class Find_eval_ordering : public Traverse
3583 typedef std::vector<Expression**> Expression_pointers;
3586 Find_eval_ordering()
3587 : Traverse(traverse_blocks
3588 | traverse_statements
3589 | traverse_expressions),
3595 { return this->exprs_.size(); }
3597 typedef Expression_pointers::const_iterator const_iterator;
3601 { return this->exprs_.begin(); }
3605 { return this->exprs_.end(); }
3610 { return TRAVERSE_SKIP_COMPONENTS; }
3613 statement(Block*, size_t*, Statement*)
3614 { return TRAVERSE_SKIP_COMPONENTS; }
3617 expression(Expression**);
3620 // A list of pointers to expressions with side-effects.
3621 Expression_pointers exprs_;
3624 // If an expression must be evaluated in order, put it on the list.
3627 Find_eval_ordering::expression(Expression** expression_pointer)
3629 // We have to look at subexpressions before this one.
3630 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3631 return TRAVERSE_EXIT;
3632 if ((*expression_pointer)->must_eval_in_order())
3633 this->exprs_.push_back(expression_pointer);
3634 return TRAVERSE_SKIP_COMPONENTS;
3637 // A traversal class for ordering evaluations.
3639 class Order_eval : public Traverse
3642 Order_eval(Gogo* gogo)
3643 : Traverse(traverse_variables
3644 | traverse_statements),
3649 variable(Named_object*);
3652 statement(Block*, size_t*, Statement*);
3659 // Implement the order of evaluation rules for a statement.
3662 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3664 // FIXME: This approach doesn't work for switch statements, because
3665 // we add the new statements before the whole switch when we need to
3666 // instead add them just before the switch expression. The right
3667 // fix is probably to lower switch statements with nonconstant cases
3668 // to a series of conditionals.
3669 if (stmt->switch_statement() != NULL)
3670 return TRAVERSE_CONTINUE;
3672 Find_eval_ordering find_eval_ordering;
3674 // If S is a variable declaration, then ordinary traversal won't do
3675 // anything. We want to explicitly traverse the initialization
3676 // expression if there is one.
3677 Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3678 Expression* init = NULL;
3679 Expression* orig_init = NULL;
3681 stmt->traverse_contents(&find_eval_ordering);
3684 init = vds->var()->var_value()->init();
3686 return TRAVERSE_CONTINUE;
3689 // It might seem that this could be
3690 // init->traverse_subexpressions. Unfortunately that can fail
3693 // newvar, err := call(arg())
3694 // Here newvar will have an init of call result 0 of
3695 // call(arg()). If we only traverse subexpressions, we will
3696 // only find arg(), and we won't bother to move anything out.
3697 // Then we get to the assignment to err, we will traverse the
3698 // whole statement, and this time we will find both call() and
3699 // arg(), and so we will move them out. This will cause them to
3700 // be put into temporary variables before the assignment to err
3701 // but after the declaration of newvar. To avoid that problem,
3702 // we traverse the entire expression here.
3703 Expression::traverse(&init, &find_eval_ordering);
3706 size_t c = find_eval_ordering.size();
3708 return TRAVERSE_CONTINUE;
3710 // If there is only one expression with a side-effect, we can
3711 // usually leave it in place.
3714 switch (stmt->classification())
3716 case Statement::STATEMENT_ASSIGNMENT:
3717 // For an assignment statement, we need to evaluate an
3718 // expression on the right hand side before we evaluate any
3719 // index expression on the left hand side, so for that case
3720 // we always move the expression. Otherwise we mishandle
3721 // m[0] = len(m) where m is a map.
3724 case Statement::STATEMENT_EXPRESSION:
3726 // If this is a call statement that doesn't return any
3727 // values, it will not have been counted as a value to
3728 // move. We need to move any subexpressions in case they
3729 // are themselves call statements that require passing a
3731 Expression* expr = stmt->expression_statement()->expr();
3732 if (expr->call_expression() != NULL
3733 && expr->call_expression()->result_count() == 0)
3735 return TRAVERSE_CONTINUE;
3739 // We can leave the expression in place.
3740 return TRAVERSE_CONTINUE;
3744 bool is_thunk = stmt->thunk_statement() != NULL;
3745 Expression_statement* es = stmt->expression_statement();
3746 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3747 p != find_eval_ordering.end();
3750 Expression** pexpr = *p;
3752 // The last expression in a thunk will be the call passed to go
3753 // or defer, which we must not evaluate early.
3754 if (is_thunk && p + 1 == find_eval_ordering.end())
3757 Location loc = (*pexpr)->location();
3759 if ((*pexpr)->call_expression() == NULL
3760 || (*pexpr)->call_expression()->result_count() < 2)
3762 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3765 *pexpr = Expression::make_temporary_reference(ts, loc);
3769 // A call expression which returns multiple results needs to
3770 // be handled specially. We can't create a temporary
3771 // because there is no type to give it. Any actual uses of
3772 // the values will be done via Call_result_expressions.
3774 // Since a given call expression can be shared by multiple
3775 // Call_result_expressions, avoid hoisting the call the
3776 // second time we see it here. In addition, don't try to
3777 // hoist the top-level multi-return call in the statement,
3778 // since doing this would result a tree with more than one copy
3780 if (this->remember_expression(*pexpr))
3782 else if (es != NULL && *pexpr == es->expr())
3785 s = Statement::make_statement(*pexpr, true);
3790 block->insert_statement_before(*pindex, s);
3795 if (init != orig_init)
3796 vds->var()->var_value()->set_init(init);
3798 return TRAVERSE_CONTINUE;
3801 // Implement the order of evaluation rules for the initializer of a
3805 Order_eval::variable(Named_object* no)
3807 if (no->is_result_variable())
3808 return TRAVERSE_CONTINUE;
3809 Variable* var = no->var_value();
3810 Expression* init = var->init();
3811 if (!var->is_global() || init == NULL)
3812 return TRAVERSE_CONTINUE;
3814 Find_eval_ordering find_eval_ordering;
3815 Expression::traverse(&init, &find_eval_ordering);
3817 if (find_eval_ordering.size() <= 1)
3819 // If there is only one expression with a side-effect, we can
3820 // leave it in place.
3821 return TRAVERSE_SKIP_COMPONENTS;
3824 Expression* orig_init = init;
3826 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3827 p != find_eval_ordering.end();
3830 Expression** pexpr = *p;
3831 Location loc = (*pexpr)->location();
3833 if ((*pexpr)->call_expression() == NULL
3834 || (*pexpr)->call_expression()->result_count() < 2)
3836 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3839 *pexpr = Expression::make_temporary_reference(ts, loc);
3843 // A call expression which returns multiple results needs to
3844 // be handled specially.
3845 s = Statement::make_statement(*pexpr, true);
3847 var->add_preinit_statement(this->gogo_, s);
3850 if (init != orig_init)
3851 var->set_init(init);
3853 return TRAVERSE_SKIP_COMPONENTS;
3856 // Use temporary variables to implement the order of evaluation rules.
3859 Gogo::order_evaluations()
3861 Order_eval order_eval(this);
3862 this->traverse(&order_eval);
3865 // Traversal to flatten parse tree after order of evaluation rules are applied.
3867 class Flatten : public Traverse
3870 Flatten(Gogo* gogo, Named_object* function)
3871 : Traverse(traverse_variables
3872 | traverse_functions
3873 | traverse_statements
3874 | traverse_expressions),
3875 gogo_(gogo), function_(function), inserter_()
3879 set_inserter(const Statement_inserter* inserter)
3880 { this->inserter_ = *inserter; }
3883 variable(Named_object*);
3886 function(Named_object*);
3889 statement(Block*, size_t* pindex, Statement*);
3892 expression(Expression**);
3897 // The function we are traversing.
3898 Named_object* function_;
3899 // Current statement inserter for use by expressions.
3900 Statement_inserter inserter_;
3903 // Flatten variables.
3906 Flatten::variable(Named_object* no)
3908 if (!no->is_variable())
3909 return TRAVERSE_CONTINUE;
3911 if (no->is_variable() && no->var_value()->is_global())
3913 // Global variables can have loops in their initialization
3914 // expressions. This is handled in flatten_init_expression.
3915 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
3917 return TRAVERSE_CONTINUE;
3920 go_assert(!no->var_value()->has_pre_init());
3922 return TRAVERSE_SKIP_COMPONENTS;
3925 // Flatten the body of a function. Record the function while flattening it,
3926 // so that we can pass it down when flattening an expression.
3929 Flatten::function(Named_object* no)
3931 go_assert(this->function_ == NULL);
3932 this->function_ = no;
3933 int t = no->func_value()->traverse(this);
3934 this->function_ = NULL;
3936 if (t == TRAVERSE_EXIT)
3938 return TRAVERSE_SKIP_COMPONENTS;
3941 // Flatten statement parse trees.
3944 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
3946 // Because we explicitly traverse the statement's contents
3947 // ourselves, we want to skip block statements here. There is
3948 // nothing to flatten in a block statement.
3949 if (sorig->is_block_statement())
3950 return TRAVERSE_CONTINUE;
3952 Statement_inserter hold_inserter(this->inserter_);
3953 this->inserter_ = Statement_inserter(block, pindex);
3955 // Flatten the expressions first.
3956 int t = sorig->traverse_contents(this);
3957 if (t == TRAVERSE_EXIT)
3959 this->inserter_ = hold_inserter;
3963 // Keep flattening until nothing changes.
3964 Statement* s = sorig;
3967 Statement* snew = s->flatten(this->gogo_, this->function_, block,
3972 t = s->traverse_contents(this);
3973 if (t == TRAVERSE_EXIT)
3975 this->inserter_ = hold_inserter;
3981 block->replace_statement(*pindex, s);
3983 this->inserter_ = hold_inserter;
3984 return TRAVERSE_SKIP_COMPONENTS;
3987 // Flatten expression parse trees.
3990 Flatten::expression(Expression** pexpr)
3992 // Keep flattening until nothing changes.
3995 Expression* e = *pexpr;
3996 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
3997 return TRAVERSE_EXIT;
3999 Expression* enew = e->flatten(this->gogo_, this->function_,
4005 return TRAVERSE_SKIP_COMPONENTS;
4011 Gogo::flatten_block(Named_object* function, Block* block)
4013 Flatten flatten(this, function);
4014 block->traverse(&flatten);
4017 // Flatten an expression. INSERTER may be NULL, in which case the
4018 // expression had better not need to create any temporaries.
4021 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
4024 Flatten flatten(this, function);
4025 if (inserter != NULL)
4026 flatten.set_inserter(inserter);
4027 flatten.expression(pexpr);
4033 Flatten flatten(this, NULL);
4034 this->traverse(&flatten);
4037 // Traversal to convert calls to the predeclared recover function to
4038 // pass in an argument indicating whether it can recover from a panic
4041 class Convert_recover : public Traverse
4044 Convert_recover(Named_object* arg)
4045 : Traverse(traverse_expressions),
4051 expression(Expression**);
4054 // The argument to pass to the function.
4058 // Convert calls to recover.
4061 Convert_recover::expression(Expression** pp)
4063 Call_expression* ce = (*pp)->call_expression();
4064 if (ce != NULL && ce->is_recover_call())
4065 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4067 return TRAVERSE_CONTINUE;
4070 // Traversal for build_recover_thunks.
4072 class Build_recover_thunks : public Traverse
4075 Build_recover_thunks(Gogo* gogo)
4076 : Traverse(traverse_functions),
4081 function(Named_object*);
4085 can_recover_arg(Location);
4091 // If this function calls recover, turn it into a thunk.
4094 Build_recover_thunks::function(Named_object* orig_no)
4096 Function* orig_func = orig_no->func_value();
4097 if (!orig_func->calls_recover()
4098 || orig_func->is_recover_thunk()
4099 || orig_func->has_recover_thunk())
4100 return TRAVERSE_CONTINUE;
4102 Gogo* gogo = this->gogo_;
4103 Location location = orig_func->location();
4108 Function_type* orig_fntype = orig_func->type();
4109 Typed_identifier_list* new_params = new Typed_identifier_list();
4110 std::string receiver_name;
4111 if (orig_fntype->is_method())
4113 const Typed_identifier* receiver = orig_fntype->receiver();
4114 snprintf(buf, sizeof buf, "rt.%u", count);
4116 receiver_name = buf;
4117 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4118 receiver->location()));
4120 const Typed_identifier_list* orig_params = orig_fntype->parameters();
4121 if (orig_params != NULL && !orig_params->empty())
4123 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4124 p != orig_params->end();
4127 snprintf(buf, sizeof buf, "pt.%u", count);
4129 new_params->push_back(Typed_identifier(buf, p->type(),
4133 snprintf(buf, sizeof buf, "pr.%u", count);
4135 std::string can_recover_name = buf;
4136 new_params->push_back(Typed_identifier(can_recover_name,
4137 Type::lookup_bool_type(),
4138 orig_fntype->location()));
4140 const Typed_identifier_list* orig_results = orig_fntype->results();
4141 Typed_identifier_list* new_results;
4142 if (orig_results == NULL || orig_results->empty())
4146 new_results = new Typed_identifier_list();
4147 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4148 p != orig_results->end();
4150 new_results->push_back(Typed_identifier("", p->type(), p->location()));
4153 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4155 orig_fntype->location());
4156 if (orig_fntype->is_varargs())
4157 new_fntype->set_is_varargs();
4159 std::string name = orig_no->name();
4160 if (orig_fntype->is_method())
4161 name += "$" + orig_fntype->receiver()->type()->mangled_name(gogo);
4163 Named_object *new_no = gogo->start_function(name, new_fntype, false,
4165 Function *new_func = new_no->func_value();
4166 if (orig_func->enclosing() != NULL)
4167 new_func->set_enclosing(orig_func->enclosing());
4169 // We build the code for the original function attached to the new
4170 // function, and then swap the original and new function bodies.
4171 // This means that existing references to the original function will
4172 // then refer to the new function. That makes this code a little
4173 // confusing, in that the reference to NEW_NO really refers to the
4174 // other function, not the one we are building.
4176 Expression* closure = NULL;
4177 if (orig_func->needs_closure())
4179 // For the new function we are creating, declare a new parameter
4180 // variable NEW_CLOSURE_NO and set it to be the closure variable
4181 // of the function. This will be set to the closure value
4182 // passed in by the caller. Then pass a reference to this
4183 // variable as the closure value when calling the original
4184 // function. In other words, simply pass the closure value
4185 // through the thunk we are creating.
4186 Named_object* orig_closure_no = orig_func->closure_var();
4187 Variable* orig_closure_var = orig_closure_no->var_value();
4188 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4189 false, false, location);
4190 new_var->set_is_closure();
4191 snprintf(buf, sizeof buf, "closure.%u", count);
4193 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4195 new_func->set_closure_var(new_closure_no);
4196 closure = Expression::make_var_reference(new_closure_no, location);
4199 Expression* fn = Expression::make_func_reference(new_no, closure, location);
4201 Expression_list* args = new Expression_list();
4202 if (new_params != NULL)
4204 // Note that we skip the last parameter, which is the boolean
4205 // indicating whether recover can succed.
4206 for (Typed_identifier_list::const_iterator p = new_params->begin();
4207 p + 1 != new_params->end();
4210 Named_object* p_no = gogo->lookup(p->name(), NULL);
4211 go_assert(p_no != NULL
4212 && p_no->is_variable()
4213 && p_no->var_value()->is_parameter());
4214 args->push_back(Expression::make_var_reference(p_no, location));
4217 args->push_back(this->can_recover_arg(location));
4219 gogo->start_block(location);
4221 Call_expression* call = Expression::make_call(fn, args, false, location);
4223 // Any varargs call has already been lowered.
4224 call->set_varargs_are_lowered();
4226 Statement* s = Statement::make_return_from_call(call, location);
4227 s->determine_types();
4228 gogo->add_statement(s);
4230 Block* b = gogo->finish_block(location);
4232 gogo->add_block(b, location);
4234 // Lower the call in case it returns multiple results.
4235 gogo->lower_block(new_no, b);
4237 gogo->finish_function(location);
4239 // Swap the function bodies and types.
4240 new_func->swap_for_recover(orig_func);
4241 orig_func->set_is_recover_thunk();
4242 new_func->set_calls_recover();
4243 new_func->set_has_recover_thunk();
4245 Bindings* orig_bindings = orig_func->block()->bindings();
4246 Bindings* new_bindings = new_func->block()->bindings();
4247 if (orig_fntype->is_method())
4249 // We changed the receiver to be a regular parameter. We have
4250 // to update the binding accordingly in both functions.
4251 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4252 go_assert(orig_rec_no != NULL
4253 && orig_rec_no->is_variable()
4254 && !orig_rec_no->var_value()->is_receiver());
4255 orig_rec_no->var_value()->set_is_receiver();
4257 std::string new_receiver_name(orig_fntype->receiver()->name());
4258 if (new_receiver_name.empty())
4260 // Find the receiver. It was named "r.NNN" in
4261 // Gogo::start_function.
4262 for (Bindings::const_definitions_iterator p =
4263 new_bindings->begin_definitions();
4264 p != new_bindings->end_definitions();
4267 const std::string& pname((*p)->name());
4268 if (pname[0] == 'r' && pname[1] == '.')
4270 new_receiver_name = pname;
4274 go_assert(!new_receiver_name.empty());
4276 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4277 if (new_rec_no == NULL)
4278 go_assert(saw_errors());
4281 go_assert(new_rec_no->is_variable()
4282 && new_rec_no->var_value()->is_receiver());
4283 new_rec_no->var_value()->set_is_not_receiver();
4287 // Because we flipped blocks but not types, the can_recover
4288 // parameter appears in the (now) old bindings as a parameter.
4289 // Change it to a local variable, whereupon it will be discarded.
4290 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4291 go_assert(can_recover_no != NULL
4292 && can_recover_no->is_variable()
4293 && can_recover_no->var_value()->is_parameter());
4294 orig_bindings->remove_binding(can_recover_no);
4296 // Add the can_recover argument to the (now) new bindings, and
4297 // attach it to any recover statements.
4298 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4299 false, true, false, location);
4300 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4302 Convert_recover convert_recover(can_recover_no);
4303 new_func->traverse(&convert_recover);
4305 // Update the function pointers in any named results.
4306 new_func->update_result_variables();
4307 orig_func->update_result_variables();
4309 return TRAVERSE_CONTINUE;
4312 // Return the expression to pass for the .can_recover parameter to the
4313 // new function. This indicates whether a call to recover may return
4314 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4317 Build_recover_thunks::can_recover_arg(Location location)
4319 static Named_object* builtin_return_address;
4320 if (builtin_return_address == NULL)
4321 builtin_return_address =
4322 Gogo::declare_builtin_rf_address("__builtin_return_address");
4324 static Named_object* can_recover;
4325 if (can_recover == NULL)
4327 const Location bloc = Linemap::predeclared_location();
4328 Typed_identifier_list* param_types = new Typed_identifier_list();
4329 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4330 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
4331 Type* boolean_type = Type::lookup_bool_type();
4332 Typed_identifier_list* results = new Typed_identifier_list();
4333 results->push_back(Typed_identifier("", boolean_type, bloc));
4334 Function_type* fntype = Type::make_function_type(NULL, param_types,
4337 Named_object::make_function_declaration("runtime_canrecover",
4338 NULL, fntype, bloc);
4339 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4342 Expression* fn = Expression::make_func_reference(builtin_return_address,
4345 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4346 Expression_list *args = new Expression_list();
4347 args->push_back(zexpr);
4349 Expression* call = Expression::make_call(fn, args, false, location);
4351 args = new Expression_list();
4352 args->push_back(call);
4354 fn = Expression::make_func_reference(can_recover, NULL, location);
4355 return Expression::make_call(fn, args, false, location);
4358 // Build thunks for functions which call recover. We build a new
4359 // function with an extra parameter, which is whether a call to
4360 // recover can succeed. We then move the body of this function to
4361 // that one. We then turn this function into a thunk which calls the
4362 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4363 // The function will be marked as not splitting the stack. This will
4364 // cooperate with the implementation of defer to make recover do the
4368 Gogo::build_recover_thunks()
4370 Build_recover_thunks build_recover_thunks(this);
4371 this->traverse(&build_recover_thunks);
4374 // Return a declaration for __builtin_return_address or
4375 // __builtin_frame_address.
4378 Gogo::declare_builtin_rf_address(const char* name)
4380 const Location bloc = Linemap::predeclared_location();
4382 Typed_identifier_list* param_types = new Typed_identifier_list();
4383 Type* uint32_type = Type::lookup_integer_type("uint32");
4384 param_types->push_back(Typed_identifier("l", uint32_type, bloc));
4386 Typed_identifier_list* return_types = new Typed_identifier_list();
4387 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4388 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4390 Function_type* fntype = Type::make_function_type(NULL, param_types,
4391 return_types, bloc);
4392 Named_object* ret = Named_object::make_function_declaration(name, NULL,
4394 ret->func_declaration_value()->set_asm_name(name);
4398 // Build a call to the runtime error function.
4401 Gogo::runtime_error(int code, Location location)
4403 Type* int32_type = Type::lookup_integer_type("int32");
4404 Expression* code_expr = Expression::make_integer_ul(code, int32_type,
4406 return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4409 // Look for named types to see whether we need to create an interface
4412 class Build_method_tables : public Traverse
4415 Build_method_tables(Gogo* gogo,
4416 const std::vector<Interface_type*>& interfaces)
4417 : Traverse(traverse_types),
4418 gogo_(gogo), interfaces_(interfaces)
4427 // A list of locally defined interfaces which have hidden methods.
4428 const std::vector<Interface_type*>& interfaces_;
4431 // Build all required interface method tables for types. We need to
4432 // ensure that we have an interface method table for every interface
4433 // which has a hidden method, for every named type which implements
4434 // that interface. Normally we can just build interface method tables
4435 // as we need them. However, in some cases we can require an
4436 // interface method table for an interface defined in a different
4437 // package for a type defined in that package. If that interface and
4438 // type both use a hidden method, that is OK. However, we will not be
4439 // able to build that interface method table when we need it, because
4440 // the type's hidden method will be static. So we have to build it
4441 // here, and just refer it from other packages as needed.
4444 Gogo::build_interface_method_tables()
4449 std::vector<Interface_type*> hidden_interfaces;
4450 hidden_interfaces.reserve(this->interface_types_.size());
4451 for (std::vector<Interface_type*>::const_iterator pi =
4452 this->interface_types_.begin();
4453 pi != this->interface_types_.end();
4456 const Typed_identifier_list* methods = (*pi)->methods();
4457 if (methods == NULL)
4459 for (Typed_identifier_list::const_iterator pm = methods->begin();
4460 pm != methods->end();
4463 if (Gogo::is_hidden_name(pm->name()))
4465 hidden_interfaces.push_back(*pi);
4471 if (!hidden_interfaces.empty())
4473 // Now traverse the tree looking for all named types.
4474 Build_method_tables bmt(this, hidden_interfaces);
4475 this->traverse(&bmt);
4478 // We no longer need the list of interfaces.
4480 this->interface_types_.clear();
4483 // This is called for each type. For a named type, for each of the
4484 // interfaces with hidden methods that it implements, create the
4488 Build_method_tables::type(Type* type)
4490 Named_type* nt = type->named_type();
4491 Struct_type* st = type->struct_type();
4492 if (nt != NULL || st != NULL)
4494 Translate_context context(this->gogo_, NULL, NULL, NULL);
4495 for (std::vector<Interface_type*>::const_iterator p =
4496 this->interfaces_.begin();
4497 p != this->interfaces_.end();
4500 // We ask whether a pointer to the named type implements the
4501 // interface, because a pointer can implement more methods
4505 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4508 nt->interface_method_table(*p, false)->get_backend(&context);
4509 nt->interface_method_table(*p, true)->get_backend(&context);
4514 if ((*p)->implements_interface(Type::make_pointer_type(st),
4517 st->interface_method_table(*p, false)->get_backend(&context);
4518 st->interface_method_table(*p, true)->get_backend(&context);
4523 return TRAVERSE_CONTINUE;
4526 // Return an expression which allocates memory to hold values of type TYPE.
4529 Gogo::allocate_memory(Type* type, Location location)
4531 Expression* td = Expression::make_type_descriptor(type, location);
4532 return Runtime::make_call(Runtime::NEW, location, 1, td);
4535 // Traversal class used to check for return statements.
4537 class Check_return_statements_traverse : public Traverse
4540 Check_return_statements_traverse()
4541 : Traverse(traverse_functions)
4545 function(Named_object*);
4548 // Check that a function has a return statement if it needs one.
4551 Check_return_statements_traverse::function(Named_object* no)
4553 Function* func = no->func_value();
4554 const Function_type* fntype = func->type();
4555 const Typed_identifier_list* results = fntype->results();
4557 // We only need a return statement if there is a return value.
4558 if (results == NULL || results->empty())
4559 return TRAVERSE_CONTINUE;
4561 if (func->block()->may_fall_through())
4562 go_error_at(func->block()->end_location(),
4563 "missing return at end of function");
4565 return TRAVERSE_CONTINUE;
4568 // Check return statements.
4571 Gogo::check_return_statements()
4573 Check_return_statements_traverse traverse;
4574 this->traverse(&traverse);
4577 // Export identifiers as requested.
4582 // For now we always stream to a section. Later we may want to
4583 // support streaming to a separate file.
4584 Stream_to_section stream(this->backend());
4586 // Write out either the prefix or pkgpath depending on how we were
4589 std::string pkgpath;
4590 if (this->pkgpath_from_option_)
4591 pkgpath = this->pkgpath_;
4592 else if (this->prefix_from_option_)
4593 prefix = this->prefix_;
4594 else if (this->is_main_package())
4599 Export exp(&stream);
4600 exp.register_builtin_types(this);
4601 exp.export_globals(this->package_name(),
4606 (this->need_init_fn_ && !this->is_main_package()
4607 ? this->get_init_fn_name()
4609 this->imported_init_fns_,
4610 this->package_->bindings());
4612 if (!this->c_header_.empty() && !saw_errors())
4613 this->write_c_header();
4616 // Write the top level named struct types in C format to a C header
4617 // file. This is used when building the runtime package, to share
4618 // struct definitions between C and Go.
4621 Gogo::write_c_header()
4624 out.open(this->c_header_.c_str());
4627 go_error_at(Linemap::unknown_location(),
4628 "cannot open %s: %m", this->c_header_.c_str());
4632 std::list<Named_object*> types;
4633 Bindings* top = this->package_->bindings();
4634 for (Bindings::const_definitions_iterator p = top->begin_definitions();
4635 p != top->end_definitions();
4638 Named_object* no = *p;
4640 // Skip names that start with underscore followed by something
4641 // other than an uppercase letter, as when compiling the runtime
4642 // package they are mostly types defined by mkrsysinfo.sh based
4643 // on the C system header files. We don't need to translate
4644 // types to C and back to Go. But do accept the special cases
4645 // _defer and _panic.
4646 std::string name = Gogo::unpack_hidden_name(no->name());
4648 && (name[1] < 'A' || name[1] > 'Z')
4649 && (name != "_defer" && name != "_panic"))
4652 if (no->is_type() && no->type_value()->struct_type() != NULL)
4653 types.push_back(no);
4654 if (no->is_const() && no->const_value()->type()->integer_type() != NULL)
4656 Numeric_constant nc;
4658 if (no->const_value()->expr()->numeric_constant_value(&nc)
4659 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
4661 out << "#define " << no->message_name() << ' ' << val
4667 std::vector<const Named_object*> written;
4669 while (!types.empty())
4671 Named_object* no = types.front();
4674 std::vector<const Named_object*> requires;
4675 std::vector<const Named_object*> declare;
4676 if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
4681 for (std::vector<const Named_object*>::const_iterator pr
4683 pr != requires.end() && ok;
4686 for (std::list<Named_object*>::const_iterator pt = types.begin();
4687 pt != types.end() && ok;
4697 // This should be impossible since the code parsed and
4702 types.push_back(no);
4706 for (std::vector<const Named_object*>::const_iterator pd
4708 pd != declare.end();
4714 std::vector<const Named_object*> drequires;
4715 std::vector<const Named_object*> ddeclare;
4716 if (!(*pd)->type_value()->struct_type()->
4717 can_write_to_c_header(&drequires, &ddeclare))
4721 for (std::vector<const Named_object*>::const_iterator pw
4723 pw != written.end();
4735 out << "struct " << (*pd)->message_name() << ";" << std::endl;
4736 written.push_back(*pd);
4741 out << "struct " << no->message_name() << " {" << std::endl;
4742 no->type_value()->struct_type()->write_to_c_header(out);
4743 out << "};" << std::endl;
4744 written.push_back(no);
4749 go_error_at(Linemap::unknown_location(),
4750 "error writing to %s: %m", this->c_header_.c_str());
4753 // Find the blocks in order to convert named types defined in blocks.
4755 class Convert_named_types : public Traverse
4758 Convert_named_types(Gogo* gogo)
4759 : Traverse(traverse_blocks),
4765 block(Block* block);
4772 Convert_named_types::block(Block* block)
4774 this->gogo_->convert_named_types_in_bindings(block->bindings());
4775 return TRAVERSE_CONTINUE;
4778 // Convert all named types to the backend representation. Since named
4779 // types can refer to other types, this needs to be done in the right
4780 // sequence, which is handled by Named_type::convert. Here we arrange
4781 // to call that for each named type.
4784 Gogo::convert_named_types()
4786 this->convert_named_types_in_bindings(this->globals_);
4787 for (Packages::iterator p = this->packages_.begin();
4788 p != this->packages_.end();
4791 Package* package = p->second;
4792 this->convert_named_types_in_bindings(package->bindings());
4795 Convert_named_types cnt(this);
4796 this->traverse(&cnt);
4798 // Make all the builtin named types used for type descriptors, and
4799 // then convert them. They will only be written out if they are
4801 Type::make_type_descriptor_type();
4802 Type::make_type_descriptor_ptr_type();
4803 Function_type::make_function_type_descriptor_type();
4804 Pointer_type::make_pointer_type_descriptor_type();
4805 Struct_type::make_struct_type_descriptor_type();
4806 Array_type::make_array_type_descriptor_type();
4807 Array_type::make_slice_type_descriptor_type();
4808 Map_type::make_map_type_descriptor_type();
4809 Channel_type::make_chan_type_descriptor_type();
4810 Interface_type::make_interface_type_descriptor_type();
4811 Expression::make_func_descriptor_type();
4812 Type::convert_builtin_named_types(this);
4814 Runtime::convert_types(this);
4816 this->named_types_are_converted_ = true;
4819 // Convert all names types in a set of bindings.
4822 Gogo::convert_named_types_in_bindings(Bindings* bindings)
4824 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4825 p != bindings->end_definitions();
4828 if ((*p)->is_type())
4829 (*p)->type_value()->convert(this);
4835 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
4837 : type_(type), enclosing_(enclosing), results_(NULL),
4838 closure_var_(NULL), block_(block), location_(location), labels_(),
4839 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
4840 pragmas_(0), is_sink_(false), results_are_named_(false),
4841 is_unnamed_type_stub_method_(false), calls_recover_(false),
4842 is_recover_thunk_(false), has_recover_thunk_(false),
4843 calls_defer_retaddr_(false), is_type_specific_function_(false),
4844 in_unique_section_(false)
4848 // Create the named result variables.
4851 Function::create_result_variables(Gogo* gogo)
4853 const Typed_identifier_list* results = this->type_->results();
4854 if (results == NULL || results->empty())
4857 if (!results->front().name().empty())
4858 this->results_are_named_ = true;
4860 this->results_ = new Results();
4861 this->results_->reserve(results->size());
4863 Block* block = this->block_;
4865 for (Typed_identifier_list::const_iterator p = results->begin();
4866 p != results->end();
4869 std::string name = p->name();
4870 if (name.empty() || Gogo::is_sink_name(name))
4872 static int result_counter;
4874 snprintf(buf, sizeof buf, "$ret%d", result_counter);
4876 name = gogo->pack_hidden_name(buf, false);
4878 Result_variable* result = new Result_variable(p->type(), this, index,
4880 Named_object* no = block->bindings()->add_result_variable(name, result);
4881 if (no->is_result_variable())
4882 this->results_->push_back(no);
4885 static int dummy_result_count;
4887 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
4888 ++dummy_result_count;
4889 name = gogo->pack_hidden_name(buf, false);
4890 no = block->bindings()->add_result_variable(name, result);
4891 go_assert(no->is_result_variable());
4892 this->results_->push_back(no);
4897 // Update the named result variables when cloning a function which
4901 Function::update_result_variables()
4903 if (this->results_ == NULL)
4906 for (Results::iterator p = this->results_->begin();
4907 p != this->results_->end();
4909 (*p)->result_var_value()->set_function(this);
4912 // Whether this method should not be included in the type descriptor.
4915 Function::nointerface() const
4917 go_assert(this->is_method());
4918 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
4921 // Record that this method should not be included in the type
4925 Function::set_nointerface()
4927 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
4930 // Return the closure variable, creating it if necessary.
4933 Function::closure_var()
4935 if (this->closure_var_ == NULL)
4937 go_assert(this->descriptor_ == NULL);
4938 // We don't know the type of the variable yet. We add fields as
4940 Location loc = this->type_->location();
4941 Struct_field_list* sfl = new Struct_field_list;
4942 Struct_type* struct_type = Type::make_struct_type(sfl, loc);
4943 struct_type->set_is_struct_incomparable();
4944 Variable* var = new Variable(Type::make_pointer_type(struct_type),
4945 NULL, false, false, false, loc);
4947 var->set_is_closure();
4948 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
4949 // Note that the new variable is not in any binding contour.
4951 return this->closure_var_;
4954 // Set the type of the closure variable.
4957 Function::set_closure_type()
4959 if (this->closure_var_ == NULL)
4961 Named_object* closure = this->closure_var_;
4962 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
4964 // The first field of a closure is always a pointer to the function
4966 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4967 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
4970 unsigned int index = 1;
4971 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
4972 p != this->closure_fields_.end();
4975 Named_object* no = p->first;
4977 snprintf(buf, sizeof buf, "%u", index);
4978 std::string n = no->name() + buf;
4980 if (no->is_variable())
4981 var_type = no->var_value()->type();
4983 var_type = no->result_var_value()->type();
4984 Type* field_type = Type::make_pointer_type(var_type);
4985 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
4989 // Return whether this function is a method.
4992 Function::is_method() const
4994 return this->type_->is_method();
4997 // Add a label definition.
5000 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
5003 Label* lnull = NULL;
5004 std::pair<Labels::iterator, bool> ins =
5005 this->labels_.insert(std::make_pair(label_name, lnull));
5007 if (label_name == "_")
5009 label = Label::create_dummy_label();
5011 ins.first->second = label;
5013 else if (ins.second)
5015 // This is a new label.
5016 label = new Label(label_name);
5017 ins.first->second = label;
5021 // The label was already in the hash table.
5022 label = ins.first->second;
5023 if (label->is_defined())
5025 go_error_at(location, "label %qs already defined",
5026 Gogo::message_name(label_name).c_str());
5027 go_inform(label->location(), "previous definition of %qs was here",
5028 Gogo::message_name(label_name).c_str());
5029 return new Label(label_name);
5033 label->define(location, gogo->bindings_snapshot(location));
5035 // Issue any errors appropriate for any previous goto's to this
5037 const std::vector<Bindings_snapshot*>& refs(label->refs());
5038 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5041 (*p)->check_goto_to(gogo->current_block());
5042 label->clear_refs();
5047 // Add a reference to a label.
5050 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5051 Location location, bool issue_goto_errors)
5053 Label* lnull = NULL;
5054 std::pair<Labels::iterator, bool> ins =
5055 this->labels_.insert(std::make_pair(label_name, lnull));
5059 // The label was already in the hash table.
5060 label = ins.first->second;
5064 go_assert(ins.first->second == NULL);
5065 label = new Label(label_name);
5066 ins.first->second = label;
5069 label->set_is_used();
5071 if (issue_goto_errors)
5073 Bindings_snapshot* snapshot = label->snapshot();
5074 if (snapshot != NULL)
5075 snapshot->check_goto_from(gogo->current_block(), location);
5077 label->add_snapshot_ref(gogo->bindings_snapshot(location));
5083 // Warn about labels that are defined but not used.
5086 Function::check_labels() const
5088 for (Labels::const_iterator p = this->labels_.begin();
5089 p != this->labels_.end();
5092 Label* label = p->second;
5093 if (!label->is_used())
5094 go_error_at(label->location(), "label %qs defined and not used",
5095 Gogo::message_name(label->name()).c_str());
5099 // Swap one function with another. This is used when building the
5100 // thunk we use to call a function which calls recover. It may not
5101 // work for any other case.
5104 Function::swap_for_recover(Function *x)
5106 go_assert(this->enclosing_ == x->enclosing_);
5107 std::swap(this->results_, x->results_);
5108 std::swap(this->closure_var_, x->closure_var_);
5109 std::swap(this->block_, x->block_);
5110 go_assert(this->location_ == x->location_);
5111 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5112 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5115 // Traverse the tree.
5118 Function::traverse(Traverse* traverse)
5120 unsigned int traverse_mask = traverse->traverse_mask();
5123 & (Traverse::traverse_types | Traverse::traverse_expressions))
5126 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5127 return TRAVERSE_EXIT;
5130 // FIXME: We should check traverse_functions here if nested
5131 // functions are stored in block bindings.
5132 if (this->block_ != NULL
5134 & (Traverse::traverse_variables
5135 | Traverse::traverse_constants
5136 | Traverse::traverse_blocks
5137 | Traverse::traverse_statements
5138 | Traverse::traverse_expressions
5139 | Traverse::traverse_types)) != 0)
5141 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5142 return TRAVERSE_EXIT;
5145 return TRAVERSE_CONTINUE;
5148 // Work out types for unspecified variables and constants.
5151 Function::determine_types()
5153 if (this->block_ != NULL)
5154 this->block_->determine_types();
5157 // Return the function descriptor, the value you get when you refer to
5158 // the function in Go code without calling it.
5161 Function::descriptor(Gogo*, Named_object* no)
5163 go_assert(!this->is_method());
5164 go_assert(this->closure_var_ == NULL);
5165 if (this->descriptor_ == NULL)
5166 this->descriptor_ = Expression::make_func_descriptor(no);
5167 return this->descriptor_;
5170 // Get a pointer to the variable representing the defer stack for this
5171 // function, making it if necessary. The value of the variable is set
5172 // by the runtime routines to true if the function is returning,
5173 // rather than panicing through. A pointer to this variable is used
5174 // as a marker for the functions on the defer stack associated with
5175 // this function. A function-specific variable permits inlining a
5176 // function which uses defer.
5179 Function::defer_stack(Location location)
5181 if (this->defer_stack_ == NULL)
5183 Type* t = Type::lookup_bool_type();
5184 Expression* n = Expression::make_boolean(false, location);
5185 this->defer_stack_ = Statement::make_temporary(t, n, location);
5186 this->defer_stack_->set_is_address_taken();
5188 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5190 return Expression::make_unary(OPERATOR_AND, ref, location);
5193 // Export the function.
5196 Function::export_func(Export* exp, const std::string& name) const
5198 Function::export_func_with_type(exp, name, this->type_);
5201 // Export a function with a type.
5204 Function::export_func_with_type(Export* exp, const std::string& name,
5205 const Function_type* fntype)
5207 exp->write_c_string("func ");
5209 if (fntype->is_method())
5211 exp->write_c_string("(");
5212 const Typed_identifier* receiver = fntype->receiver();
5213 exp->write_name(receiver->name());
5214 exp->write_escape(receiver->note());
5215 exp->write_c_string(" ");
5216 exp->write_type(receiver->type());
5217 exp->write_c_string(") ");
5220 exp->write_string(name);
5222 exp->write_c_string(" (");
5223 const Typed_identifier_list* parameters = fntype->parameters();
5224 if (parameters != NULL)
5227 bool is_varargs = fntype->is_varargs();
5229 for (Typed_identifier_list::const_iterator p = parameters->begin();
5230 p != parameters->end();
5236 exp->write_c_string(", ");
5237 exp->write_name(p->name());
5238 exp->write_escape(p->note());
5239 exp->write_c_string(" ");
5240 if (!is_varargs || p + 1 != parameters->end())
5241 exp->write_type(p->type());
5244 exp->write_c_string("...");
5245 exp->write_type(p->type()->array_type()->element_type());
5249 exp->write_c_string(")");
5251 const Typed_identifier_list* results = fntype->results();
5252 if (results != NULL)
5254 if (results->size() == 1 && results->begin()->name().empty())
5256 exp->write_c_string(" ");
5257 exp->write_type(results->begin()->type());
5261 exp->write_c_string(" (");
5263 for (Typed_identifier_list::const_iterator p = results->begin();
5264 p != results->end();
5270 exp->write_c_string(", ");
5271 exp->write_name(p->name());
5272 exp->write_escape(p->note());
5273 exp->write_c_string(" ");
5274 exp->write_type(p->type());
5276 exp->write_c_string(")");
5279 exp->write_c_string(";\n");
5282 // Import a function.
5285 Function::import_func(Import* imp, std::string* pname,
5286 Typed_identifier** preceiver,
5287 Typed_identifier_list** pparameters,
5288 Typed_identifier_list** presults,
5291 imp->require_c_string("func ");
5294 if (imp->peek_char() == '(')
5296 imp->require_c_string("(");
5297 std::string name = imp->read_name();
5298 std::string escape_note = imp->read_escape();
5299 imp->require_c_string(" ");
5300 Type* rtype = imp->read_type();
5301 *preceiver = new Typed_identifier(name, rtype, imp->location());
5302 (*preceiver)->set_note(escape_note);
5303 imp->require_c_string(") ");
5306 *pname = imp->read_identifier();
5308 Typed_identifier_list* parameters;
5309 *is_varargs = false;
5310 imp->require_c_string(" (");
5311 if (imp->peek_char() == ')')
5315 parameters = new Typed_identifier_list();
5318 std::string name = imp->read_name();
5319 std::string escape_note = imp->read_escape();
5320 imp->require_c_string(" ");
5322 if (imp->match_c_string("..."))
5328 Type* ptype = imp->read_type();
5330 ptype = Type::make_array_type(ptype, NULL);
5331 Typed_identifier t = Typed_identifier(name, ptype, imp->location());
5332 t.set_note(escape_note);
5333 parameters->push_back(t);
5334 if (imp->peek_char() != ',')
5336 go_assert(!*is_varargs);
5337 imp->require_c_string(", ");
5340 imp->require_c_string(")");
5341 *pparameters = parameters;
5343 Typed_identifier_list* results;
5344 if (imp->peek_char() != ' ')
5348 results = new Typed_identifier_list();
5349 imp->require_c_string(" ");
5350 if (imp->peek_char() != '(')
5352 Type* rtype = imp->read_type();
5353 results->push_back(Typed_identifier("", rtype, imp->location()));
5357 imp->require_c_string("(");
5360 std::string name = imp->read_name();
5361 std::string note = imp->read_escape();
5362 imp->require_c_string(" ");
5363 Type* rtype = imp->read_type();
5364 Typed_identifier t = Typed_identifier(name, rtype,
5367 results->push_back(t);
5368 if (imp->peek_char() != ',')
5370 imp->require_c_string(", ");
5372 imp->require_c_string(")");
5375 imp->require_c_string(";\n");
5376 *presults = results;
5379 // Get the backend representation.
5382 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
5384 if (this->fndecl_ == NULL)
5386 std::string asm_name;
5387 bool is_visible = false;
5388 if (no->package() != NULL)
5390 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
5392 else if (Gogo::unpack_hidden_name(no->name()) == "init"
5393 && !this->type_->is_method())
5395 else if (no->name() == gogo->get_init_fn_name())
5398 asm_name = no->name();
5400 else if (Gogo::unpack_hidden_name(no->name()) == "main"
5401 && gogo->is_main_package())
5403 // Methods have to be public even if they are hidden because
5404 // they can be pulled into type descriptors when using
5405 // anonymous fields.
5406 else if (!Gogo::is_hidden_name(no->name())
5407 || this->type_->is_method())
5409 if (!this->is_unnamed_type_stub_method_)
5411 std::string pkgpath = gogo->pkgpath_symbol();
5412 if (this->type_->is_method()
5413 && Gogo::is_hidden_name(no->name())
5414 && Gogo::hidden_name_pkgpath(no->name()) != gogo->pkgpath())
5416 // This is a method we created for an unexported
5417 // method of an imported embedded type. We need to
5418 // use the pkgpath of the imported package to avoid
5419 // a possible name collision. See bug478 for a test
5421 pkgpath = Gogo::hidden_name_pkgpath(no->name());
5422 pkgpath = Gogo::pkgpath_for_symbol(pkgpath);
5426 asm_name.append(1, '.');
5427 asm_name.append(Gogo::unpack_hidden_name(no->name()));
5428 if (this->type_->is_method())
5430 asm_name.append(1, '.');
5431 Type* rtype = this->type_->receiver()->type();
5432 asm_name.append(rtype->mangled_name(gogo));
5436 if (!this->asm_name_.empty())
5438 asm_name = this->asm_name_;
5442 // If a function calls the predeclared recover function, we
5443 // can't inline it, because recover behaves differently in a
5444 // function passed directly to defer. If this is a recover
5445 // thunk that we built to test whether a function can be
5446 // recovered, we can't inline it, because that will mess up
5447 // our return address comparison.
5448 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
5450 // If a function calls __go_set_defer_retaddr, then mark it as
5451 // uninlinable. This prevents the GCC backend from splitting
5452 // the function; splitting the function is a bad idea because we
5453 // want the return address label to be in the same function as
5455 if (this->calls_defer_retaddr_)
5456 is_inlinable = false;
5458 // Check the //go:noinline compiler directive.
5459 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
5460 is_inlinable = false;
5462 // If this is a thunk created to call a function which calls
5463 // the predeclared recover function, we need to disable
5464 // stack splitting for the thunk.
5465 bool disable_split_stack = this->is_recover_thunk_;
5467 // Check the //go:nosplit compiler directive.
5468 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
5469 disable_split_stack = true;
5471 // Encode name if asm_name not already set at this point
5472 if (asm_name.empty() && go_id_needs_encoding(no->get_id(gogo)))
5473 asm_name = go_encode_id(no->get_id(gogo));
5475 // This should go into a unique section if that has been
5476 // requested elsewhere, or if this is a nointerface function.
5477 // We want to put a nointerface function into a unique section
5478 // because there is a good chance that the linker garbage
5479 // collection can discard it.
5480 bool in_unique_section = (this->in_unique_section_
5481 || (this->is_method() && this->nointerface()));
5483 Btype* functype = this->type_->get_backend_fntype(gogo);
5485 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5486 is_visible, false, is_inlinable,
5487 disable_split_stack, in_unique_section,
5490 return this->fndecl_;
5493 // Get the backend representation.
5496 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
5498 if (this->fndecl_ == NULL)
5500 // Let Go code use an asm declaration to pick up a builtin
5502 if (!this->asm_name_.empty())
5504 Bfunction* builtin_decl =
5505 gogo->backend()->lookup_builtin(this->asm_name_);
5506 if (builtin_decl != NULL)
5508 this->fndecl_ = builtin_decl;
5509 return this->fndecl_;
5513 std::string asm_name;
5514 if (this->asm_name_.empty())
5516 asm_name = (no->package() == NULL
5517 ? gogo->pkgpath_symbol()
5518 : no->package()->pkgpath_symbol());
5519 asm_name.append(1, '.');
5520 asm_name.append(Gogo::unpack_hidden_name(no->name()));
5521 if (this->fntype_->is_method())
5523 asm_name.append(1, '.');
5524 Type* rtype = this->fntype_->receiver()->type();
5525 asm_name.append(rtype->mangled_name(gogo));
5528 else if (go_id_needs_encoding(no->get_id(gogo)))
5529 asm_name = go_encode_id(no->get_id(gogo));
5531 Btype* functype = this->fntype_->get_backend_fntype(gogo);
5533 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5534 true, true, true, false, false,
5538 return this->fndecl_;
5541 // Build the descriptor for a function declaration. This won't
5542 // necessarily happen if the package has just a declaration for the
5543 // function and no other reference to it, but we may still need the
5544 // descriptor for references from other packages.
5546 Function_declaration::build_backend_descriptor(Gogo* gogo)
5548 if (this->descriptor_ != NULL)
5550 Translate_context context(gogo, NULL, NULL, NULL);
5551 this->descriptor_->get_backend(&context);
5555 // Check that the types used in this declaration's signature are defined.
5556 // Reports errors for any undefined type.
5559 Function_declaration::check_types() const
5561 // Calling Type::base will give errors for any undefined types.
5562 Function_type* fntype = this->type();
5563 if (fntype->receiver() != NULL)
5564 fntype->receiver()->type()->base();
5565 if (fntype->parameters() != NULL)
5567 const Typed_identifier_list* params = fntype->parameters();
5568 for (Typed_identifier_list::const_iterator p = params->begin();
5575 // Return the function's decl after it has been built.
5578 Function::get_decl() const
5580 go_assert(this->fndecl_ != NULL);
5581 return this->fndecl_;
5584 // Build the backend representation for the function code.
5587 Function::build(Gogo* gogo, Named_object* named_function)
5589 Translate_context context(gogo, named_function, NULL, NULL);
5591 // A list of parameter variables for this function.
5592 std::vector<Bvariable*> param_vars;
5594 // Variables that need to be declared for this function and their
5596 std::vector<Bvariable*> vars;
5597 std::vector<Bexpression*> var_inits;
5598 for (Bindings::const_definitions_iterator p =
5599 this->block_->bindings()->begin_definitions();
5600 p != this->block_->bindings()->end_definitions();
5603 Location loc = (*p)->location();
5604 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
5606 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5607 Bvariable* parm_bvar = bvar;
5609 // We always pass the receiver to a method as a pointer. If
5610 // the receiver is declared as a non-pointer type, then we
5611 // copy the value into a local variable.
5612 if ((*p)->var_value()->is_receiver()
5613 && (*p)->var_value()->type()->points_to() == NULL)
5615 std::string name = (*p)->name() + ".pointer";
5616 Type* var_type = (*p)->var_value()->type();
5617 Variable* parm_var =
5618 new Variable(Type::make_pointer_type(var_type), NULL, false,
5620 Named_object* parm_no =
5621 Named_object::make_variable(name, NULL, parm_var);
5622 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5624 vars.push_back(bvar);
5625 Expression* parm_ref =
5626 Expression::make_var_reference(parm_no, loc);
5627 parm_ref = Expression::make_unary(OPERATOR_MULT, parm_ref, loc);
5628 if ((*p)->var_value()->is_in_heap())
5629 parm_ref = Expression::make_heap_expression(parm_ref, loc);
5630 var_inits.push_back(parm_ref->get_backend(&context));
5632 else if ((*p)->var_value()->is_in_heap())
5634 // If we take the address of a parameter, then we need
5635 // to copy it into the heap.
5636 std::string parm_name = (*p)->name() + ".param";
5637 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
5638 false, true, false, loc);
5639 Named_object* parm_no =
5640 Named_object::make_variable(parm_name, NULL, parm_var);
5641 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5643 vars.push_back(bvar);
5644 Expression* var_ref =
5645 Expression::make_var_reference(parm_no, loc);
5646 var_ref = Expression::make_heap_expression(var_ref, loc);
5647 var_inits.push_back(var_ref->get_backend(&context));
5649 param_vars.push_back(parm_bvar);
5651 else if ((*p)->is_result_variable())
5653 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5655 Type* type = (*p)->result_var_value()->type();
5657 if (!(*p)->result_var_value()->is_in_heap())
5659 Btype* btype = type->get_backend(gogo);
5660 init = gogo->backend()->zero_expression(btype);
5663 init = Expression::make_allocation(type,
5664 loc)->get_backend(&context);
5666 vars.push_back(bvar);
5667 var_inits.push_back(init);
5670 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
5672 go_assert(saw_errors());
5676 // If we need a closure variable, make sure to create it.
5677 // It gets installed in the function as a side effect of creation.
5678 if (this->closure_var_ != NULL)
5680 go_assert(this->closure_var_->var_value()->is_closure());
5681 this->closure_var_->get_backend_variable(gogo, named_function);
5684 if (this->block_ != NULL)
5686 // Declare variables if necessary.
5687 Bblock* var_decls = NULL;
5689 Bstatement* defer_init = NULL;
5690 if (!vars.empty() || this->defer_stack_ != NULL)
5693 gogo->backend()->block(this->fndecl_, NULL, vars,
5694 this->block_->start_location(),
5695 this->block_->end_location());
5697 if (this->defer_stack_ != NULL)
5699 Translate_context dcontext(gogo, named_function, this->block_,
5701 defer_init = this->defer_stack_->get_backend(&dcontext);
5705 // Build the backend representation for all the statements in the
5707 Translate_context context(gogo, named_function, NULL, NULL);
5708 Bblock* code_block = this->block_->get_backend(&context);
5710 // Initialize variables if necessary.
5711 std::vector<Bstatement*> init;
5712 go_assert(vars.size() == var_inits.size());
5713 for (size_t i = 0; i < vars.size(); ++i)
5715 Bstatement* init_stmt =
5716 gogo->backend()->init_statement(this->fndecl_, vars[i],
5718 init.push_back(init_stmt);
5720 if (defer_init != NULL)
5721 init.push_back(defer_init);
5722 Bstatement* var_init = gogo->backend()->statement_list(init);
5724 // Initialize all variables before executing this code block.
5725 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
5726 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
5728 // If we have a defer stack, initialize it at the start of a
5730 Bstatement* except = NULL;
5731 Bstatement* fini = NULL;
5732 if (defer_init != NULL)
5734 // Clean up the defer stack when we leave the function.
5735 this->build_defer_wrapper(gogo, named_function, &except, &fini);
5737 // Wrap the code for this function in an exception handler to handle
5740 gogo->backend()->exception_handler_statement(code_stmt,
5745 // Stick the code into the block we built for the receiver, if
5747 if (var_decls != NULL)
5749 std::vector<Bstatement*> code_stmt_list(1, code_stmt);
5750 gogo->backend()->block_add_statements(var_decls, code_stmt_list);
5751 code_stmt = gogo->backend()->block_statement(var_decls);
5754 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
5756 go_assert(saw_errors());
5761 // If we created a descriptor for the function, make sure we emit it.
5762 if (this->descriptor_ != NULL)
5764 Translate_context context(gogo, NULL, NULL, NULL);
5765 this->descriptor_->get_backend(&context);
5769 // Build the wrappers around function code needed if the function has
5770 // any defer statements. This sets *EXCEPT to an exception handler
5771 // and *FINI to a finally handler.
5774 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
5775 Bstatement** except, Bstatement** fini)
5777 Location end_loc = this->block_->end_location();
5779 // Add an exception handler. This is used if a panic occurs. Its
5780 // purpose is to stop the stack unwinding if a deferred function
5781 // calls recover. There are more details in
5782 // libgo/runtime/go-unwind.c.
5784 std::vector<Bstatement*> stmts;
5785 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5786 this->defer_stack(end_loc));
5787 Translate_context context(gogo, named_function, NULL, NULL);
5788 Bexpression* defer = call->get_backend(&context);
5789 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
5791 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
5792 if (ret_bstmt != NULL)
5793 stmts.push_back(ret_bstmt);
5795 go_assert(*except == NULL);
5796 *except = gogo->backend()->statement_list(stmts);
5798 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5799 this->defer_stack(end_loc));
5800 defer = call->get_backend(&context);
5802 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
5803 this->defer_stack(end_loc));
5804 Bexpression* undefer = call->get_backend(&context);
5805 Bstatement* function_defer =
5806 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
5808 stmts = std::vector<Bstatement*>(1, function_defer);
5809 if (this->type_->results() != NULL
5810 && !this->type_->results()->empty()
5811 && !this->type_->results()->front().name().empty())
5813 // If the result variables are named, and we are returning from
5814 // this function rather than panicing through it, we need to
5815 // return them again, because they might have been changed by a
5816 // defer function. The runtime routines set the defer_stack
5817 // variable to true if we are returning from this function.
5819 ret_bstmt = this->return_value(gogo, named_function, end_loc);
5820 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
5822 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
5824 Expression::make_temporary_reference(this->defer_stack_, end_loc);
5825 Bexpression* bref = ref->get_backend(&context);
5826 ret = gogo->backend()->conditional_expression(this->fndecl_,
5827 NULL, bref, ret, NULL,
5829 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
5832 go_assert(*fini == NULL);
5833 *fini = gogo->backend()->statement_list(stmts);
5836 // Return the statement that assigns values to this function's result struct.
5839 Function::return_value(Gogo* gogo, Named_object* named_function,
5840 Location location) const
5842 const Typed_identifier_list* results = this->type_->results();
5843 if (results == NULL || results->empty())
5846 go_assert(this->results_ != NULL);
5847 if (this->results_->size() != results->size())
5849 go_assert(saw_errors());
5850 return gogo->backend()->error_statement();
5853 std::vector<Bexpression*> vals(results->size());
5854 for (size_t i = 0; i < vals.size(); ++i)
5856 Named_object* no = (*this->results_)[i];
5857 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
5858 Bexpression* val = gogo->backend()->var_expression(bvar, VE_rvalue,
5860 if (no->result_var_value()->is_in_heap())
5862 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
5863 val = gogo->backend()->indirect_expression(bt, val, true, location);
5867 return gogo->backend()->return_statement(this->fndecl_, vals, location);
5872 Block::Block(Block* enclosing, Location location)
5873 : enclosing_(enclosing), statements_(),
5874 bindings_(new Bindings(enclosing == NULL
5876 : enclosing->bindings())),
5877 start_location_(location),
5878 end_location_(Linemap::unknown_location())
5882 // Add a statement to a block.
5885 Block::add_statement(Statement* statement)
5887 this->statements_.push_back(statement);
5890 // Add a statement to the front of a block. This is slow but is only
5891 // used for reference counts of parameters.
5894 Block::add_statement_at_front(Statement* statement)
5896 this->statements_.insert(this->statements_.begin(), statement);
5899 // Replace a statement in a block.
5902 Block::replace_statement(size_t index, Statement* s)
5904 go_assert(index < this->statements_.size());
5905 this->statements_[index] = s;
5908 // Add a statement before another statement.
5911 Block::insert_statement_before(size_t index, Statement* s)
5913 go_assert(index < this->statements_.size());
5914 this->statements_.insert(this->statements_.begin() + index, s);
5917 // Add a statement after another statement.
5920 Block::insert_statement_after(size_t index, Statement* s)
5922 go_assert(index < this->statements_.size());
5923 this->statements_.insert(this->statements_.begin() + index + 1, s);
5926 // Traverse the tree.
5929 Block::traverse(Traverse* traverse)
5931 unsigned int traverse_mask = traverse->traverse_mask();
5933 if ((traverse_mask & Traverse::traverse_blocks) != 0)
5935 int t = traverse->block(this);
5936 if (t == TRAVERSE_EXIT)
5937 return TRAVERSE_EXIT;
5938 else if (t == TRAVERSE_SKIP_COMPONENTS)
5939 return TRAVERSE_CONTINUE;
5943 & (Traverse::traverse_variables
5944 | Traverse::traverse_constants
5945 | Traverse::traverse_expressions
5946 | Traverse::traverse_types)) != 0)
5948 const unsigned int e_or_t = (Traverse::traverse_expressions
5949 | Traverse::traverse_types);
5950 const unsigned int e_or_t_or_s = (e_or_t
5951 | Traverse::traverse_statements);
5952 for (Bindings::const_definitions_iterator pb =
5953 this->bindings_->begin_definitions();
5954 pb != this->bindings_->end_definitions();
5957 int t = TRAVERSE_CONTINUE;
5958 switch ((*pb)->classification())
5960 case Named_object::NAMED_OBJECT_CONST:
5961 if ((traverse_mask & Traverse::traverse_constants) != 0)
5962 t = traverse->constant(*pb, false);
5963 if (t == TRAVERSE_CONTINUE
5964 && (traverse_mask & e_or_t) != 0)
5966 Type* tc = (*pb)->const_value()->type();
5968 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5969 return TRAVERSE_EXIT;
5970 t = (*pb)->const_value()->traverse_expression(traverse);
5974 case Named_object::NAMED_OBJECT_VAR:
5975 case Named_object::NAMED_OBJECT_RESULT_VAR:
5976 if ((traverse_mask & Traverse::traverse_variables) != 0)
5977 t = traverse->variable(*pb);
5978 if (t == TRAVERSE_CONTINUE
5979 && (traverse_mask & e_or_t) != 0)
5981 if ((*pb)->is_result_variable()
5982 || (*pb)->var_value()->has_type())
5984 Type* tv = ((*pb)->is_variable()
5985 ? (*pb)->var_value()->type()
5986 : (*pb)->result_var_value()->type());
5988 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5989 return TRAVERSE_EXIT;
5992 if (t == TRAVERSE_CONTINUE
5993 && (traverse_mask & e_or_t_or_s) != 0
5994 && (*pb)->is_variable())
5995 t = (*pb)->var_value()->traverse_expression(traverse,
5999 case Named_object::NAMED_OBJECT_FUNC:
6000 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
6003 case Named_object::NAMED_OBJECT_TYPE:
6004 if ((traverse_mask & e_or_t) != 0)
6005 t = Type::traverse((*pb)->type_value(), traverse);
6008 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
6009 case Named_object::NAMED_OBJECT_UNKNOWN:
6010 case Named_object::NAMED_OBJECT_ERRONEOUS:
6013 case Named_object::NAMED_OBJECT_PACKAGE:
6014 case Named_object::NAMED_OBJECT_SINK:
6021 if (t == TRAVERSE_EXIT)
6022 return TRAVERSE_EXIT;
6026 // No point in checking traverse_mask here--if we got here we always
6027 // want to walk the statements. The traversal can insert new
6028 // statements before or after the current statement. Inserting
6029 // statements before the current statement requires updating I via
6030 // the pointer; those statements will not be traversed. Any new
6031 // statements inserted after the current statement will be traversed
6033 for (size_t i = 0; i < this->statements_.size(); ++i)
6035 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
6036 return TRAVERSE_EXIT;
6039 return TRAVERSE_CONTINUE;
6042 // Work out types for unspecified variables and constants.
6045 Block::determine_types()
6047 for (Bindings::const_definitions_iterator pb =
6048 this->bindings_->begin_definitions();
6049 pb != this->bindings_->end_definitions();
6052 if ((*pb)->is_variable())
6053 (*pb)->var_value()->determine_type();
6054 else if ((*pb)->is_const())
6055 (*pb)->const_value()->determine_type();
6058 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6059 ps != this->statements_.end();
6061 (*ps)->determine_types();
6064 // Return true if the statements in this block may fall through.
6067 Block::may_fall_through() const
6069 if (this->statements_.empty())
6071 return this->statements_.back()->may_fall_through();
6074 // Convert a block to the backend representation.
6077 Block::get_backend(Translate_context* context)
6079 Gogo* gogo = context->gogo();
6080 Named_object* function = context->function();
6081 std::vector<Bvariable*> vars;
6082 vars.reserve(this->bindings_->size_definitions());
6083 for (Bindings::const_definitions_iterator pv =
6084 this->bindings_->begin_definitions();
6085 pv != this->bindings_->end_definitions();
6088 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
6089 vars.push_back((*pv)->get_backend_variable(gogo, function));
6092 go_assert(function != NULL);
6093 Bfunction* bfunction =
6094 function->func_value()->get_or_make_decl(gogo, function);
6095 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
6096 vars, this->start_location_,
6097 this->end_location_);
6099 Translate_context subcontext(gogo, function, this, ret);
6100 std::vector<Bstatement*> bstatements;
6101 bstatements.reserve(this->statements_.size());
6102 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
6103 p != this->statements_.end();
6105 bstatements.push_back((*p)->get_backend(&subcontext));
6107 context->backend()->block_add_statements(ret, bstatements);
6112 // Class Bindings_snapshot.
6114 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
6115 : block_(b), counts_(), location_(location)
6119 this->counts_.push_back(b->bindings()->size_definitions());
6124 // Report errors appropriate for a goto from B to this.
6127 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
6130 if (!this->check_goto_block(loc, b, this->block_, &dummy))
6132 this->check_goto_defs(loc, this->block_,
6133 this->block_->bindings()->size_definitions(),
6137 // Report errors appropriate for a goto from this to B.
6140 Bindings_snapshot::check_goto_to(const Block* b)
6143 if (!this->check_goto_block(this->location_, this->block_, b, &index))
6145 this->check_goto_defs(this->location_, b, this->counts_[index],
6146 b->bindings()->size_definitions());
6149 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6150 // Return true if all is well, false if we reported an error. If this
6151 // returns true, it sets *PINDEX to the number of blocks BTO is above
6155 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
6156 const Block* bto, size_t* pindex)
6158 // It is an error if BTO is not either BFROM or above BFROM.
6160 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
6164 go_error_at(loc, "goto jumps into block");
6165 go_inform(bto->start_location(), "goto target block starts here");
6173 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6174 // CFROM is the number of names defined at the point of the goto and
6175 // CTO is the number of names defined at the point of the label.
6178 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
6179 size_t cfrom, size_t cto)
6183 Bindings::const_definitions_iterator p =
6184 block->bindings()->begin_definitions();
6185 for (size_t i = 0; i < cfrom; ++i)
6187 go_assert(p != block->bindings()->end_definitions());
6190 go_assert(p != block->bindings()->end_definitions());
6192 std::string n = (*p)->message_name();
6193 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
6194 go_inform((*p)->location(), "%qs defined here", n.c_str());
6198 // Class Function_declaration.
6200 // Return the function descriptor.
6203 Function_declaration::descriptor(Gogo*, Named_object* no)
6205 go_assert(!this->fntype_->is_method());
6206 if (this->descriptor_ == NULL)
6207 this->descriptor_ = Expression::make_func_descriptor(no);
6208 return this->descriptor_;
6213 Variable::Variable(Type* type, Expression* init, bool is_global,
6214 bool is_parameter, bool is_receiver,
6216 : type_(type), init_(init), preinit_(NULL), location_(location),
6217 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
6218 is_closure_(false), is_receiver_(is_receiver),
6219 is_varargs_parameter_(false), is_used_(false),
6220 is_address_taken_(false), is_non_escaping_address_taken_(false),
6221 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6222 type_from_init_tuple_(false), type_from_range_index_(false),
6223 type_from_range_value_(false), type_from_chan_element_(false),
6224 is_type_switch_var_(false), determined_type_(false),
6225 in_unique_section_(false), escapes_(true)
6227 go_assert(type != NULL || init != NULL);
6228 go_assert(!is_parameter || init == NULL);
6231 // Traverse the initializer expression.
6234 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
6236 if (this->preinit_ != NULL)
6238 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
6239 return TRAVERSE_EXIT;
6241 if (this->init_ != NULL
6243 & (Traverse::traverse_expressions | Traverse::traverse_types))
6246 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
6247 return TRAVERSE_EXIT;
6249 return TRAVERSE_CONTINUE;
6252 // Lower the initialization expression after parsing is complete.
6255 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
6256 Statement_inserter* inserter)
6258 Named_object* dep = gogo->var_depends_on(this);
6259 if (dep != NULL && dep->is_variable())
6260 dep->var_value()->lower_init_expression(gogo, function, inserter);
6262 if (this->init_ != NULL && !this->init_is_lowered_)
6266 // We will give an error elsewhere, this is just to prevent
6267 // an infinite loop.
6272 Statement_inserter global_inserter;
6273 if (this->is_global_)
6275 global_inserter = Statement_inserter(gogo, this);
6276 inserter = &global_inserter;
6279 gogo->lower_expression(function, inserter, &this->init_);
6281 this->seen_ = false;
6283 this->init_is_lowered_ = true;
6287 // Flatten the initialization expression after ordering evaluations.
6290 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
6291 Statement_inserter* inserter)
6293 Named_object* dep = gogo->var_depends_on(this);
6294 if (dep != NULL && dep->is_variable())
6295 dep->var_value()->flatten_init_expression(gogo, function, inserter);
6297 if (this->init_ != NULL && !this->init_is_flattened_)
6301 // We will give an error elsewhere, this is just to prevent
6302 // an infinite loop.
6307 Statement_inserter global_inserter;
6308 if (this->is_global_)
6310 global_inserter = Statement_inserter(gogo, this);
6311 inserter = &global_inserter;
6314 gogo->flatten_expression(function, inserter, &this->init_);
6316 // If an interface conversion is needed, we need a temporary
6318 if (this->type_ != NULL
6319 && !Type::are_identical(this->type_, this->init_->type(), false,
6321 && this->init_->type()->interface_type() != NULL
6322 && !this->init_->is_variable())
6324 Temporary_statement* temp =
6325 Statement::make_temporary(NULL, this->init_, this->location_);
6326 inserter->insert(temp);
6327 this->init_ = Expression::make_temporary_reference(temp,
6331 this->seen_ = false;
6332 this->init_is_flattened_ = true;
6336 // Get the preinit block.
6339 Variable::preinit_block(Gogo* gogo)
6341 go_assert(this->is_global_);
6342 if (this->preinit_ == NULL)
6343 this->preinit_ = new Block(NULL, this->location());
6345 // If a global variable has a preinitialization statement, then we
6346 // need to have an initialization function.
6347 gogo->set_need_init_fn();
6349 return this->preinit_;
6352 // Add a statement to be run before the initialization expression.
6355 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
6357 Block* b = this->preinit_block(gogo);
6358 b->add_statement(s);
6359 b->set_end_location(s->location());
6362 // Whether this variable has a type.
6365 Variable::has_type() const
6367 if (this->type_ == NULL)
6370 // A variable created in a type switch case nil does not actually
6371 // have a type yet. It will be changed to use the initializer's
6372 // type in determine_type.
6373 if (this->is_type_switch_var_
6374 && this->type_->is_nil_constant_as_type())
6380 // In an assignment which sets a variable to a tuple of EXPR, return
6381 // the type of the first element of the tuple.
6384 Variable::type_from_tuple(Expression* expr, bool report_error) const
6386 if (expr->map_index_expression() != NULL)
6388 Map_type* mt = expr->map_index_expression()->get_map_type();
6390 return Type::make_error_type();
6391 return mt->val_type();
6393 else if (expr->receive_expression() != NULL)
6395 Expression* channel = expr->receive_expression()->channel();
6396 Type* channel_type = channel->type();
6397 if (channel_type->channel_type() == NULL)
6398 return Type::make_error_type();
6399 return channel_type->channel_type()->element_type();
6404 go_error_at(this->location(), "invalid tuple definition");
6405 return Type::make_error_type();
6409 // Given EXPR used in a range clause, return either the index type or
6410 // the value type of the range, depending upon GET_INDEX_TYPE.
6413 Variable::type_from_range(Expression* expr, bool get_index_type,
6414 bool report_error) const
6416 Type* t = expr->type();
6417 if (t->array_type() != NULL
6418 || (t->points_to() != NULL
6419 && t->points_to()->array_type() != NULL
6420 && !t->points_to()->is_slice_type()))
6423 return Type::lookup_integer_type("int");
6425 return t->deref()->array_type()->element_type();
6427 else if (t->is_string_type())
6430 return Type::lookup_integer_type("int");
6432 return Type::lookup_integer_type("int32");
6434 else if (t->map_type() != NULL)
6437 return t->map_type()->key_type();
6439 return t->map_type()->val_type();
6441 else if (t->channel_type() != NULL)
6444 return t->channel_type()->element_type();
6448 go_error_at(this->location(),
6449 ("invalid definition of value variable "
6450 "for channel range"));
6451 return Type::make_error_type();
6457 go_error_at(this->location(), "invalid type for range clause");
6458 return Type::make_error_type();
6462 // EXPR should be a channel. Return the channel's element type.
6465 Variable::type_from_chan_element(Expression* expr, bool report_error) const
6467 Type* t = expr->type();
6468 if (t->channel_type() != NULL)
6469 return t->channel_type()->element_type();
6473 go_error_at(this->location(), "expected channel");
6474 return Type::make_error_type();
6478 // Return the type of the Variable. This may be called before
6479 // Variable::determine_type is called, which means that we may need to
6480 // get the type from the initializer. FIXME: If we combine lowering
6481 // with type determination, then this should be unnecessary.
6486 // A variable in a type switch with a nil case will have the wrong
6487 // type here. This gets fixed up in determine_type, below.
6488 Type* type = this->type_;
6489 Expression* init = this->init_;
6490 if (this->is_type_switch_var_
6492 && this->type_->is_nil_constant_as_type())
6494 Type_guard_expression* tge = this->init_->type_guard_expression();
6495 go_assert(tge != NULL);
6502 if (this->type_ == NULL || !this->type_->is_error_type())
6504 go_error_at(this->location_, "variable initializer refers to itself");
6505 this->type_ = Type::make_error_type();
6514 else if (this->type_from_init_tuple_)
6515 type = this->type_from_tuple(init, false);
6516 else if (this->type_from_range_index_ || this->type_from_range_value_)
6517 type = this->type_from_range(init, this->type_from_range_index_, false);
6518 else if (this->type_from_chan_element_)
6519 type = this->type_from_chan_element(init, false);
6522 go_assert(init != NULL);
6523 type = init->type();
6524 go_assert(type != NULL);
6526 // Variables should not have abstract types.
6527 if (type->is_abstract())
6528 type = type->make_non_abstract_type();
6530 if (type->is_void_type())
6531 type = Type::make_error_type();
6534 this->seen_ = false;
6539 // Fetch the type from a const pointer, in which case it should have
6540 // been set already.
6543 Variable::type() const
6545 go_assert(this->type_ != NULL);
6549 // Set the type if necessary.
6552 Variable::determine_type()
6554 if (this->determined_type_)
6556 this->determined_type_ = true;
6558 if (this->preinit_ != NULL)
6559 this->preinit_->determine_types();
6561 // A variable in a type switch with a nil case will have the wrong
6562 // type here. It will have an initializer which is a type guard.
6563 // We want to initialize it to the value without the type guard, and
6564 // use the type of that value as well.
6565 if (this->is_type_switch_var_
6566 && this->type_ != NULL
6567 && this->type_->is_nil_constant_as_type())
6569 Type_guard_expression* tge = this->init_->type_guard_expression();
6570 go_assert(tge != NULL);
6572 this->init_ = tge->expr();
6575 if (this->init_ == NULL)
6576 go_assert(this->type_ != NULL && !this->type_->is_abstract());
6577 else if (this->type_from_init_tuple_)
6579 Expression *init = this->init_;
6580 init->determine_type_no_context();
6581 this->type_ = this->type_from_tuple(init, true);
6584 else if (this->type_from_range_index_ || this->type_from_range_value_)
6586 Expression* init = this->init_;
6587 init->determine_type_no_context();
6588 this->type_ = this->type_from_range(init, this->type_from_range_index_,
6592 else if (this->type_from_chan_element_)
6594 Expression* init = this->init_;
6595 init->determine_type_no_context();
6596 this->type_ = this->type_from_chan_element(init, true);
6601 Type_context context(this->type_, false);
6602 this->init_->determine_type(&context);
6603 if (this->type_ == NULL)
6605 Type* type = this->init_->type();
6606 go_assert(type != NULL);
6607 if (type->is_abstract())
6608 type = type->make_non_abstract_type();
6610 if (type->is_void_type())
6612 go_error_at(this->location_, "variable has no type");
6613 type = Type::make_error_type();
6615 else if (type->is_nil_type())
6617 go_error_at(this->location_, "variable defined to nil type");
6618 type = Type::make_error_type();
6620 else if (type->is_call_multiple_result_type())
6622 go_error_at(this->location_,
6623 "single variable set to multiple-value function call");
6624 type = Type::make_error_type();
6632 // Get the initial value of a variable. This does not
6633 // consider whether the variable is in the heap--it returns the
6634 // initial value as though it were always stored in the stack.
6637 Variable::get_init(Gogo* gogo, Named_object* function)
6639 go_assert(this->preinit_ == NULL);
6640 Location loc = this->location();
6641 if (this->init_ == NULL)
6643 go_assert(!this->is_parameter_);
6644 if (this->is_global_ || this->is_in_heap())
6646 Btype* btype = this->type()->get_backend(gogo);
6647 return gogo->backend()->zero_expression(btype);
6651 Translate_context context(gogo, function, NULL, NULL);
6652 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
6653 return init->get_backend(&context);
6657 // Get the initial value of a variable when a block is required.
6658 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6661 Variable::get_init_block(Gogo* gogo, Named_object* function,
6662 Bvariable* var_decl)
6664 go_assert(this->preinit_ != NULL);
6666 // We want to add the variable assignment to the end of the preinit
6669 Translate_context context(gogo, function, NULL, NULL);
6670 Bblock* bblock = this->preinit_->get_backend(&context);
6671 Bfunction* bfunction =
6672 function->func_value()->get_or_make_decl(gogo, function);
6674 // It's possible to have pre-init statements without an initializer
6675 // if the pre-init statements set the variable.
6676 Bstatement* decl_init = NULL;
6677 if (this->init_ != NULL)
6679 if (var_decl == NULL)
6681 Bexpression* init_bexpr = this->init_->get_backend(&context);
6682 decl_init = gogo->backend()->expression_statement(bfunction,
6687 Location loc = this->location();
6688 Expression* val_expr =
6689 Expression::make_cast(this->type(), this->init_, loc);
6690 Bexpression* val = val_expr->get_backend(&context);
6691 Bexpression* var_ref =
6692 gogo->backend()->var_expression(var_decl, VE_lvalue, loc);
6693 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
6697 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
6698 if (decl_init != NULL)
6699 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
6703 // Export the variable
6706 Variable::export_var(Export* exp, const std::string& name) const
6708 go_assert(this->is_global_);
6709 exp->write_c_string("var ");
6710 exp->write_string(name);
6711 exp->write_c_string(" ");
6712 exp->write_type(this->type());
6713 exp->write_c_string(";\n");
6716 // Import a variable.
6719 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
6721 imp->require_c_string("var ");
6722 *pname = imp->read_identifier();
6723 imp->require_c_string(" ");
6724 *ptype = imp->read_type();
6725 imp->require_c_string(";\n");
6728 // Convert a variable to the backend representation.
6731 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
6732 const Package* package, const std::string& name)
6734 if (this->backend_ == NULL)
6736 Backend* backend = gogo->backend();
6737 Type* type = this->type_;
6738 if (type->is_error_type()
6739 || (type->is_undefined()
6740 && (!this->is_global_ || package == NULL)))
6741 this->backend_ = backend->error_variable();
6744 bool is_parameter = this->is_parameter_;
6745 if (this->is_receiver_ && type->points_to() == NULL)
6746 is_parameter = false;
6747 if (this->is_in_heap())
6749 is_parameter = false;
6750 type = Type::make_pointer_type(type);
6753 const std::string n = Gogo::unpack_hidden_name(name);
6754 Btype* btype = type->get_backend(gogo);
6757 if (Map_type::is_zero_value(this))
6758 bvar = Map_type::backend_zero_value(gogo);
6759 else if (this->is_global_)
6761 std::string var_name(package != NULL
6762 ? package->package_name()
6763 : gogo->package_name());
6764 var_name.push_back('.');
6766 std::string asm_name;
6767 if (Gogo::is_hidden_name(name))
6768 asm_name = var_name;
6771 asm_name = package != NULL
6772 ? package->pkgpath_symbol()
6773 : gogo->pkgpath_symbol();
6774 asm_name.push_back('.');
6777 asm_name = go_encode_id(asm_name);
6779 bool is_hidden = Gogo::is_hidden_name(name);
6780 // Hack to export runtime.writeBarrier. FIXME.
6781 // This is because go:linkname doesn't work on variables.
6782 if (gogo->compiling_runtime()
6783 && var_name == "runtime.writeBarrier")
6786 bvar = backend->global_variable(var_name,
6791 this->in_unique_section_,
6794 else if (function == NULL)
6796 go_assert(saw_errors());
6797 bvar = backend->error_variable();
6801 Bfunction* bfunction = function->func_value()->get_decl();
6802 bool is_address_taken = (this->is_non_escaping_address_taken_
6803 && !this->is_in_heap());
6804 if (this->is_closure())
6805 bvar = backend->static_chain_variable(bfunction, n, btype,
6807 else if (is_parameter)
6808 bvar = backend->parameter_variable(bfunction, n, btype,
6812 bvar = backend->local_variable(bfunction, n, btype,
6816 this->backend_ = bvar;
6819 return this->backend_;
6822 // Class Result_variable.
6824 // Convert a result variable to the backend representation.
6827 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
6828 const std::string& name)
6830 if (this->backend_ == NULL)
6832 Backend* backend = gogo->backend();
6833 Type* type = this->type_;
6834 if (type->is_error())
6835 this->backend_ = backend->error_variable();
6838 if (this->is_in_heap())
6839 type = Type::make_pointer_type(type);
6840 Btype* btype = type->get_backend(gogo);
6841 Bfunction* bfunction = function->func_value()->get_decl();
6842 std::string n = Gogo::unpack_hidden_name(name);
6843 bool is_address_taken = (this->is_non_escaping_address_taken_
6844 && !this->is_in_heap());
6845 this->backend_ = backend->local_variable(bfunction, n, btype,
6850 return this->backend_;
6853 // Class Named_constant.
6855 // Traverse the initializer expression.
6858 Named_constant::traverse_expression(Traverse* traverse)
6860 return Expression::traverse(&this->expr_, traverse);
6863 // Determine the type of the constant.
6866 Named_constant::determine_type()
6868 if (this->type_ != NULL)
6870 Type_context context(this->type_, false);
6871 this->expr_->determine_type(&context);
6875 // A constant may have an abstract type.
6876 Type_context context(NULL, true);
6877 this->expr_->determine_type(&context);
6878 this->type_ = this->expr_->type();
6879 go_assert(this->type_ != NULL);
6883 // Indicate that we found and reported an error for this constant.
6886 Named_constant::set_error()
6888 this->type_ = Type::make_error_type();
6889 this->expr_ = Expression::make_error(this->location_);
6892 // Export a constant.
6895 Named_constant::export_const(Export* exp, const std::string& name) const
6897 exp->write_c_string("const ");
6898 exp->write_string(name);
6899 exp->write_c_string(" ");
6900 if (!this->type_->is_abstract())
6902 exp->write_type(this->type_);
6903 exp->write_c_string(" ");
6905 exp->write_c_string("= ");
6906 this->expr()->export_expression(exp);
6907 exp->write_c_string(";\n");
6910 // Import a constant.
6913 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
6916 imp->require_c_string("const ");
6917 *pname = imp->read_identifier();
6918 imp->require_c_string(" ");
6919 if (imp->peek_char() == '=')
6923 *ptype = imp->read_type();
6924 imp->require_c_string(" ");
6926 imp->require_c_string("= ");
6927 *pexpr = Expression::import_expression(imp);
6928 imp->require_c_string(";\n");
6931 // Get the backend representation.
6934 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
6936 if (this->bconst_ == NULL)
6938 Translate_context subcontext(gogo, NULL, NULL, NULL);
6939 Type* type = this->type();
6940 Location loc = this->location();
6942 Expression* const_ref = Expression::make_const_reference(const_no, loc);
6943 Bexpression* const_decl = const_ref->get_backend(&subcontext);
6944 if (type != NULL && type->is_numeric_type())
6946 Btype* btype = type->get_backend(gogo);
6947 std::string name = const_no->get_id(gogo);
6949 gogo->backend()->named_constant_expression(btype, name,
6952 this->bconst_ = const_decl;
6954 return this->bconst_;
6960 Type_declaration::add_method(const std::string& name, Function* function)
6962 Named_object* ret = Named_object::make_function(name, NULL, function);
6963 this->methods_.push_back(ret);
6967 // Add a method declaration.
6970 Type_declaration::add_method_declaration(const std::string& name,
6972 Function_type* type,
6975 Named_object* ret = Named_object::make_function_declaration(name, package,
6977 this->methods_.push_back(ret);
6981 // Return whether any methods are defined.
6984 Type_declaration::has_methods() const
6986 return !this->methods_.empty();
6989 // Define methods for the real type.
6992 Type_declaration::define_methods(Named_type* nt)
6994 if (this->methods_.empty())
6997 while (nt->is_alias())
6999 Type *t = nt->real_type()->forwarded();
7000 if (t->named_type() != NULL)
7001 nt = t->named_type();
7002 else if (t->forward_declaration_type() != NULL)
7004 Named_object* no = t->forward_declaration_type()->named_object();
7005 Type_declaration* td = no->type_declaration_value();
7006 td->methods_.insert(td->methods_.end(), this->methods_.begin(),
7007 this->methods_.end());
7008 this->methods_.clear();
7013 for (std::vector<Named_object*>::const_iterator p =
7014 this->methods_.begin();
7015 p != this->methods_.end();
7017 go_error_at((*p)->location(),
7018 ("invalid receiver type "
7019 "(receiver must be a named type"));
7024 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
7025 p != this->methods_.end();
7028 if (!(*p)->func_value()->is_sink())
7029 nt->add_existing_method(*p);
7033 // We are using the type. Return true if we should issue a warning.
7036 Type_declaration::using_type()
7038 bool ret = !this->issued_warning_;
7039 this->issued_warning_ = true;
7043 // Class Unknown_name.
7045 // Set the real named object.
7048 Unknown_name::set_real_named_object(Named_object* no)
7050 go_assert(this->real_named_object_ == NULL);
7051 go_assert(!no->is_unknown());
7052 this->real_named_object_ = no;
7055 // Class Named_object.
7057 Named_object::Named_object(const std::string& name,
7058 const Package* package,
7059 Classification classification)
7060 : name_(name), package_(package), classification_(classification),
7061 is_redefinition_(false)
7063 if (Gogo::is_sink_name(name))
7064 go_assert(classification == NAMED_OBJECT_SINK);
7067 // Make an unknown name. This is used by the parser. The name must
7068 // be resolved later. Unknown names are only added in the current
7072 Named_object::make_unknown_name(const std::string& name,
7075 Named_object* named_object = new Named_object(name, NULL,
7076 NAMED_OBJECT_UNKNOWN);
7077 Unknown_name* value = new Unknown_name(location);
7078 named_object->u_.unknown_value = value;
7079 return named_object;
7085 Named_object::make_constant(const Typed_identifier& tid,
7086 const Package* package, Expression* expr,
7089 Named_object* named_object = new Named_object(tid.name(), package,
7090 NAMED_OBJECT_CONST);
7091 Named_constant* named_constant = new Named_constant(tid.type(), expr,
7094 named_object->u_.const_value = named_constant;
7095 return named_object;
7098 // Make a named type.
7101 Named_object::make_type(const std::string& name, const Package* package,
7102 Type* type, Location location)
7104 Named_object* named_object = new Named_object(name, package,
7106 Named_type* named_type = Type::make_named_type(named_object, type, location);
7107 named_object->u_.type_value = named_type;
7108 return named_object;
7111 // Make a type declaration.
7114 Named_object::make_type_declaration(const std::string& name,
7115 const Package* package,
7118 Named_object* named_object = new Named_object(name, package,
7119 NAMED_OBJECT_TYPE_DECLARATION);
7120 Type_declaration* type_declaration = new Type_declaration(location);
7121 named_object->u_.type_declaration = type_declaration;
7122 return named_object;
7128 Named_object::make_variable(const std::string& name, const Package* package,
7131 Named_object* named_object = new Named_object(name, package,
7133 named_object->u_.var_value = variable;
7134 return named_object;
7137 // Make a result variable.
7140 Named_object::make_result_variable(const std::string& name,
7141 Result_variable* result)
7143 Named_object* named_object = new Named_object(name, NULL,
7144 NAMED_OBJECT_RESULT_VAR);
7145 named_object->u_.result_var_value = result;
7146 return named_object;
7149 // Make a sink. This is used for the special blank identifier _.
7152 Named_object::make_sink()
7154 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
7157 // Make a named function.
7160 Named_object::make_function(const std::string& name, const Package* package,
7163 Named_object* named_object = new Named_object(name, package,
7165 named_object->u_.func_value = function;
7166 return named_object;
7169 // Make a function declaration.
7172 Named_object::make_function_declaration(const std::string& name,
7173 const Package* package,
7174 Function_type* fntype,
7177 Named_object* named_object = new Named_object(name, package,
7178 NAMED_OBJECT_FUNC_DECLARATION);
7179 Function_declaration *func_decl = new Function_declaration(fntype, location);
7180 named_object->u_.func_declaration_value = func_decl;
7181 return named_object;
7187 Named_object::make_package(const std::string& alias, Package* package)
7189 Named_object* named_object = new Named_object(alias, NULL,
7190 NAMED_OBJECT_PACKAGE);
7191 named_object->u_.package_value = package;
7192 return named_object;
7195 // Return the name to use in an error message.
7198 Named_object::message_name() const
7200 if (this->package_ == NULL)
7201 return Gogo::message_name(this->name_);
7203 if (this->package_->has_package_name())
7204 ret = this->package_->package_name();
7206 ret = this->package_->pkgpath();
7207 ret = Gogo::message_name(ret);
7209 ret += Gogo::message_name(this->name_);
7213 // Set the type when a declaration is defined.
7216 Named_object::set_type_value(Named_type* named_type)
7218 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
7219 Type_declaration* td = this->u_.type_declaration;
7220 td->define_methods(named_type);
7222 Named_object* in_function = td->in_function(&index);
7223 if (in_function != NULL)
7224 named_type->set_in_function(in_function, index);
7226 this->classification_ = NAMED_OBJECT_TYPE;
7227 this->u_.type_value = named_type;
7230 // Define a function which was previously declared.
7233 Named_object::set_function_value(Function* function)
7235 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
7236 if (this->func_declaration_value()->has_descriptor())
7238 Expression* descriptor =
7239 this->func_declaration_value()->descriptor(NULL, NULL);
7240 function->set_descriptor(descriptor);
7242 this->classification_ = NAMED_OBJECT_FUNC;
7243 // FIXME: We should free the old value.
7244 this->u_.func_value = function;
7247 // Declare an unknown object as a type declaration.
7250 Named_object::declare_as_type()
7252 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
7253 Unknown_name* unk = this->u_.unknown_value;
7254 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
7255 this->u_.type_declaration = new Type_declaration(unk->location());
7259 // Return the location of a named object.
7262 Named_object::location() const
7264 switch (this->classification_)
7267 case NAMED_OBJECT_UNINITIALIZED:
7270 case NAMED_OBJECT_ERRONEOUS:
7271 return Linemap::unknown_location();
7273 case NAMED_OBJECT_UNKNOWN:
7274 return this->unknown_value()->location();
7276 case NAMED_OBJECT_CONST:
7277 return this->const_value()->location();
7279 case NAMED_OBJECT_TYPE:
7280 return this->type_value()->location();
7282 case NAMED_OBJECT_TYPE_DECLARATION:
7283 return this->type_declaration_value()->location();
7285 case NAMED_OBJECT_VAR:
7286 return this->var_value()->location();
7288 case NAMED_OBJECT_RESULT_VAR:
7289 return this->result_var_value()->location();
7291 case NAMED_OBJECT_SINK:
7294 case NAMED_OBJECT_FUNC:
7295 return this->func_value()->location();
7297 case NAMED_OBJECT_FUNC_DECLARATION:
7298 return this->func_declaration_value()->location();
7300 case NAMED_OBJECT_PACKAGE:
7301 return this->package_value()->location();
7305 // Export a named object.
7308 Named_object::export_named_object(Export* exp) const
7310 switch (this->classification_)
7313 case NAMED_OBJECT_UNINITIALIZED:
7314 case NAMED_OBJECT_UNKNOWN:
7317 case NAMED_OBJECT_ERRONEOUS:
7320 case NAMED_OBJECT_CONST:
7321 this->const_value()->export_const(exp, this->name_);
7324 case NAMED_OBJECT_TYPE:
7325 this->type_value()->export_named_type(exp, this->name_);
7328 case NAMED_OBJECT_TYPE_DECLARATION:
7329 go_error_at(this->type_declaration_value()->location(),
7330 "attempt to export %<%s%> which was declared but not defined",
7331 this->message_name().c_str());
7334 case NAMED_OBJECT_FUNC_DECLARATION:
7335 this->func_declaration_value()->export_func(exp, this->name_);
7338 case NAMED_OBJECT_VAR:
7339 this->var_value()->export_var(exp, this->name_);
7342 case NAMED_OBJECT_RESULT_VAR:
7343 case NAMED_OBJECT_SINK:
7346 case NAMED_OBJECT_FUNC:
7347 this->func_value()->export_func(exp, this->name_);
7352 // Convert a variable to the backend representation.
7355 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
7357 if (this->classification_ == NAMED_OBJECT_VAR)
7358 return this->var_value()->get_backend_variable(gogo, function,
7359 this->package_, this->name_);
7360 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
7361 return this->result_var_value()->get_backend_variable(gogo, function,
7368 // Return the external identifier for this object.
7371 Named_object::get_id(Gogo* gogo)
7373 go_assert(!this->is_variable() && !this->is_result_variable());
7374 std::string decl_name;
7375 if (this->is_function_declaration()
7376 && !this->func_declaration_value()->asm_name().empty())
7377 decl_name = this->func_declaration_value()->asm_name();
7378 else if (this->is_type()
7379 && Linemap::is_predeclared_location(this->type_value()->location()))
7381 // We don't need the package name for builtin types.
7382 decl_name = Gogo::unpack_hidden_name(this->name_);
7386 std::string package_name;
7387 if (this->package_ == NULL)
7388 package_name = gogo->package_name();
7390 package_name = this->package_->package_name();
7392 // Note that this will be misleading if this is an unexported
7393 // method generated for an embedded imported type. In that case
7394 // the unexported method should have the package name of the
7395 // package from which it is imported, but we are going to give
7396 // it our package name. Fixing this would require knowing the
7397 // package name, but we only know the package path. It might be
7398 // better to use package paths here anyhow. This doesn't affect
7399 // the assembler code, because we always set that name in
7400 // Function::get_or_make_decl anyhow. FIXME.
7402 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
7404 Function_type* fntype;
7405 if (this->is_function())
7406 fntype = this->func_value()->type();
7407 else if (this->is_function_declaration())
7408 fntype = this->func_declaration_value()->type();
7411 if (fntype != NULL && fntype->is_method())
7413 decl_name.push_back('.');
7414 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
7417 if (this->is_type())
7420 const Named_object* in_function = this->type_value()->in_function(&index);
7421 if (in_function != NULL)
7423 decl_name += '$' + Gogo::unpack_hidden_name(in_function->name());
7427 snprintf(buf, sizeof buf, "%u", index);
7436 // Get the backend representation for this named object.
7439 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
7440 std::vector<Btype*>& type_decls,
7441 std::vector<Bfunction*>& func_decls)
7443 // If this is a definition, avoid trying to get the backend
7444 // representation, as that can crash.
7445 if (this->is_redefinition_)
7447 go_assert(saw_errors());
7451 switch (this->classification_)
7453 case NAMED_OBJECT_CONST:
7454 if (!Gogo::is_erroneous_name(this->name_))
7455 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
7458 case NAMED_OBJECT_TYPE:
7460 Named_type* named_type = this->u_.type_value;
7461 if (!Gogo::is_erroneous_name(this->name_))
7462 type_decls.push_back(named_type->get_backend(gogo));
7464 // We need to produce a type descriptor for every named
7465 // type, and for a pointer to every named type, since
7466 // other files or packages might refer to them. We need
7467 // to do this even for hidden types, because they might
7468 // still be returned by some function. Simply calling the
7469 // type_descriptor method is enough to create the type
7470 // descriptor, even though we don't do anything with it.
7471 if (this->package_ == NULL && !saw_errors())
7474 type_descriptor_pointer(gogo, Linemap::predeclared_location());
7475 named_type->gc_symbol_pointer(gogo);
7476 Type* pn = Type::make_pointer_type(named_type);
7477 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
7478 pn->gc_symbol_pointer(gogo);
7483 case NAMED_OBJECT_TYPE_DECLARATION:
7484 go_error_at(Linemap::unknown_location(),
7485 "reference to undefined type %qs",
7486 this->message_name().c_str());
7489 case NAMED_OBJECT_VAR:
7490 case NAMED_OBJECT_RESULT_VAR:
7491 case NAMED_OBJECT_SINK:
7494 case NAMED_OBJECT_FUNC:
7496 Function* func = this->u_.func_value;
7497 if (!Gogo::is_erroneous_name(this->name_))
7498 func_decls.push_back(func->get_or_make_decl(gogo, this));
7500 if (func->block() != NULL)
7501 func->build(gogo, this);
7505 case NAMED_OBJECT_ERRONEOUS:
7515 Bindings::Bindings(Bindings* enclosing)
7516 : enclosing_(enclosing), named_objects_(), bindings_()
7523 Bindings::clear_file_scope(Gogo* gogo)
7525 Contour::iterator p = this->bindings_.begin();
7526 while (p != this->bindings_.end())
7529 if (p->second->package() != NULL)
7531 else if (p->second->is_package())
7533 else if (p->second->is_function()
7534 && !p->second->func_value()->type()->is_method()
7535 && Gogo::unpack_hidden_name(p->second->name()) == "init")
7544 gogo->add_file_block_name(p->second->name(), p->second->location());
7545 p = this->bindings_.erase(p);
7550 // Look up a symbol.
7553 Bindings::lookup(const std::string& name) const
7555 Contour::const_iterator p = this->bindings_.find(name);
7556 if (p != this->bindings_.end())
7557 return p->second->resolve();
7558 else if (this->enclosing_ != NULL)
7559 return this->enclosing_->lookup(name);
7564 // Look up a symbol locally.
7567 Bindings::lookup_local(const std::string& name) const
7569 Contour::const_iterator p = this->bindings_.find(name);
7570 if (p == this->bindings_.end())
7575 // Remove an object from a set of bindings. This is used for a
7576 // special case in thunks for functions which call recover.
7579 Bindings::remove_binding(Named_object* no)
7581 Contour::iterator pb = this->bindings_.find(no->name());
7582 go_assert(pb != this->bindings_.end());
7583 this->bindings_.erase(pb);
7584 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
7585 pn != this->named_objects_.end();
7590 this->named_objects_.erase(pn);
7597 // Add a method to the list of objects. This is not added to the
7598 // lookup table. This is so that we have a single list of objects
7599 // declared at the top level, which we walk through when it's time to
7600 // convert to trees.
7603 Bindings::add_method(Named_object* method)
7605 this->named_objects_.push_back(method);
7608 // Add a generic Named_object to a Contour.
7611 Bindings::add_named_object_to_contour(Contour* contour,
7612 Named_object* named_object)
7614 go_assert(named_object == named_object->resolve());
7615 const std::string& name(named_object->name());
7616 go_assert(!Gogo::is_sink_name(name));
7618 std::pair<Contour::iterator, bool> ins =
7619 contour->insert(std::make_pair(name, named_object));
7622 // The name was already there.
7623 if (named_object->package() != NULL
7624 && ins.first->second->package() == named_object->package()
7625 && (ins.first->second->classification()
7626 == named_object->classification()))
7628 // This is a second import of the same object.
7629 return ins.first->second;
7631 ins.first->second = this->new_definition(ins.first->second,
7633 return ins.first->second;
7637 // Don't push declarations on the list. We push them on when
7638 // and if we find the definitions. That way we genericize the
7639 // functions in order.
7640 if (!named_object->is_type_declaration()
7641 && !named_object->is_function_declaration()
7642 && !named_object->is_unknown())
7643 this->named_objects_.push_back(named_object);
7644 return named_object;
7648 // We had an existing named object OLD_OBJECT, and we've seen a new
7649 // one NEW_OBJECT with the same name. FIXME: This does not free the
7650 // new object when we don't need it.
7653 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
7655 if (new_object->is_erroneous() && !old_object->is_erroneous())
7659 switch (old_object->classification())
7662 case Named_object::NAMED_OBJECT_UNINITIALIZED:
7665 case Named_object::NAMED_OBJECT_ERRONEOUS:
7668 case Named_object::NAMED_OBJECT_UNKNOWN:
7670 Named_object* real = old_object->unknown_value()->real_named_object();
7672 return this->new_definition(real, new_object);
7673 go_assert(!new_object->is_unknown());
7674 old_object->unknown_value()->set_real_named_object(new_object);
7675 if (!new_object->is_type_declaration()
7676 && !new_object->is_function_declaration())
7677 this->named_objects_.push_back(new_object);
7681 case Named_object::NAMED_OBJECT_CONST:
7684 case Named_object::NAMED_OBJECT_TYPE:
7685 if (new_object->is_type_declaration())
7689 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7690 if (new_object->is_type_declaration())
7692 if (new_object->is_type())
7694 old_object->set_type_value(new_object->type_value());
7695 new_object->type_value()->set_named_object(old_object);
7696 this->named_objects_.push_back(old_object);
7701 case Named_object::NAMED_OBJECT_VAR:
7702 case Named_object::NAMED_OBJECT_RESULT_VAR:
7703 // We have already given an error in the parser for cases where
7704 // one parameter or result variable redeclares another one.
7705 if ((new_object->is_variable()
7706 && new_object->var_value()->is_parameter())
7707 || new_object->is_result_variable())
7711 case Named_object::NAMED_OBJECT_SINK:
7714 case Named_object::NAMED_OBJECT_FUNC:
7715 if (new_object->is_function_declaration())
7717 if (!new_object->func_declaration_value()->asm_name().empty())
7718 go_error_at(Linemap::unknown_location(),
7719 ("sorry, not implemented: "
7720 "__asm__ for function definitions"));
7721 Function_type* old_type = old_object->func_value()->type();
7722 Function_type* new_type =
7723 new_object->func_declaration_value()->type();
7724 if (old_type->is_valid_redeclaration(new_type, &reason))
7729 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7731 if (new_object->is_function())
7733 Function_type* old_type =
7734 old_object->func_declaration_value()->type();
7735 Function_type* new_type = new_object->func_value()->type();
7736 if (old_type->is_valid_redeclaration(new_type, &reason))
7738 if (!old_object->func_declaration_value()->asm_name().empty())
7739 go_error_at(Linemap::unknown_location(),
7740 ("sorry, not implemented: "
7741 "__asm__ for function definitions"));
7742 old_object->set_function_value(new_object->func_value());
7743 this->named_objects_.push_back(old_object);
7750 case Named_object::NAMED_OBJECT_PACKAGE:
7754 std::string n = old_object->message_name();
7756 go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
7758 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
7760 old_object->set_is_redefinition();
7761 new_object->set_is_redefinition();
7763 go_inform(old_object->location(), "previous definition of %qs was here",
7769 // Add a named type.
7772 Bindings::add_named_type(Named_type* named_type)
7774 return this->add_named_object(named_type->named_object());
7780 Bindings::add_function(const std::string& name, const Package* package,
7783 return this->add_named_object(Named_object::make_function(name, package,
7787 // Add a function declaration.
7790 Bindings::add_function_declaration(const std::string& name,
7791 const Package* package,
7792 Function_type* type,
7795 Named_object* no = Named_object::make_function_declaration(name, package,
7797 return this->add_named_object(no);
7800 // Define a type which was previously declared.
7803 Bindings::define_type(Named_object* no, Named_type* type)
7805 no->set_type_value(type);
7806 this->named_objects_.push_back(no);
7809 // Mark all local variables as used. This is used for some types of
7813 Bindings::mark_locals_used()
7815 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
7816 p != this->named_objects_.end();
7818 if ((*p)->is_variable())
7819 (*p)->var_value()->set_is_used();
7822 // Traverse bindings.
7825 Bindings::traverse(Traverse* traverse, bool is_global)
7827 unsigned int traverse_mask = traverse->traverse_mask();
7829 // We don't use an iterator because we permit the traversal to add
7830 // new global objects.
7831 const unsigned int e_or_t = (Traverse::traverse_expressions
7832 | Traverse::traverse_types);
7833 const unsigned int e_or_t_or_s = (e_or_t
7834 | Traverse::traverse_statements);
7835 for (size_t i = 0; i < this->named_objects_.size(); ++i)
7837 Named_object* p = this->named_objects_[i];
7838 int t = TRAVERSE_CONTINUE;
7839 switch (p->classification())
7841 case Named_object::NAMED_OBJECT_CONST:
7842 if ((traverse_mask & Traverse::traverse_constants) != 0)
7843 t = traverse->constant(p, is_global);
7844 if (t == TRAVERSE_CONTINUE
7845 && (traverse_mask & e_or_t) != 0)
7847 Type* tc = p->const_value()->type();
7849 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
7850 return TRAVERSE_EXIT;
7851 t = p->const_value()->traverse_expression(traverse);
7855 case Named_object::NAMED_OBJECT_VAR:
7856 case Named_object::NAMED_OBJECT_RESULT_VAR:
7857 if ((traverse_mask & Traverse::traverse_variables) != 0)
7858 t = traverse->variable(p);
7859 if (t == TRAVERSE_CONTINUE
7860 && (traverse_mask & e_or_t) != 0)
7862 if (p->is_result_variable()
7863 || p->var_value()->has_type())
7865 Type* tv = (p->is_variable()
7866 ? p->var_value()->type()
7867 : p->result_var_value()->type());
7869 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
7870 return TRAVERSE_EXIT;
7873 if (t == TRAVERSE_CONTINUE
7874 && (traverse_mask & e_or_t_or_s) != 0
7875 && p->is_variable())
7876 t = p->var_value()->traverse_expression(traverse, traverse_mask);
7879 case Named_object::NAMED_OBJECT_FUNC:
7880 if ((traverse_mask & Traverse::traverse_functions) != 0)
7881 t = traverse->function(p);
7883 if (t == TRAVERSE_CONTINUE
7885 & (Traverse::traverse_variables
7886 | Traverse::traverse_constants
7887 | Traverse::traverse_functions
7888 | Traverse::traverse_blocks
7889 | Traverse::traverse_statements
7890 | Traverse::traverse_expressions
7891 | Traverse::traverse_types)) != 0)
7892 t = p->func_value()->traverse(traverse);
7895 case Named_object::NAMED_OBJECT_PACKAGE:
7896 // These are traversed in Gogo::traverse.
7897 go_assert(is_global);
7900 case Named_object::NAMED_OBJECT_TYPE:
7901 if ((traverse_mask & e_or_t) != 0)
7902 t = Type::traverse(p->type_value(), traverse);
7905 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7906 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7907 case Named_object::NAMED_OBJECT_UNKNOWN:
7908 case Named_object::NAMED_OBJECT_ERRONEOUS:
7911 case Named_object::NAMED_OBJECT_SINK:
7916 if (t == TRAVERSE_EXIT)
7917 return TRAVERSE_EXIT;
7920 // If we need to traverse types, check the function declarations,
7921 // which have types. Also check any methods of a type declaration.
7922 if ((traverse_mask & e_or_t) != 0)
7924 for (Bindings::const_declarations_iterator p =
7925 this->begin_declarations();
7926 p != this->end_declarations();
7929 if (p->second->is_function_declaration())
7931 if (Type::traverse(p->second->func_declaration_value()->type(),
7934 return TRAVERSE_EXIT;
7936 else if (p->second->is_type_declaration())
7938 const std::vector<Named_object*>* methods =
7939 p->second->type_declaration_value()->methods();
7940 for (std::vector<Named_object*>::const_iterator pm =
7942 pm != methods->end();
7945 Named_object* no = *pm;
7947 if (no->is_function())
7948 t = no->func_value()->type();
7949 else if (no->is_function_declaration())
7950 t = no->func_declaration_value()->type();
7953 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
7954 return TRAVERSE_EXIT;
7960 return TRAVERSE_CONTINUE;
7965 // Clear any references to this label.
7970 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
7971 p != this->refs_.end();
7974 this->refs_.clear();
7977 // Get the backend representation for a label.
7980 Label::get_backend_label(Translate_context* context)
7982 if (this->blabel_ == NULL)
7984 Function* function = context->function()->func_value();
7985 Bfunction* bfunction = function->get_decl();
7986 this->blabel_ = context->backend()->label(bfunction, this->name_,
7989 return this->blabel_;
7992 // Return an expression for the address of this label.
7995 Label::get_addr(Translate_context* context, Location location)
7997 Blabel* label = this->get_backend_label(context);
7998 return context->backend()->label_address(label, location);
8001 // Return the dummy label that represents any instance of the blank label.
8004 Label::create_dummy_label()
8006 static Label* dummy_label;
8007 if (dummy_label == NULL)
8009 dummy_label = new Label("_");
8010 dummy_label->set_is_used();
8015 // Class Unnamed_label.
8017 // Get the backend representation for an unnamed label.
8020 Unnamed_label::get_blabel(Translate_context* context)
8022 if (this->blabel_ == NULL)
8024 Function* function = context->function()->func_value();
8025 Bfunction* bfunction = function->get_decl();
8026 this->blabel_ = context->backend()->label(bfunction, "",
8029 return this->blabel_;
8032 // Return a statement which defines this unnamed label.
8035 Unnamed_label::get_definition(Translate_context* context)
8037 Blabel* blabel = this->get_blabel(context);
8038 return context->backend()->label_definition_statement(blabel);
8041 // Return a goto statement to this unnamed label.
8044 Unnamed_label::get_goto(Translate_context* context, Location location)
8046 Blabel* blabel = this->get_blabel(context);
8047 return context->backend()->goto_statement(blabel, location);
8052 Package::Package(const std::string& pkgpath,
8053 const std::string& pkgpath_symbol, Location location)
8054 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
8055 package_name_(), bindings_(new Bindings(NULL)),
8058 go_assert(!pkgpath.empty());
8061 // Set the package name.
8064 Package::set_package_name(const std::string& package_name, Location location)
8066 go_assert(!package_name.empty());
8067 if (this->package_name_.empty())
8068 this->package_name_ = package_name;
8069 else if (this->package_name_ != package_name)
8070 go_error_at(location,
8071 ("saw two different packages with "
8072 "the same package path %s: %s, %s"),
8073 this->pkgpath_.c_str(), this->package_name_.c_str(),
8074 package_name.c_str());
8077 // Return the pkgpath symbol, which is a prefix for symbols defined in
8081 Package::pkgpath_symbol() const
8083 if (this->pkgpath_symbol_.empty())
8084 return Gogo::pkgpath_for_symbol(this->pkgpath_);
8085 return this->pkgpath_symbol_;
8088 // Set the package path symbol.
8091 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
8093 go_assert(!pkgpath_symbol.empty());
8094 if (this->pkgpath_symbol_.empty())
8095 this->pkgpath_symbol_ = pkgpath_symbol;
8097 go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
8100 // Note that symbol from this package was and qualified by ALIAS.
8103 Package::note_usage(const std::string& alias) const
8105 Aliases::const_iterator p = this->aliases_.find(alias);
8106 go_assert(p != this->aliases_.end());
8107 p->second->note_usage();
8110 // Forget a given usage. If forgetting this usage means this package becomes
8111 // unused, report that error.
8114 Package::forget_usage(Expression* usage) const
8116 if (this->fake_uses_.empty())
8119 std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
8120 go_assert(p != this->fake_uses_.end());
8121 this->fake_uses_.erase(p);
8123 if (this->fake_uses_.empty())
8124 go_error_at(this->location(), "imported and not used: %s",
8125 Gogo::message_name(this->package_name()).c_str());
8128 // Clear the used field for the next file. If the only usages of this package
8129 // are possibly fake, keep the fake usages for lowering.
8132 Package::clear_used()
8134 std::string dot_alias = "." + this->package_name();
8135 Aliases::const_iterator p = this->aliases_.find(dot_alias);
8136 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
8137 this->fake_uses_.clear();
8139 this->aliases_.clear();
8143 Package::add_alias(const std::string& alias, Location location)
8145 Aliases::const_iterator p = this->aliases_.find(alias);
8146 if (p == this->aliases_.end())
8148 std::pair<Aliases::iterator, bool> ret;
8149 ret = this->aliases_.insert(std::make_pair(alias,
8150 new Package_alias(location)));
8156 // Determine types of constants. Everything else in a package
8157 // (variables, function declarations) should already have a fixed
8158 // type. Constants may have abstract types.
8161 Package::determine_types()
8163 Bindings* bindings = this->bindings_;
8164 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
8165 p != bindings->end_definitions();
8168 if ((*p)->is_const())
8169 (*p)->const_value()->determine_type();
8177 Traverse::~Traverse()
8179 if (this->types_seen_ != NULL)
8180 delete this->types_seen_;
8181 if (this->expressions_seen_ != NULL)
8182 delete this->expressions_seen_;
8185 // Record that we are looking at a type, and return true if we have
8189 Traverse::remember_type(const Type* type)
8191 if (type->is_error_type())
8193 go_assert((this->traverse_mask() & traverse_types) != 0
8194 || (this->traverse_mask() & traverse_expressions) != 0);
8195 // We mostly only have to remember named types. But it turns out
8196 // that an interface type can refer to itself without using a name
8197 // by relying on interface inheritance, as in
8198 // type I interface { F() interface{I} }
8199 if (type->classification() != Type::TYPE_NAMED
8200 && type->classification() != Type::TYPE_INTERFACE)
8202 if (this->types_seen_ == NULL)
8203 this->types_seen_ = new Types_seen();
8204 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
8208 // Record that we are looking at an expression, and return true if we
8209 // have already seen it. NB: this routine used to assert if the traverse
8210 // mask did not include expressions/types -- this is no longer the case,
8211 // since it can be useful to remember specific expressions during
8212 // walks that only cover statements.
8215 Traverse::remember_expression(const Expression* expression)
8217 if (this->expressions_seen_ == NULL)
8218 this->expressions_seen_ = new Expressions_seen();
8219 std::pair<Expressions_seen::iterator, bool> ins =
8220 this->expressions_seen_->insert(expression);
8224 // The default versions of these functions should never be called: the
8225 // traversal mask indicates which functions may be called.
8228 Traverse::variable(Named_object*)
8234 Traverse::constant(Named_object*, bool)
8240 Traverse::function(Named_object*)
8246 Traverse::block(Block*)
8252 Traverse::statement(Block*, size_t*, Statement*)
8258 Traverse::expression(Expression**)
8264 Traverse::type(Type*)
8269 // Class Statement_inserter.
8272 Statement_inserter::insert(Statement* s)
8274 if (this->block_ != NULL)
8276 go_assert(this->pindex_ != NULL);
8277 this->block_->insert_statement_before(*this->pindex_, s);
8280 else if (this->var_ != NULL)
8281 this->var_->add_preinit_statement(this->gogo_, s);
8283 go_assert(saw_errors());