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.
13 #include "statements.h"
14 #include "expressions.h"
24 Gogo::Gogo(Backend* backend, Linemap* linemap, int int_type_size,
30 globals_(new Bindings(NULL)),
32 imported_unsafe_(false),
39 unique_prefix_specified_(false),
41 specific_type_functions_(),
42 specific_type_functions_are_written_(false),
43 named_types_are_converted_(false)
45 const Location loc = Linemap::predeclared_location();
47 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
48 RUNTIME_TYPE_KIND_UINT8);
49 this->add_named_type(uint8_type);
50 this->add_named_type(Type::make_integer_type("uint16", true, 16,
51 RUNTIME_TYPE_KIND_UINT16));
52 this->add_named_type(Type::make_integer_type("uint32", true, 32,
53 RUNTIME_TYPE_KIND_UINT32));
54 this->add_named_type(Type::make_integer_type("uint64", true, 64,
55 RUNTIME_TYPE_KIND_UINT64));
57 this->add_named_type(Type::make_integer_type("int8", false, 8,
58 RUNTIME_TYPE_KIND_INT8));
59 this->add_named_type(Type::make_integer_type("int16", false, 16,
60 RUNTIME_TYPE_KIND_INT16));
61 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
62 RUNTIME_TYPE_KIND_INT32);
63 this->add_named_type(int32_type);
64 this->add_named_type(Type::make_integer_type("int64", false, 64,
65 RUNTIME_TYPE_KIND_INT64));
67 this->add_named_type(Type::make_float_type("float32", 32,
68 RUNTIME_TYPE_KIND_FLOAT32));
69 this->add_named_type(Type::make_float_type("float64", 64,
70 RUNTIME_TYPE_KIND_FLOAT64));
72 this->add_named_type(Type::make_complex_type("complex64", 64,
73 RUNTIME_TYPE_KIND_COMPLEX64));
74 this->add_named_type(Type::make_complex_type("complex128", 128,
75 RUNTIME_TYPE_KIND_COMPLEX128));
77 if (int_type_size < 32)
79 this->add_named_type(Type::make_integer_type("uint", true,
81 RUNTIME_TYPE_KIND_UINT));
82 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
83 RUNTIME_TYPE_KIND_INT);
84 this->add_named_type(int_type);
86 this->add_named_type(Type::make_integer_type("uintptr", true,
88 RUNTIME_TYPE_KIND_UINTPTR));
90 // "byte" is an alias for "uint8".
91 uint8_type->integer_type()->set_is_byte();
92 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
94 this->add_named_type(byte_type->type_value());
96 // "rune" is an alias for "int32".
97 int32_type->integer_type()->set_is_rune();
98 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
100 this->add_named_type(rune_type->type_value());
102 this->add_named_type(Type::make_named_bool_type());
104 this->add_named_type(Type::make_named_string_type());
106 // "error" is interface { Error() string }.
108 Typed_identifier_list *methods = new Typed_identifier_list;
109 Typed_identifier_list *results = new Typed_identifier_list;
110 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
111 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
112 methods->push_back(Typed_identifier("Error", method_type, loc));
113 Interface_type *error_iface = Type::make_interface_type(methods, loc);
114 error_iface->finalize_methods();
115 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
116 this->add_named_type(error_type);
119 this->globals_->add_constant(Typed_identifier("true",
120 Type::make_boolean_type(),
123 Expression::make_boolean(true, loc),
125 this->globals_->add_constant(Typed_identifier("false",
126 Type::make_boolean_type(),
129 Expression::make_boolean(false, loc),
132 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
135 Expression::make_nil(loc),
138 Type* abstract_int_type = Type::make_abstract_integer_type();
139 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
142 Expression::make_iota(),
145 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
146 new_type->set_is_varargs();
147 new_type->set_is_builtin();
148 this->globals_->add_function_declaration("new", NULL, new_type, loc);
150 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
151 make_type->set_is_varargs();
152 make_type->set_is_builtin();
153 this->globals_->add_function_declaration("make", NULL, make_type, loc);
155 Typed_identifier_list* len_result = new Typed_identifier_list();
156 len_result->push_back(Typed_identifier("", int_type, loc));
157 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
159 len_type->set_is_builtin();
160 this->globals_->add_function_declaration("len", NULL, len_type, loc);
162 Typed_identifier_list* cap_result = new Typed_identifier_list();
163 cap_result->push_back(Typed_identifier("", int_type, loc));
164 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
166 cap_type->set_is_builtin();
167 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
169 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
170 print_type->set_is_varargs();
171 print_type->set_is_builtin();
172 this->globals_->add_function_declaration("print", NULL, print_type, loc);
174 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
175 print_type->set_is_varargs();
176 print_type->set_is_builtin();
177 this->globals_->add_function_declaration("println", NULL, print_type, loc);
179 Type *empty = Type::make_empty_interface_type(loc);
180 Typed_identifier_list* panic_parms = new Typed_identifier_list();
181 panic_parms->push_back(Typed_identifier("e", empty, loc));
182 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
184 panic_type->set_is_builtin();
185 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
187 Typed_identifier_list* recover_result = new Typed_identifier_list();
188 recover_result->push_back(Typed_identifier("", empty, loc));
189 Function_type* recover_type = Type::make_function_type(NULL, NULL,
192 recover_type->set_is_builtin();
193 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
195 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
196 close_type->set_is_varargs();
197 close_type->set_is_builtin();
198 this->globals_->add_function_declaration("close", NULL, close_type, loc);
200 Typed_identifier_list* copy_result = new Typed_identifier_list();
201 copy_result->push_back(Typed_identifier("", int_type, loc));
202 Function_type* copy_type = Type::make_function_type(NULL, NULL,
204 copy_type->set_is_varargs();
205 copy_type->set_is_builtin();
206 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
208 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
209 append_type->set_is_varargs();
210 append_type->set_is_builtin();
211 this->globals_->add_function_declaration("append", NULL, append_type, loc);
213 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
214 complex_type->set_is_varargs();
215 complex_type->set_is_builtin();
216 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
218 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
219 real_type->set_is_varargs();
220 real_type->set_is_builtin();
221 this->globals_->add_function_declaration("real", NULL, real_type, loc);
223 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
224 imag_type->set_is_varargs();
225 imag_type->set_is_builtin();
226 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
228 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
229 delete_type->set_is_varargs();
230 delete_type->set_is_builtin();
231 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
234 // Munge name for use in an error message.
237 Gogo::message_name(const std::string& name)
239 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
242 // Get the package name.
245 Gogo::package_name() const
247 go_assert(this->package_ != NULL);
248 return this->package_->name();
251 // Set the package name.
254 Gogo::set_package_name(const std::string& package_name,
257 if (this->package_ != NULL && this->package_->name() != package_name)
259 error_at(location, "expected package %<%s%>",
260 Gogo::message_name(this->package_->name()).c_str());
264 // If the user did not specify a unique prefix, we always use "go".
265 // This in effect requires that the package name be unique.
266 if (this->unique_prefix_.empty())
267 this->unique_prefix_ = "go";
269 this->package_ = this->register_package(package_name, this->unique_prefix_,
272 // We used to permit people to qualify symbols with the current
273 // package name (e.g., P.x), but we no longer do.
274 // this->globals_->add_package(package_name, this->package_);
276 if (this->is_main_package())
278 // Declare "main" as a function which takes no parameters and
280 Location uloc = Linemap::unknown_location();
281 this->declare_function("main",
282 Type::make_function_type (NULL, NULL, NULL, uloc),
287 // Return whether this is the "main" package. This is not true if
288 // -fgo-prefix was used.
291 Gogo::is_main_package() const
293 return this->package_name() == "main" && !this->unique_prefix_specified_;
299 Gogo::import_package(const std::string& filename,
300 const std::string& local_name,
301 bool is_local_name_exported,
304 if (filename == "unsafe")
306 this->import_unsafe(local_name, is_local_name_exported, location);
310 Imports::const_iterator p = this->imports_.find(filename);
311 if (p != this->imports_.end())
313 Package* package = p->second;
314 package->set_location(location);
315 package->set_is_imported();
316 std::string ln = local_name;
317 bool is_ln_exported = is_local_name_exported;
320 ln = package->name();
321 is_ln_exported = Lex::is_exported_name(ln);
325 Bindings* bindings = package->bindings();
326 for (Bindings::const_declarations_iterator p =
327 bindings->begin_declarations();
328 p != bindings->end_declarations();
330 this->add_named_object(p->second);
333 package->set_uses_sink_alias();
336 ln = this->pack_hidden_name(ln, is_ln_exported);
337 this->package_->bindings()->add_package(ln, package);
342 Import::Stream* stream = Import::open_package(filename, location);
345 error_at(location, "import file %qs not found", filename.c_str());
349 Import imp(stream, location);
350 imp.register_builtin_types(this);
351 Package* package = imp.import(this, local_name, is_local_name_exported);
354 if (package->name() == this->package_name()
355 && package->unique_prefix() == this->unique_prefix())
357 ("imported package uses same package name and prefix "
358 "as package being compiled (see -fgo-prefix option)"));
360 this->imports_.insert(std::make_pair(filename, package));
361 package->set_is_imported();
367 // Add an import control function for an imported package to the list.
370 Gogo::add_import_init_fn(const std::string& package_name,
371 const std::string& init_name, int prio)
373 for (std::set<Import_init>::const_iterator p =
374 this->imported_init_fns_.begin();
375 p != this->imported_init_fns_.end();
378 if (p->init_name() == init_name
379 && (p->package_name() != package_name || p->priority() != prio))
381 error("duplicate package initialization name %qs",
382 Gogo::message_name(init_name).c_str());
383 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
384 Gogo::message_name(p->package_name()).c_str(),
386 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
387 Gogo::message_name(package_name).c_str(), prio);
392 this->imported_init_fns_.insert(Import_init(package_name, init_name,
396 // Return whether we are at the global binding level.
399 Gogo::in_global_scope() const
401 return this->functions_.empty();
404 // Return the current binding contour.
407 Gogo::current_bindings()
409 if (!this->functions_.empty())
410 return this->functions_.back().blocks.back()->bindings();
411 else if (this->package_ != NULL)
412 return this->package_->bindings();
414 return this->globals_;
418 Gogo::current_bindings() const
420 if (!this->functions_.empty())
421 return this->functions_.back().blocks.back()->bindings();
422 else if (this->package_ != NULL)
423 return this->package_->bindings();
425 return this->globals_;
428 // Return the current block.
431 Gogo::current_block()
433 if (this->functions_.empty())
436 return this->functions_.back().blocks.back();
439 // Look up a name in the current binding contour. If PFUNCTION is not
440 // NULL, set it to the function in which the name is defined, or NULL
441 // if the name is defined in global scope.
444 Gogo::lookup(const std::string& name, Named_object** pfunction) const
446 if (pfunction != NULL)
449 if (Gogo::is_sink_name(name))
450 return Named_object::make_sink();
452 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
453 p != this->functions_.rend();
456 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
459 if (pfunction != NULL)
460 *pfunction = p->function;
465 if (this->package_ != NULL)
467 Named_object* ret = this->package_->bindings()->lookup(name);
470 if (ret->package() != NULL)
471 ret->package()->set_used();
476 // We do not look in the global namespace. If we did, the global
477 // namespace would effectively hide names which were defined in
478 // package scope which we have not yet seen. Instead,
479 // define_global_names is called after parsing is over to connect
480 // undefined names at package scope with names defined at global
486 // Look up a name in the current block, without searching enclosing
490 Gogo::lookup_in_block(const std::string& name) const
492 go_assert(!this->functions_.empty());
493 go_assert(!this->functions_.back().blocks.empty());
494 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
497 // Look up a name in the global namespace.
500 Gogo::lookup_global(const char* name) const
502 return this->globals_->lookup(name);
505 // Add an imported package.
508 Gogo::add_imported_package(const std::string& real_name,
509 const std::string& alias_arg,
510 bool is_alias_exported,
511 const std::string& unique_prefix,
513 bool* padd_to_globals)
515 // FIXME: Now that we compile packages as a whole, should we permit
516 // importing the current package?
517 if (this->package_name() == real_name
518 && this->unique_prefix() == unique_prefix)
520 *padd_to_globals = false;
521 if (!alias_arg.empty() && alias_arg != ".")
523 std::string alias = this->pack_hidden_name(alias_arg,
525 this->package_->bindings()->add_package(alias, this->package_);
527 return this->package_;
529 else if (alias_arg == ".")
531 *padd_to_globals = true;
532 return this->register_package(real_name, unique_prefix, location);
534 else if (alias_arg == "_")
536 Package* ret = this->register_package(real_name, unique_prefix, location);
537 ret->set_uses_sink_alias();
542 *padd_to_globals = false;
543 std::string alias = alias_arg;
547 is_alias_exported = Lex::is_exported_name(alias);
549 alias = this->pack_hidden_name(alias, is_alias_exported);
550 Named_object* no = this->add_package(real_name, alias, unique_prefix,
552 if (!no->is_package())
554 return no->package_value();
561 Gogo::add_package(const std::string& real_name, const std::string& alias,
562 const std::string& unique_prefix, Location location)
564 go_assert(this->in_global_scope());
566 // Register the package. Note that we might have already seen it in
567 // an earlier import.
568 Package* package = this->register_package(real_name, unique_prefix, location);
570 return this->package_->bindings()->add_package(alias, package);
573 // Register a package. This package may or may not be imported. This
574 // returns the Package structure for the package, creating if it
578 Gogo::register_package(const std::string& package_name,
579 const std::string& unique_prefix,
582 go_assert(!unique_prefix.empty() && !package_name.empty());
583 std::string name = unique_prefix + '.' + package_name;
584 Package* package = NULL;
585 std::pair<Packages::iterator, bool> ins =
586 this->packages_.insert(std::make_pair(name, package));
589 // We have seen this package name before.
590 package = ins.first->second;
591 go_assert(package != NULL);
592 go_assert(package->name() == package_name
593 && package->unique_prefix() == unique_prefix);
594 if (Linemap::is_unknown_location(package->location()))
595 package->set_location(location);
599 // First time we have seen this package name.
600 package = new Package(package_name, unique_prefix, location);
601 go_assert(ins.first->second == NULL);
602 ins.first->second = package;
608 // Start compiling a function.
611 Gogo::start_function(const std::string& name, Function_type* type,
612 bool add_method_to_type, Location location)
614 bool at_top_level = this->functions_.empty();
616 Block* block = new Block(NULL, location);
618 Function* enclosing = (at_top_level
620 : this->functions_.back().function->func_value());
622 Function* function = new Function(type, enclosing, block, location);
624 if (type->is_method())
626 const Typed_identifier* receiver = type->receiver();
627 Variable* this_param = new Variable(receiver->type(), NULL, false,
628 true, true, location);
629 std::string name = receiver->name();
632 // We need to give receivers a name since they wind up in
633 // DECL_ARGUMENTS. FIXME.
634 static unsigned int count;
636 snprintf(buf, sizeof buf, "r.%u", count);
640 if (!Gogo::is_sink_name(name))
641 block->bindings()->add_variable(name, NULL, this_param);
644 const Typed_identifier_list* parameters = type->parameters();
645 bool is_varargs = type->is_varargs();
646 if (parameters != NULL)
648 for (Typed_identifier_list::const_iterator p = parameters->begin();
649 p != parameters->end();
652 Variable* param = new Variable(p->type(), NULL, false, true, false,
654 if (is_varargs && p + 1 == parameters->end())
655 param->set_is_varargs_parameter();
657 std::string name = p->name();
658 if (name.empty() || Gogo::is_sink_name(name))
660 // We need to give parameters a name since they wind up
661 // in DECL_ARGUMENTS. FIXME.
662 static unsigned int count;
664 snprintf(buf, sizeof buf, "p.%u", count);
668 block->bindings()->add_variable(name, NULL, param);
672 function->create_result_variables(this);
674 const std::string* pname;
675 std::string nested_name;
676 bool is_init = false;
677 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
679 if ((type->parameters() != NULL && !type->parameters()->empty())
680 || (type->results() != NULL && !type->results()->empty()))
682 "func init must have no arguments and no return values");
683 // There can be multiple "init" functions, so give them each a
685 static int init_count;
687 snprintf(buf, sizeof buf, ".$init%d", init_count);
690 pname = &nested_name;
693 else if (!name.empty())
697 // Invent a name for a nested function.
698 static int nested_count;
700 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
703 pname = &nested_name;
707 if (Gogo::is_sink_name(*pname))
709 static int sink_count;
711 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
713 ret = Named_object::make_function(buf, NULL, function);
715 else if (!type->is_method())
717 ret = this->package_->bindings()->add_function(*pname, NULL, function);
718 if (!ret->is_function() || ret->func_value() != function)
720 // Redefinition error. Invent a name to avoid knockon
722 static int redefinition_count;
724 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
725 ++redefinition_count;
726 ret = this->package_->bindings()->add_function(buf, NULL, function);
731 if (!add_method_to_type)
732 ret = Named_object::make_function(name, NULL, function);
735 go_assert(at_top_level);
736 Type* rtype = type->receiver()->type();
738 // We want to look through the pointer created by the
739 // parser, without getting an error if the type is not yet
741 if (rtype->classification() == Type::TYPE_POINTER)
742 rtype = rtype->points_to();
744 if (rtype->is_error_type())
745 ret = Named_object::make_function(name, NULL, function);
746 else if (rtype->named_type() != NULL)
748 ret = rtype->named_type()->add_method(name, function);
749 if (!ret->is_function())
751 // Redefinition error.
752 ret = Named_object::make_function(name, NULL, function);
755 else if (rtype->forward_declaration_type() != NULL)
757 Named_object* type_no =
758 rtype->forward_declaration_type()->named_object();
759 if (type_no->is_unknown())
761 // If we are seeing methods it really must be a
762 // type. Declare it as such. An alternative would
763 // be to support lists of methods for unknown
764 // expressions. Either way the error messages if
765 // this is not a type are going to get confusing.
766 Named_object* declared =
767 this->declare_package_type(type_no->name(),
768 type_no->location());
770 == type_no->unknown_value()->real_named_object());
772 ret = rtype->forward_declaration_type()->add_method(name,
778 this->package_->bindings()->add_method(ret);
781 this->functions_.resize(this->functions_.size() + 1);
782 Open_function& of(this->functions_.back());
784 of.blocks.push_back(block);
788 this->init_functions_.push_back(ret);
789 this->need_init_fn_ = true;
795 // Finish compiling a function.
798 Gogo::finish_function(Location location)
800 this->finish_block(location);
801 go_assert(this->functions_.back().blocks.empty());
802 this->functions_.pop_back();
805 // Return the current function.
808 Gogo::current_function() const
810 go_assert(!this->functions_.empty());
811 return this->functions_.back().function;
814 // Start a new block.
817 Gogo::start_block(Location location)
819 go_assert(!this->functions_.empty());
820 Block* block = new Block(this->current_block(), location);
821 this->functions_.back().blocks.push_back(block);
827 Gogo::finish_block(Location location)
829 go_assert(!this->functions_.empty());
830 go_assert(!this->functions_.back().blocks.empty());
831 Block* block = this->functions_.back().blocks.back();
832 this->functions_.back().blocks.pop_back();
833 block->set_end_location(location);
837 // Add an unknown name.
840 Gogo::add_unknown_name(const std::string& name, Location location)
842 return this->package_->bindings()->add_unknown_name(name, location);
845 // Declare a function.
848 Gogo::declare_function(const std::string& name, Function_type* type,
851 if (!type->is_method())
852 return this->current_bindings()->add_function_declaration(name, NULL, type,
856 // We don't bother to add this to the list of global
858 Type* rtype = type->receiver()->type();
860 // We want to look through the pointer created by the
861 // parser, without getting an error if the type is not yet
863 if (rtype->classification() == Type::TYPE_POINTER)
864 rtype = rtype->points_to();
866 if (rtype->is_error_type())
868 else if (rtype->named_type() != NULL)
869 return rtype->named_type()->add_method_declaration(name, NULL, type,
871 else if (rtype->forward_declaration_type() != NULL)
873 Forward_declaration_type* ftype = rtype->forward_declaration_type();
874 return ftype->add_method_declaration(name, type, location);
881 // Add a label definition.
884 Gogo::add_label_definition(const std::string& label_name,
887 go_assert(!this->functions_.empty());
888 Function* func = this->functions_.back().function->func_value();
889 Label* label = func->add_label_definition(this, label_name, location);
890 this->add_statement(Statement::make_label_statement(label, location));
894 // Add a label reference.
897 Gogo::add_label_reference(const std::string& label_name,
898 Location location, bool issue_goto_errors)
900 go_assert(!this->functions_.empty());
901 Function* func = this->functions_.back().function->func_value();
902 return func->add_label_reference(this, label_name, location,
906 // Return the current binding state.
909 Gogo::bindings_snapshot(Location location)
911 return new Bindings_snapshot(this->current_block(), location);
917 Gogo::add_statement(Statement* statement)
919 go_assert(!this->functions_.empty()
920 && !this->functions_.back().blocks.empty());
921 this->functions_.back().blocks.back()->add_statement(statement);
927 Gogo::add_block(Block* block, Location location)
929 go_assert(!this->functions_.empty()
930 && !this->functions_.back().blocks.empty());
931 Statement* statement = Statement::make_block_statement(block, location);
932 this->functions_.back().blocks.back()->add_statement(statement);
938 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
941 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
947 Gogo::add_type(const std::string& name, Type* type, Location location)
949 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
951 if (!this->in_global_scope() && no->is_type())
952 no->type_value()->set_in_function(this->functions_.back().function);
958 Gogo::add_named_type(Named_type* type)
960 go_assert(this->in_global_scope());
961 this->current_bindings()->add_named_type(type);
967 Gogo::declare_type(const std::string& name, Location location)
969 Bindings* bindings = this->current_bindings();
970 Named_object* no = bindings->add_type_declaration(name, NULL, location);
971 if (!this->in_global_scope() && no->is_type_declaration())
973 Named_object* f = this->functions_.back().function;
974 no->type_declaration_value()->set_in_function(f);
979 // Declare a type at the package level.
982 Gogo::declare_package_type(const std::string& name, Location location)
984 return this->package_->bindings()->add_type_declaration(name, NULL, location);
987 // Declare a function at the package level.
990 Gogo::declare_package_function(const std::string& name, Function_type* type,
993 return this->package_->bindings()->add_function_declaration(name, NULL, type,
997 // Define a type which was already declared.
1000 Gogo::define_type(Named_object* no, Named_type* type)
1002 this->current_bindings()->define_type(no, type);
1008 Gogo::add_variable(const std::string& name, Variable* variable)
1010 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1013 // In a function the middle-end wants to see a DECL_EXPR node.
1015 && no->is_variable()
1016 && !no->var_value()->is_parameter()
1017 && !this->functions_.empty())
1018 this->add_statement(Statement::make_variable_declaration(no));
1023 // Add a sink--a reference to the blank identifier _.
1028 return Named_object::make_sink();
1031 // Add a named object.
1034 Gogo::add_named_object(Named_object* no)
1036 this->current_bindings()->add_named_object(no);
1039 // Mark all local variables used. This is used when some types of
1040 // parse error occur.
1043 Gogo::mark_locals_used()
1045 for (Open_functions::iterator pf = this->functions_.begin();
1046 pf != this->functions_.end();
1049 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1050 pb != pf->blocks.end();
1052 (*pb)->bindings()->mark_locals_used();
1056 // Record that we've seen an interface type.
1059 Gogo::record_interface_type(Interface_type* itype)
1061 this->interface_types_.push_back(itype);
1064 // Return a name for a thunk object.
1069 static int thunk_count;
1070 char thunk_name[50];
1071 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1076 // Return whether a function is a thunk.
1079 Gogo::is_thunk(const Named_object* no)
1081 return no->name().compare(0, 6, "$thunk") == 0;
1084 // Define the global names. We do this only after parsing all the
1085 // input files, because the program might define the global names
1089 Gogo::define_global_names()
1091 for (Bindings::const_declarations_iterator p =
1092 this->globals_->begin_declarations();
1093 p != this->globals_->end_declarations();
1096 Named_object* global_no = p->second;
1097 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1098 Named_object* no = this->package_->bindings()->lookup(name);
1102 if (no->is_type_declaration())
1104 if (global_no->is_type())
1106 if (no->type_declaration_value()->has_methods())
1107 error_at(no->location(),
1108 "may not define methods for global type");
1109 no->set_type_value(global_no->type_value());
1113 error_at(no->location(), "expected type");
1114 Type* errtype = Type::make_error_type();
1116 Named_object::make_type("erroneous_type", NULL, errtype,
1117 Linemap::predeclared_location());
1118 no->set_type_value(err->type_value());
1121 else if (no->is_unknown())
1122 no->unknown_value()->set_real_named_object(global_no);
1126 // Clear out names in file scope.
1129 Gogo::clear_file_scope()
1131 this->package_->bindings()->clear_file_scope();
1133 // Warn about packages which were imported but not used.
1134 for (Packages::iterator p = this->packages_.begin();
1135 p != this->packages_.end();
1138 Package* package = p->second;
1139 if (package != this->package_
1140 && package->is_imported()
1142 && !package->uses_sink_alias()
1144 error_at(package->location(), "imported and not used: %s",
1145 Gogo::message_name(package->name()).c_str());
1146 package->clear_is_imported();
1147 package->clear_uses_sink_alias();
1148 package->clear_used();
1152 // Queue up a type specific function for later writing. These are
1153 // written out in write_specific_type_functions, called after the
1154 // parse tree is lowered.
1157 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1158 const std::string& hash_name,
1159 Function_type* hash_fntype,
1160 const std::string& equal_name,
1161 Function_type* equal_fntype)
1163 go_assert(!this->specific_type_functions_are_written_);
1164 go_assert(!this->in_global_scope());
1165 Specific_type_function* tsf = new Specific_type_function(type, name,
1170 this->specific_type_functions_.push_back(tsf);
1173 // Look for types which need specific hash or equality functions.
1175 class Specific_type_functions : public Traverse
1178 Specific_type_functions(Gogo* gogo)
1179 : Traverse(traverse_types),
1191 Specific_type_functions::type(Type* t)
1193 Named_object* hash_fn;
1194 Named_object* equal_fn;
1195 switch (t->classification())
1197 case Type::TYPE_NAMED:
1199 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1200 t->type_functions(this->gogo_, t->named_type(), NULL, NULL, &hash_fn,
1203 // If this is a struct type, we don't want to make functions
1204 // for the unnamed struct.
1205 Type* rt = t->named_type()->real_type();
1206 if (rt->struct_type() == NULL)
1208 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1209 return TRAVERSE_EXIT;
1213 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1214 return TRAVERSE_EXIT;
1217 return TRAVERSE_SKIP_COMPONENTS;
1220 case Type::TYPE_STRUCT:
1221 case Type::TYPE_ARRAY:
1222 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1223 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1230 return TRAVERSE_CONTINUE;
1233 // Write out type specific functions.
1236 Gogo::write_specific_type_functions()
1238 Specific_type_functions stf(this);
1239 this->traverse(&stf);
1241 while (!this->specific_type_functions_.empty())
1243 Specific_type_function* tsf = this->specific_type_functions_.back();
1244 this->specific_type_functions_.pop_back();
1245 tsf->type->write_specific_type_functions(this, tsf->name,
1252 this->specific_type_functions_are_written_ = true;
1255 // Traverse the tree.
1258 Gogo::traverse(Traverse* traverse)
1260 // Traverse the current package first for consistency. The other
1261 // packages will only contain imported types, constants, and
1263 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1265 for (Packages::const_iterator p = this->packages_.begin();
1266 p != this->packages_.end();
1269 if (p->second != this->package_)
1271 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1277 // Traversal class used to verify types.
1279 class Verify_types : public Traverse
1283 : Traverse(traverse_types)
1290 // Verify that a type is correct.
1293 Verify_types::type(Type* t)
1296 return TRAVERSE_SKIP_COMPONENTS;
1297 return TRAVERSE_CONTINUE;
1300 // Verify that all types are correct.
1303 Gogo::verify_types()
1305 Verify_types traverse;
1306 this->traverse(&traverse);
1309 // Traversal class used to lower parse tree.
1311 class Lower_parse_tree : public Traverse
1314 Lower_parse_tree(Gogo* gogo, Named_object* function)
1315 : Traverse(traverse_variables
1316 | traverse_constants
1317 | traverse_functions
1318 | traverse_statements
1319 | traverse_expressions),
1320 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1324 set_inserter(const Statement_inserter* inserter)
1325 { this->inserter_ = *inserter; }
1328 variable(Named_object*);
1331 constant(Named_object*, bool);
1334 function(Named_object*);
1337 statement(Block*, size_t* pindex, Statement*);
1340 expression(Expression**);
1345 // The function we are traversing.
1346 Named_object* function_;
1347 // Value to use for the predeclared constant iota.
1349 // Current statement inserter for use by expressions.
1350 Statement_inserter inserter_;
1356 Lower_parse_tree::variable(Named_object* no)
1358 if (!no->is_variable())
1359 return TRAVERSE_CONTINUE;
1361 if (no->is_variable() && no->var_value()->is_global())
1363 // Global variables can have loops in their initialization
1364 // expressions. This is handled in lower_init_expression.
1365 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1367 return TRAVERSE_CONTINUE;
1370 // This is a local variable. We are going to return
1371 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1372 // initialization expression when we reach the variable declaration
1373 // statement. However, that means that we need to traverse the type
1375 if (no->var_value()->has_type())
1377 Type* type = no->var_value()->type();
1380 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1381 return TRAVERSE_EXIT;
1384 go_assert(!no->var_value()->has_pre_init());
1386 return TRAVERSE_SKIP_COMPONENTS;
1389 // Lower constants. We handle constants specially so that we can set
1390 // the right value for the predeclared constant iota. This works in
1391 // conjunction with the way we lower Const_expression objects.
1394 Lower_parse_tree::constant(Named_object* no, bool)
1396 Named_constant* nc = no->const_value();
1398 // Don't get into trouble if the constant's initializer expression
1399 // refers to the constant itself.
1401 return TRAVERSE_CONTINUE;
1404 go_assert(this->iota_value_ == -1);
1405 this->iota_value_ = nc->iota_value();
1406 nc->traverse_expression(this);
1407 this->iota_value_ = -1;
1409 nc->clear_lowering();
1411 // We will traverse the expression a second time, but that will be
1414 return TRAVERSE_CONTINUE;
1417 // Lower function closure types. Record the function while lowering
1418 // it, so that we can pass it down when lowering an expression.
1421 Lower_parse_tree::function(Named_object* no)
1423 no->func_value()->set_closure_type();
1425 go_assert(this->function_ == NULL);
1426 this->function_ = no;
1427 int t = no->func_value()->traverse(this);
1428 this->function_ = NULL;
1430 if (t == TRAVERSE_EXIT)
1432 return TRAVERSE_SKIP_COMPONENTS;
1435 // Lower statement parse trees.
1438 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1440 // Because we explicitly traverse the statement's contents
1441 // ourselves, we want to skip block statements here. There is
1442 // nothing to lower in a block statement.
1443 if (sorig->is_block_statement())
1444 return TRAVERSE_CONTINUE;
1446 Statement_inserter hold_inserter(this->inserter_);
1447 this->inserter_ = Statement_inserter(block, pindex);
1449 // Lower the expressions first.
1450 int t = sorig->traverse_contents(this);
1451 if (t == TRAVERSE_EXIT)
1453 this->inserter_ = hold_inserter;
1457 // Keep lowering until nothing changes.
1458 Statement* s = sorig;
1461 Statement* snew = s->lower(this->gogo_, this->function_, block,
1466 t = s->traverse_contents(this);
1467 if (t == TRAVERSE_EXIT)
1469 this->inserter_ = hold_inserter;
1475 block->replace_statement(*pindex, s);
1477 this->inserter_ = hold_inserter;
1478 return TRAVERSE_SKIP_COMPONENTS;
1481 // Lower expression parse trees.
1484 Lower_parse_tree::expression(Expression** pexpr)
1486 // We have to lower all subexpressions first, so that we can get
1487 // their type if necessary. This is awkward, because we don't have
1488 // a postorder traversal pass.
1489 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1490 return TRAVERSE_EXIT;
1491 // Keep lowering until nothing changes.
1494 Expression* e = *pexpr;
1495 Expression* enew = e->lower(this->gogo_, this->function_,
1496 &this->inserter_, this->iota_value_);
1501 return TRAVERSE_SKIP_COMPONENTS;
1504 // Lower the parse tree. This is called after the parse is complete,
1505 // when all names should be resolved.
1508 Gogo::lower_parse_tree()
1510 Lower_parse_tree lower_parse_tree(this, NULL);
1511 this->traverse(&lower_parse_tree);
1517 Gogo::lower_block(Named_object* function, Block* block)
1519 Lower_parse_tree lower_parse_tree(this, function);
1520 block->traverse(&lower_parse_tree);
1523 // Lower an expression. INSERTER may be NULL, in which case the
1524 // expression had better not need to create any temporaries.
1527 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1530 Lower_parse_tree lower_parse_tree(this, function);
1531 if (inserter != NULL)
1532 lower_parse_tree.set_inserter(inserter);
1533 lower_parse_tree.expression(pexpr);
1536 // Lower a constant. This is called when lowering a reference to a
1537 // constant. We have to make sure that the constant has already been
1541 Gogo::lower_constant(Named_object* no)
1543 go_assert(no->is_const());
1544 Lower_parse_tree lower(this, NULL);
1545 lower.constant(no, false);
1548 // Look for interface types to finalize methods of inherited
1551 class Finalize_methods : public Traverse
1554 Finalize_methods(Gogo* gogo)
1555 : Traverse(traverse_types),
1566 // Finalize the methods of an interface type.
1569 Finalize_methods::type(Type* t)
1571 // Check the classification so that we don't finalize the methods
1572 // twice for a named interface type.
1573 switch (t->classification())
1575 case Type::TYPE_INTERFACE:
1576 t->interface_type()->finalize_methods();
1579 case Type::TYPE_NAMED:
1581 // We have to finalize the methods of the real type first.
1582 // But if the real type is a struct type, then we only want to
1583 // finalize the methods of the field types, not of the struct
1584 // type itself. We don't want to add methods to the struct,
1585 // since it has a name.
1586 Named_type* nt = t->named_type();
1587 Type* rt = nt->real_type();
1588 if (rt->classification() != Type::TYPE_STRUCT)
1590 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1591 return TRAVERSE_EXIT;
1595 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1596 return TRAVERSE_EXIT;
1599 nt->finalize_methods(this->gogo_);
1601 // If this type is defined in a different package, then finalize the
1602 // types of all the methods, since we won't see them otherwise.
1603 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1605 const Methods* methods = nt->methods();
1606 for (Methods::const_iterator p = methods->begin();
1607 p != methods->end();
1610 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1611 return TRAVERSE_EXIT;
1615 return TRAVERSE_SKIP_COMPONENTS;
1618 case Type::TYPE_STRUCT:
1619 t->struct_type()->finalize_methods(this->gogo_);
1626 return TRAVERSE_CONTINUE;
1629 // Finalize method lists and build stub methods for types.
1632 Gogo::finalize_methods()
1634 Finalize_methods finalize(this);
1635 this->traverse(&finalize);
1638 // Set types for unspecified variables and constants.
1641 Gogo::determine_types()
1643 Bindings* bindings = this->current_bindings();
1644 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1645 p != bindings->end_definitions();
1648 if ((*p)->is_function())
1649 (*p)->func_value()->determine_types();
1650 else if ((*p)->is_variable())
1651 (*p)->var_value()->determine_type();
1652 else if ((*p)->is_const())
1653 (*p)->const_value()->determine_type();
1655 // See if a variable requires us to build an initialization
1656 // function. We know that we will see all global variables
1658 if (!this->need_init_fn_ && (*p)->is_variable())
1660 Variable* variable = (*p)->var_value();
1662 // If this is a global variable which requires runtime
1663 // initialization, we need an initialization function.
1664 if (!variable->is_global())
1666 else if (variable->init() == NULL)
1668 else if (variable->type()->interface_type() != NULL)
1669 this->need_init_fn_ = true;
1670 else if (variable->init()->is_constant())
1672 else if (!variable->init()->is_composite_literal())
1673 this->need_init_fn_ = true;
1674 else if (variable->init()->is_nonconstant_composite_literal())
1675 this->need_init_fn_ = true;
1677 // If this is a global variable which holds a pointer value,
1678 // then we need an initialization function to register it as a
1680 if (variable->is_global() && variable->type()->has_pointer())
1681 this->need_init_fn_ = true;
1685 // Determine the types of constants in packages.
1686 for (Packages::const_iterator p = this->packages_.begin();
1687 p != this->packages_.end();
1689 p->second->determine_types();
1692 // Traversal class used for type checking.
1694 class Check_types_traverse : public Traverse
1697 Check_types_traverse(Gogo* gogo)
1698 : Traverse(traverse_variables
1699 | traverse_constants
1700 | traverse_functions
1701 | traverse_statements
1702 | traverse_expressions),
1707 variable(Named_object*);
1710 constant(Named_object*, bool);
1713 function(Named_object*);
1716 statement(Block*, size_t* pindex, Statement*);
1719 expression(Expression**);
1726 // Check that a variable initializer has the right type.
1729 Check_types_traverse::variable(Named_object* named_object)
1731 if (named_object->is_variable())
1733 Variable* var = named_object->var_value();
1735 // Give error if variable type is not defined.
1736 var->type()->base();
1738 Expression* init = var->init();
1741 && !Type::are_assignable(var->type(), init->type(), &reason))
1744 error_at(var->location(), "incompatible type in initialization");
1746 error_at(var->location(),
1747 "incompatible type in initialization (%s)",
1751 else if (!var->is_used()
1752 && !var->is_global()
1753 && !var->is_parameter()
1754 && !var->is_receiver()
1755 && !var->type()->is_error()
1756 && (init == NULL || !init->is_error_expression())
1757 && !Lex::is_invalid_identifier(named_object->name()))
1758 error_at(var->location(), "%qs declared and not used",
1759 named_object->message_name().c_str());
1761 return TRAVERSE_CONTINUE;
1764 // Check that a constant initializer has the right type.
1767 Check_types_traverse::constant(Named_object* named_object, bool)
1769 Named_constant* constant = named_object->const_value();
1770 Type* ctype = constant->type();
1771 if (ctype->integer_type() == NULL
1772 && ctype->float_type() == NULL
1773 && ctype->complex_type() == NULL
1774 && !ctype->is_boolean_type()
1775 && !ctype->is_string_type())
1777 if (ctype->is_nil_type())
1778 error_at(constant->location(), "const initializer cannot be nil");
1779 else if (!ctype->is_error())
1780 error_at(constant->location(), "invalid constant type");
1781 constant->set_error();
1783 else if (!constant->expr()->is_constant())
1785 error_at(constant->expr()->location(), "expression is not constant");
1786 constant->set_error();
1788 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1791 error_at(constant->location(),
1792 "initialization expression has wrong type");
1793 constant->set_error();
1795 return TRAVERSE_CONTINUE;
1798 // There are no types to check in a function, but this is where we
1799 // issue warnings about labels which are defined but not referenced.
1802 Check_types_traverse::function(Named_object* no)
1804 no->func_value()->check_labels();
1805 return TRAVERSE_CONTINUE;
1808 // Check that types are valid in a statement.
1811 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1813 s->check_types(this->gogo_);
1814 return TRAVERSE_CONTINUE;
1817 // Check that types are valid in an expression.
1820 Check_types_traverse::expression(Expression** expr)
1822 (*expr)->check_types(this->gogo_);
1823 return TRAVERSE_CONTINUE;
1826 // Check that types are valid.
1831 Check_types_traverse traverse(this);
1832 this->traverse(&traverse);
1835 // Check the types in a single block.
1838 Gogo::check_types_in_block(Block* block)
1840 Check_types_traverse traverse(this);
1841 block->traverse(&traverse);
1844 // A traversal class used to find a single shortcut operator within an
1847 class Find_shortcut : public Traverse
1851 : Traverse(traverse_blocks
1852 | traverse_statements
1853 | traverse_expressions),
1857 // A pointer to the expression which was found, or NULL if none was
1861 { return this->found_; }
1866 { return TRAVERSE_SKIP_COMPONENTS; }
1869 statement(Block*, size_t*, Statement*)
1870 { return TRAVERSE_SKIP_COMPONENTS; }
1873 expression(Expression**);
1876 Expression** found_;
1879 // Find a shortcut expression.
1882 Find_shortcut::expression(Expression** pexpr)
1884 Expression* expr = *pexpr;
1885 Binary_expression* be = expr->binary_expression();
1887 return TRAVERSE_CONTINUE;
1888 Operator op = be->op();
1889 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1890 return TRAVERSE_CONTINUE;
1891 go_assert(this->found_ == NULL);
1892 this->found_ = pexpr;
1893 return TRAVERSE_EXIT;
1896 // A traversal class used to turn shortcut operators into explicit if
1899 class Shortcuts : public Traverse
1902 Shortcuts(Gogo* gogo)
1903 : Traverse(traverse_variables
1904 | traverse_statements),
1910 variable(Named_object*);
1913 statement(Block*, size_t*, Statement*);
1916 // Convert a shortcut operator.
1918 convert_shortcut(Block* enclosing, Expression** pshortcut);
1924 // Remove shortcut operators in a single statement.
1927 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1929 // FIXME: This approach doesn't work for switch statements, because
1930 // we add the new statements before the whole switch when we need to
1931 // instead add them just before the switch expression. The right
1932 // fix is probably to lower switch statements with nonconstant cases
1933 // to a series of conditionals.
1934 if (s->switch_statement() != NULL)
1935 return TRAVERSE_CONTINUE;
1939 Find_shortcut find_shortcut;
1941 // If S is a variable declaration, then ordinary traversal won't
1942 // do anything. We want to explicitly traverse the
1943 // initialization expression if there is one.
1944 Variable_declaration_statement* vds = s->variable_declaration_statement();
1945 Expression* init = NULL;
1947 s->traverse_contents(&find_shortcut);
1950 init = vds->var()->var_value()->init();
1952 return TRAVERSE_CONTINUE;
1953 init->traverse(&init, &find_shortcut);
1955 Expression** pshortcut = find_shortcut.found();
1956 if (pshortcut == NULL)
1957 return TRAVERSE_CONTINUE;
1959 Statement* snew = this->convert_shortcut(block, pshortcut);
1960 block->insert_statement_before(*pindex, snew);
1963 if (pshortcut == &init)
1964 vds->var()->var_value()->set_init(init);
1968 // Remove shortcut operators in the initializer of a global variable.
1971 Shortcuts::variable(Named_object* no)
1973 if (no->is_result_variable())
1974 return TRAVERSE_CONTINUE;
1975 Variable* var = no->var_value();
1976 Expression* init = var->init();
1977 if (!var->is_global() || init == NULL)
1978 return TRAVERSE_CONTINUE;
1982 Find_shortcut find_shortcut;
1983 init->traverse(&init, &find_shortcut);
1984 Expression** pshortcut = find_shortcut.found();
1985 if (pshortcut == NULL)
1986 return TRAVERSE_CONTINUE;
1988 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1989 var->add_preinit_statement(this->gogo_, snew);
1990 if (pshortcut == &init)
1991 var->set_init(init);
1995 // Given an expression which uses a shortcut operator, return a
1996 // statement which implements it, and update *PSHORTCUT accordingly.
1999 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2001 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2002 Expression* left = shortcut->left();
2003 Expression* right = shortcut->right();
2004 Location loc = shortcut->location();
2006 Block* retblock = new Block(enclosing, loc);
2007 retblock->set_end_location(loc);
2009 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
2011 retblock->add_statement(ts);
2013 Block* block = new Block(retblock, loc);
2014 block->set_end_location(loc);
2015 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2016 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2017 block->add_statement(assign);
2019 Expression* cond = Expression::make_temporary_reference(ts, loc);
2020 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2021 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2023 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2025 retblock->add_statement(if_statement);
2027 *pshortcut = Expression::make_temporary_reference(ts, loc);
2031 // Now convert any shortcut operators in LEFT and RIGHT.
2032 Shortcuts shortcuts(this->gogo_);
2033 retblock->traverse(&shortcuts);
2035 return Statement::make_block_statement(retblock, loc);
2038 // Turn shortcut operators into explicit if statements. Doing this
2039 // considerably simplifies the order of evaluation rules.
2042 Gogo::remove_shortcuts()
2044 Shortcuts shortcuts(this);
2045 this->traverse(&shortcuts);
2048 // A traversal class which finds all the expressions which must be
2049 // evaluated in order within a statement or larger expression. This
2050 // is used to implement the rules about order of evaluation.
2052 class Find_eval_ordering : public Traverse
2055 typedef std::vector<Expression**> Expression_pointers;
2058 Find_eval_ordering()
2059 : Traverse(traverse_blocks
2060 | traverse_statements
2061 | traverse_expressions),
2067 { return this->exprs_.size(); }
2069 typedef Expression_pointers::const_iterator const_iterator;
2073 { return this->exprs_.begin(); }
2077 { return this->exprs_.end(); }
2082 { return TRAVERSE_SKIP_COMPONENTS; }
2085 statement(Block*, size_t*, Statement*)
2086 { return TRAVERSE_SKIP_COMPONENTS; }
2089 expression(Expression**);
2092 // A list of pointers to expressions with side-effects.
2093 Expression_pointers exprs_;
2096 // If an expression must be evaluated in order, put it on the list.
2099 Find_eval_ordering::expression(Expression** expression_pointer)
2101 // We have to look at subexpressions before this one.
2102 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2103 return TRAVERSE_EXIT;
2104 if ((*expression_pointer)->must_eval_in_order())
2105 this->exprs_.push_back(expression_pointer);
2106 return TRAVERSE_SKIP_COMPONENTS;
2109 // A traversal class for ordering evaluations.
2111 class Order_eval : public Traverse
2114 Order_eval(Gogo* gogo)
2115 : Traverse(traverse_variables
2116 | traverse_statements),
2121 variable(Named_object*);
2124 statement(Block*, size_t*, Statement*);
2131 // Implement the order of evaluation rules for a statement.
2134 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2136 // FIXME: This approach doesn't work for switch statements, because
2137 // we add the new statements before the whole switch when we need to
2138 // instead add them just before the switch expression. The right
2139 // fix is probably to lower switch statements with nonconstant cases
2140 // to a series of conditionals.
2141 if (s->switch_statement() != NULL)
2142 return TRAVERSE_CONTINUE;
2144 Find_eval_ordering find_eval_ordering;
2146 // If S is a variable declaration, then ordinary traversal won't do
2147 // anything. We want to explicitly traverse the initialization
2148 // expression if there is one.
2149 Variable_declaration_statement* vds = s->variable_declaration_statement();
2150 Expression* init = NULL;
2151 Expression* orig_init = NULL;
2153 s->traverse_contents(&find_eval_ordering);
2156 init = vds->var()->var_value()->init();
2158 return TRAVERSE_CONTINUE;
2161 // It might seem that this could be
2162 // init->traverse_subexpressions. Unfortunately that can fail
2165 // newvar, err := call(arg())
2166 // Here newvar will have an init of call result 0 of
2167 // call(arg()). If we only traverse subexpressions, we will
2168 // only find arg(), and we won't bother to move anything out.
2169 // Then we get to the assignment to err, we will traverse the
2170 // whole statement, and this time we will find both call() and
2171 // arg(), and so we will move them out. This will cause them to
2172 // be put into temporary variables before the assignment to err
2173 // but after the declaration of newvar. To avoid that problem,
2174 // we traverse the entire expression here.
2175 Expression::traverse(&init, &find_eval_ordering);
2178 if (find_eval_ordering.size() <= 1)
2180 // If there is only one expression with a side-effect, we can
2181 // leave it in place.
2182 return TRAVERSE_CONTINUE;
2185 bool is_thunk = s->thunk_statement() != NULL;
2186 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2187 p != find_eval_ordering.end();
2190 Expression** pexpr = *p;
2192 // The last expression in a thunk will be the call passed to go
2193 // or defer, which we must not evaluate early.
2194 if (is_thunk && p + 1 == find_eval_ordering.end())
2197 Location loc = (*pexpr)->location();
2199 if ((*pexpr)->call_expression() == NULL
2200 || (*pexpr)->call_expression()->result_count() < 2)
2202 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2205 *pexpr = Expression::make_temporary_reference(ts, loc);
2209 // A call expression which returns multiple results needs to
2210 // be handled specially. We can't create a temporary
2211 // because there is no type to give it. Any actual uses of
2212 // the values will be done via Call_result_expressions.
2213 s = Statement::make_statement(*pexpr, true);
2216 block->insert_statement_before(*pindex, s);
2220 if (init != orig_init)
2221 vds->var()->var_value()->set_init(init);
2223 return TRAVERSE_CONTINUE;
2226 // Implement the order of evaluation rules for the initializer of a
2230 Order_eval::variable(Named_object* no)
2232 if (no->is_result_variable())
2233 return TRAVERSE_CONTINUE;
2234 Variable* var = no->var_value();
2235 Expression* init = var->init();
2236 if (!var->is_global() || init == NULL)
2237 return TRAVERSE_CONTINUE;
2239 Find_eval_ordering find_eval_ordering;
2240 Expression::traverse(&init, &find_eval_ordering);
2242 if (find_eval_ordering.size() <= 1)
2244 // If there is only one expression with a side-effect, we can
2245 // leave it in place.
2246 return TRAVERSE_SKIP_COMPONENTS;
2249 Expression* orig_init = init;
2251 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2252 p != find_eval_ordering.end();
2255 Expression** pexpr = *p;
2256 Location loc = (*pexpr)->location();
2258 if ((*pexpr)->call_expression() == NULL
2259 || (*pexpr)->call_expression()->result_count() < 2)
2261 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2264 *pexpr = Expression::make_temporary_reference(ts, loc);
2268 // A call expression which returns multiple results needs to
2269 // be handled specially.
2270 s = Statement::make_statement(*pexpr, true);
2272 var->add_preinit_statement(this->gogo_, s);
2275 if (init != orig_init)
2276 var->set_init(init);
2278 return TRAVERSE_SKIP_COMPONENTS;
2281 // Use temporary variables to implement the order of evaluation rules.
2284 Gogo::order_evaluations()
2286 Order_eval order_eval(this);
2287 this->traverse(&order_eval);
2290 // Traversal to convert calls to the predeclared recover function to
2291 // pass in an argument indicating whether it can recover from a panic
2294 class Convert_recover : public Traverse
2297 Convert_recover(Named_object* arg)
2298 : Traverse(traverse_expressions),
2304 expression(Expression**);
2307 // The argument to pass to the function.
2311 // Convert calls to recover.
2314 Convert_recover::expression(Expression** pp)
2316 Call_expression* ce = (*pp)->call_expression();
2317 if (ce != NULL && ce->is_recover_call())
2318 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2320 return TRAVERSE_CONTINUE;
2323 // Traversal for build_recover_thunks.
2325 class Build_recover_thunks : public Traverse
2328 Build_recover_thunks(Gogo* gogo)
2329 : Traverse(traverse_functions),
2334 function(Named_object*);
2338 can_recover_arg(Location);
2344 // If this function calls recover, turn it into a thunk.
2347 Build_recover_thunks::function(Named_object* orig_no)
2349 Function* orig_func = orig_no->func_value();
2350 if (!orig_func->calls_recover()
2351 || orig_func->is_recover_thunk()
2352 || orig_func->has_recover_thunk())
2353 return TRAVERSE_CONTINUE;
2355 Gogo* gogo = this->gogo_;
2356 Location location = orig_func->location();
2361 Function_type* orig_fntype = orig_func->type();
2362 Typed_identifier_list* new_params = new Typed_identifier_list();
2363 std::string receiver_name;
2364 if (orig_fntype->is_method())
2366 const Typed_identifier* receiver = orig_fntype->receiver();
2367 snprintf(buf, sizeof buf, "rt.%u", count);
2369 receiver_name = buf;
2370 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2371 receiver->location()));
2373 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2374 if (orig_params != NULL && !orig_params->empty())
2376 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2377 p != orig_params->end();
2380 snprintf(buf, sizeof buf, "pt.%u", count);
2382 new_params->push_back(Typed_identifier(buf, p->type(),
2386 snprintf(buf, sizeof buf, "pr.%u", count);
2388 std::string can_recover_name = buf;
2389 new_params->push_back(Typed_identifier(can_recover_name,
2390 Type::lookup_bool_type(),
2391 orig_fntype->location()));
2393 const Typed_identifier_list* orig_results = orig_fntype->results();
2394 Typed_identifier_list* new_results;
2395 if (orig_results == NULL || orig_results->empty())
2399 new_results = new Typed_identifier_list();
2400 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2401 p != orig_results->end();
2403 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2406 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2408 orig_fntype->location());
2409 if (orig_fntype->is_varargs())
2410 new_fntype->set_is_varargs();
2412 std::string name = orig_no->name() + "$recover";
2413 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2415 Function *new_func = new_no->func_value();
2416 if (orig_func->enclosing() != NULL)
2417 new_func->set_enclosing(orig_func->enclosing());
2419 // We build the code for the original function attached to the new
2420 // function, and then swap the original and new function bodies.
2421 // This means that existing references to the original function will
2422 // then refer to the new function. That makes this code a little
2423 // confusing, in that the reference to NEW_NO really refers to the
2424 // other function, not the one we are building.
2426 Expression* closure = NULL;
2427 if (orig_func->needs_closure())
2429 Named_object* orig_closure_no = orig_func->closure_var();
2430 Variable* orig_closure_var = orig_closure_no->var_value();
2431 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2432 true, false, location);
2433 snprintf(buf, sizeof buf, "closure.%u", count);
2435 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2437 new_func->set_closure_var(new_closure_no);
2438 closure = Expression::make_var_reference(new_closure_no, location);
2441 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2443 Expression_list* args = new Expression_list();
2444 if (new_params != NULL)
2446 // Note that we skip the last parameter, which is the boolean
2447 // indicating whether recover can succed.
2448 for (Typed_identifier_list::const_iterator p = new_params->begin();
2449 p + 1 != new_params->end();
2452 Named_object* p_no = gogo->lookup(p->name(), NULL);
2453 go_assert(p_no != NULL
2454 && p_no->is_variable()
2455 && p_no->var_value()->is_parameter());
2456 args->push_back(Expression::make_var_reference(p_no, location));
2459 args->push_back(this->can_recover_arg(location));
2461 gogo->start_block(location);
2463 Call_expression* call = Expression::make_call(fn, args, false, location);
2466 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2467 s = Statement::make_statement(call, true);
2470 Expression_list* vals = new Expression_list();
2471 size_t rc = orig_fntype->results()->size();
2473 vals->push_back(call);
2476 for (size_t i = 0; i < rc; ++i)
2477 vals->push_back(Expression::make_call_result(call, i));
2479 s = Statement::make_return_statement(vals, location);
2481 s->determine_types();
2482 gogo->add_statement(s);
2484 Block* b = gogo->finish_block(location);
2486 gogo->add_block(b, location);
2488 // Lower the call in case it returns multiple results.
2489 gogo->lower_block(new_no, b);
2491 gogo->finish_function(location);
2493 // Swap the function bodies and types.
2494 new_func->swap_for_recover(orig_func);
2495 orig_func->set_is_recover_thunk();
2496 new_func->set_calls_recover();
2497 new_func->set_has_recover_thunk();
2499 Bindings* orig_bindings = orig_func->block()->bindings();
2500 Bindings* new_bindings = new_func->block()->bindings();
2501 if (orig_fntype->is_method())
2503 // We changed the receiver to be a regular parameter. We have
2504 // to update the binding accordingly in both functions.
2505 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2506 go_assert(orig_rec_no != NULL
2507 && orig_rec_no->is_variable()
2508 && !orig_rec_no->var_value()->is_receiver());
2509 orig_rec_no->var_value()->set_is_receiver();
2511 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2512 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2513 if (new_rec_no == NULL)
2514 go_assert(saw_errors());
2517 go_assert(new_rec_no->is_variable()
2518 && new_rec_no->var_value()->is_receiver());
2519 new_rec_no->var_value()->set_is_not_receiver();
2523 // Because we flipped blocks but not types, the can_recover
2524 // parameter appears in the (now) old bindings as a parameter.
2525 // Change it to a local variable, whereupon it will be discarded.
2526 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2527 go_assert(can_recover_no != NULL
2528 && can_recover_no->is_variable()
2529 && can_recover_no->var_value()->is_parameter());
2530 orig_bindings->remove_binding(can_recover_no);
2532 // Add the can_recover argument to the (now) new bindings, and
2533 // attach it to any recover statements.
2534 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2535 false, true, false, location);
2536 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2538 Convert_recover convert_recover(can_recover_no);
2539 new_func->traverse(&convert_recover);
2541 // Update the function pointers in any named results.
2542 new_func->update_result_variables();
2543 orig_func->update_result_variables();
2545 return TRAVERSE_CONTINUE;
2548 // Return the expression to pass for the .can_recover parameter to the
2549 // new function. This indicates whether a call to recover may return
2550 // non-nil. The expression is
2551 // __go_can_recover(__builtin_return_address()).
2554 Build_recover_thunks::can_recover_arg(Location location)
2556 static Named_object* builtin_return_address;
2557 if (builtin_return_address == NULL)
2559 const Location bloc = Linemap::predeclared_location();
2561 Typed_identifier_list* param_types = new Typed_identifier_list();
2562 Type* uint_type = Type::lookup_integer_type("uint");
2563 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2565 Typed_identifier_list* return_types = new Typed_identifier_list();
2566 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2567 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2569 Function_type* fntype = Type::make_function_type(NULL, param_types,
2570 return_types, bloc);
2571 builtin_return_address =
2572 Named_object::make_function_declaration("__builtin_return_address",
2573 NULL, fntype, bloc);
2574 const char* n = "__builtin_return_address";
2575 builtin_return_address->func_declaration_value()->set_asm_name(n);
2578 static Named_object* can_recover;
2579 if (can_recover == NULL)
2581 const Location bloc = Linemap::predeclared_location();
2582 Typed_identifier_list* param_types = new Typed_identifier_list();
2583 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2584 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2585 Type* boolean_type = Type::lookup_bool_type();
2586 Typed_identifier_list* results = new Typed_identifier_list();
2587 results->push_back(Typed_identifier("", boolean_type, bloc));
2588 Function_type* fntype = Type::make_function_type(NULL, param_types,
2590 can_recover = Named_object::make_function_declaration("__go_can_recover",
2593 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2596 Expression* fn = Expression::make_func_reference(builtin_return_address,
2600 mpz_init_set_ui(zval, 0UL);
2601 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2603 Expression_list *args = new Expression_list();
2604 args->push_back(zexpr);
2606 Expression* call = Expression::make_call(fn, args, false, location);
2608 args = new Expression_list();
2609 args->push_back(call);
2611 fn = Expression::make_func_reference(can_recover, NULL, location);
2612 return Expression::make_call(fn, args, false, location);
2615 // Build thunks for functions which call recover. We build a new
2616 // function with an extra parameter, which is whether a call to
2617 // recover can succeed. We then move the body of this function to
2618 // that one. We then turn this function into a thunk which calls the
2619 // new one, passing the value of
2620 // __go_can_recover(__builtin_return_address()). The function will be
2621 // marked as not splitting the stack. This will cooperate with the
2622 // implementation of defer to make recover do the right thing.
2625 Gogo::build_recover_thunks()
2627 Build_recover_thunks build_recover_thunks(this);
2628 this->traverse(&build_recover_thunks);
2631 // Look for named types to see whether we need to create an interface
2634 class Build_method_tables : public Traverse
2637 Build_method_tables(Gogo* gogo,
2638 const std::vector<Interface_type*>& interfaces)
2639 : Traverse(traverse_types),
2640 gogo_(gogo), interfaces_(interfaces)
2649 // A list of locally defined interfaces which have hidden methods.
2650 const std::vector<Interface_type*>& interfaces_;
2653 // Build all required interface method tables for types. We need to
2654 // ensure that we have an interface method table for every interface
2655 // which has a hidden method, for every named type which implements
2656 // that interface. Normally we can just build interface method tables
2657 // as we need them. However, in some cases we can require an
2658 // interface method table for an interface defined in a different
2659 // package for a type defined in that package. If that interface and
2660 // type both use a hidden method, that is OK. However, we will not be
2661 // able to build that interface method table when we need it, because
2662 // the type's hidden method will be static. So we have to build it
2663 // here, and just refer it from other packages as needed.
2666 Gogo::build_interface_method_tables()
2671 std::vector<Interface_type*> hidden_interfaces;
2672 hidden_interfaces.reserve(this->interface_types_.size());
2673 for (std::vector<Interface_type*>::const_iterator pi =
2674 this->interface_types_.begin();
2675 pi != this->interface_types_.end();
2678 const Typed_identifier_list* methods = (*pi)->methods();
2679 if (methods == NULL)
2681 for (Typed_identifier_list::const_iterator pm = methods->begin();
2682 pm != methods->end();
2685 if (Gogo::is_hidden_name(pm->name()))
2687 hidden_interfaces.push_back(*pi);
2693 if (!hidden_interfaces.empty())
2695 // Now traverse the tree looking for all named types.
2696 Build_method_tables bmt(this, hidden_interfaces);
2697 this->traverse(&bmt);
2700 // We no longer need the list of interfaces.
2702 this->interface_types_.clear();
2705 // This is called for each type. For a named type, for each of the
2706 // interfaces with hidden methods that it implements, create the
2710 Build_method_tables::type(Type* type)
2712 Named_type* nt = type->named_type();
2715 for (std::vector<Interface_type*>::const_iterator p =
2716 this->interfaces_.begin();
2717 p != this->interfaces_.end();
2720 // We ask whether a pointer to the named type implements the
2721 // interface, because a pointer can implement more methods
2723 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2725 nt->interface_method_table(this->gogo_, *p, false);
2726 nt->interface_method_table(this->gogo_, *p, true);
2730 return TRAVERSE_CONTINUE;
2733 // Traversal class used to check for return statements.
2735 class Check_return_statements_traverse : public Traverse
2738 Check_return_statements_traverse()
2739 : Traverse(traverse_functions)
2743 function(Named_object*);
2746 // Check that a function has a return statement if it needs one.
2749 Check_return_statements_traverse::function(Named_object* no)
2751 Function* func = no->func_value();
2752 const Function_type* fntype = func->type();
2753 const Typed_identifier_list* results = fntype->results();
2755 // We only need a return statement if there is a return value.
2756 if (results == NULL || results->empty())
2757 return TRAVERSE_CONTINUE;
2759 if (func->block()->may_fall_through())
2760 error_at(func->location(), "control reaches end of non-void function");
2762 return TRAVERSE_CONTINUE;
2765 // Check return statements.
2768 Gogo::check_return_statements()
2770 Check_return_statements_traverse traverse;
2771 this->traverse(&traverse);
2774 // Get the unique prefix to use before all exported symbols. This
2775 // must be unique across the entire link.
2778 Gogo::unique_prefix() const
2780 go_assert(!this->unique_prefix_.empty());
2781 return this->unique_prefix_;
2784 // Set the unique prefix to use before all exported symbols. This
2785 // comes from the command line option -fgo-prefix=XXX.
2788 Gogo::set_unique_prefix(const std::string& arg)
2790 go_assert(this->unique_prefix_.empty());
2791 this->unique_prefix_ = arg;
2792 this->unique_prefix_specified_ = true;
2795 // Work out the package priority. It is one more than the maximum
2796 // priority of an imported package.
2799 Gogo::package_priority() const
2802 for (Packages::const_iterator p = this->packages_.begin();
2803 p != this->packages_.end();
2805 if (p->second->priority() > priority)
2806 priority = p->second->priority();
2807 return priority + 1;
2810 // Export identifiers as requested.
2815 // For now we always stream to a section. Later we may want to
2816 // support streaming to a separate file.
2817 Stream_to_section stream;
2819 Export exp(&stream);
2820 exp.register_builtin_types(this);
2821 exp.export_globals(this->package_name(),
2822 this->unique_prefix(),
2823 this->package_priority(),
2824 (this->need_init_fn_ && !this->is_main_package()
2825 ? this->get_init_fn_name()
2827 this->imported_init_fns_,
2828 this->package_->bindings());
2831 // Find the blocks in order to convert named types defined in blocks.
2833 class Convert_named_types : public Traverse
2836 Convert_named_types(Gogo* gogo)
2837 : Traverse(traverse_blocks),
2843 block(Block* block);
2850 Convert_named_types::block(Block* block)
2852 this->gogo_->convert_named_types_in_bindings(block->bindings());
2853 return TRAVERSE_CONTINUE;
2856 // Convert all named types to the backend representation. Since named
2857 // types can refer to other types, this needs to be done in the right
2858 // sequence, which is handled by Named_type::convert. Here we arrange
2859 // to call that for each named type.
2862 Gogo::convert_named_types()
2864 this->convert_named_types_in_bindings(this->globals_);
2865 for (Packages::iterator p = this->packages_.begin();
2866 p != this->packages_.end();
2869 Package* package = p->second;
2870 this->convert_named_types_in_bindings(package->bindings());
2873 Convert_named_types cnt(this);
2874 this->traverse(&cnt);
2876 // Make all the builtin named types used for type descriptors, and
2877 // then convert them. They will only be written out if they are
2879 Type::make_type_descriptor_type();
2880 Type::make_type_descriptor_ptr_type();
2881 Function_type::make_function_type_descriptor_type();
2882 Pointer_type::make_pointer_type_descriptor_type();
2883 Struct_type::make_struct_type_descriptor_type();
2884 Array_type::make_array_type_descriptor_type();
2885 Array_type::make_slice_type_descriptor_type();
2886 Map_type::make_map_type_descriptor_type();
2887 Map_type::make_map_descriptor_type();
2888 Channel_type::make_chan_type_descriptor_type();
2889 Interface_type::make_interface_type_descriptor_type();
2890 Type::convert_builtin_named_types(this);
2892 Runtime::convert_types(this);
2894 Function_type::convert_types(this);
2896 this->named_types_are_converted_ = true;
2899 // Convert all names types in a set of bindings.
2902 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2904 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2905 p != bindings->end_definitions();
2908 if ((*p)->is_type())
2909 (*p)->type_value()->convert(this);
2915 Function::Function(Function_type* type, Function* enclosing, Block* block,
2917 : type_(type), enclosing_(enclosing), results_(NULL),
2918 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2919 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2920 is_recover_thunk_(false), has_recover_thunk_(false)
2924 // Create the named result variables.
2927 Function::create_result_variables(Gogo* gogo)
2929 const Typed_identifier_list* results = this->type_->results();
2930 if (results == NULL || results->empty())
2933 if (!results->front().name().empty())
2934 this->results_are_named_ = true;
2936 this->results_ = new Results();
2937 this->results_->reserve(results->size());
2939 Block* block = this->block_;
2941 for (Typed_identifier_list::const_iterator p = results->begin();
2942 p != results->end();
2945 std::string name = p->name();
2946 if (name.empty() || Gogo::is_sink_name(name))
2948 static int result_counter;
2950 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2952 name = gogo->pack_hidden_name(buf, false);
2954 Result_variable* result = new Result_variable(p->type(), this, index,
2956 Named_object* no = block->bindings()->add_result_variable(name, result);
2957 if (no->is_result_variable())
2958 this->results_->push_back(no);
2961 static int dummy_result_count;
2963 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2964 ++dummy_result_count;
2965 name = gogo->pack_hidden_name(buf, false);
2966 no = block->bindings()->add_result_variable(name, result);
2967 go_assert(no->is_result_variable());
2968 this->results_->push_back(no);
2973 // Update the named result variables when cloning a function which
2977 Function::update_result_variables()
2979 if (this->results_ == NULL)
2982 for (Results::iterator p = this->results_->begin();
2983 p != this->results_->end();
2985 (*p)->result_var_value()->set_function(this);
2988 // Return the closure variable, creating it if necessary.
2991 Function::closure_var()
2993 if (this->closure_var_ == NULL)
2995 // We don't know the type of the variable yet. We add fields as
2997 Location loc = this->type_->location();
2998 Struct_field_list* sfl = new Struct_field_list;
2999 Type* struct_type = Type::make_struct_type(sfl, loc);
3000 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3001 NULL, false, true, false, loc);
3003 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
3004 // Note that the new variable is not in any binding contour.
3006 return this->closure_var_;
3009 // Set the type of the closure variable.
3012 Function::set_closure_type()
3014 if (this->closure_var_ == NULL)
3016 Named_object* closure = this->closure_var_;
3017 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3018 unsigned int index = 0;
3019 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3020 p != this->closure_fields_.end();
3023 Named_object* no = p->first;
3025 snprintf(buf, sizeof buf, "%u", index);
3026 std::string n = no->name() + buf;
3028 if (no->is_variable())
3029 var_type = no->var_value()->type();
3031 var_type = no->result_var_value()->type();
3032 Type* field_type = Type::make_pointer_type(var_type);
3033 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3037 // Return whether this function is a method.
3040 Function::is_method() const
3042 return this->type_->is_method();
3045 // Add a label definition.
3048 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3051 Label* lnull = NULL;
3052 std::pair<Labels::iterator, bool> ins =
3053 this->labels_.insert(std::make_pair(label_name, lnull));
3057 // This is a new label.
3058 label = new Label(label_name);
3059 ins.first->second = label;
3063 // The label was already in the hash table.
3064 label = ins.first->second;
3065 if (label->is_defined())
3067 error_at(location, "label %qs already defined",
3068 Gogo::message_name(label_name).c_str());
3069 inform(label->location(), "previous definition of %qs was here",
3070 Gogo::message_name(label_name).c_str());
3071 return new Label(label_name);
3075 label->define(location, gogo->bindings_snapshot(location));
3077 // Issue any errors appropriate for any previous goto's to this
3079 const std::vector<Bindings_snapshot*>& refs(label->refs());
3080 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3083 (*p)->check_goto_to(gogo->current_block());
3084 label->clear_refs();
3089 // Add a reference to a label.
3092 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3093 Location location, bool issue_goto_errors)
3095 Label* lnull = NULL;
3096 std::pair<Labels::iterator, bool> ins =
3097 this->labels_.insert(std::make_pair(label_name, lnull));
3101 // The label was already in the hash table.
3102 label = ins.first->second;
3106 go_assert(ins.first->second == NULL);
3107 label = new Label(label_name);
3108 ins.first->second = label;
3111 label->set_is_used();
3113 if (issue_goto_errors)
3115 Bindings_snapshot* snapshot = label->snapshot();
3116 if (snapshot != NULL)
3117 snapshot->check_goto_from(gogo->current_block(), location);
3119 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3125 // Warn about labels that are defined but not used.
3128 Function::check_labels() const
3130 for (Labels::const_iterator p = this->labels_.begin();
3131 p != this->labels_.end();
3134 Label* label = p->second;
3135 if (!label->is_used())
3136 error_at(label->location(), "label %qs defined and not used",
3137 Gogo::message_name(label->name()).c_str());
3141 // Swap one function with another. This is used when building the
3142 // thunk we use to call a function which calls recover. It may not
3143 // work for any other case.
3146 Function::swap_for_recover(Function *x)
3148 go_assert(this->enclosing_ == x->enclosing_);
3149 std::swap(this->results_, x->results_);
3150 std::swap(this->closure_var_, x->closure_var_);
3151 std::swap(this->block_, x->block_);
3152 go_assert(this->location_ == x->location_);
3153 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3154 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3157 // Traverse the tree.
3160 Function::traverse(Traverse* traverse)
3162 unsigned int traverse_mask = traverse->traverse_mask();
3165 & (Traverse::traverse_types | Traverse::traverse_expressions))
3168 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3169 return TRAVERSE_EXIT;
3172 // FIXME: We should check traverse_functions here if nested
3173 // functions are stored in block bindings.
3174 if (this->block_ != NULL
3176 & (Traverse::traverse_variables
3177 | Traverse::traverse_constants
3178 | Traverse::traverse_blocks
3179 | Traverse::traverse_statements
3180 | Traverse::traverse_expressions
3181 | Traverse::traverse_types)) != 0)
3183 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3184 return TRAVERSE_EXIT;
3187 return TRAVERSE_CONTINUE;
3190 // Work out types for unspecified variables and constants.
3193 Function::determine_types()
3195 if (this->block_ != NULL)
3196 this->block_->determine_types();
3199 // Get a pointer to the variable representing the defer stack for this
3200 // function, making it if necessary. The value of the variable is set
3201 // by the runtime routines to true if the function is returning,
3202 // rather than panicing through. A pointer to this variable is used
3203 // as a marker for the functions on the defer stack associated with
3204 // this function. A function-specific variable permits inlining a
3205 // function which uses defer.
3208 Function::defer_stack(Location location)
3210 if (this->defer_stack_ == NULL)
3212 Type* t = Type::lookup_bool_type();
3213 Expression* n = Expression::make_boolean(false, location);
3214 this->defer_stack_ = Statement::make_temporary(t, n, location);
3215 this->defer_stack_->set_is_address_taken();
3217 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3219 return Expression::make_unary(OPERATOR_AND, ref, location);
3222 // Export the function.
3225 Function::export_func(Export* exp, const std::string& name) const
3227 Function::export_func_with_type(exp, name, this->type_);
3230 // Export a function with a type.
3233 Function::export_func_with_type(Export* exp, const std::string& name,
3234 const Function_type* fntype)
3236 exp->write_c_string("func ");
3238 if (fntype->is_method())
3240 exp->write_c_string("(");
3241 exp->write_type(fntype->receiver()->type());
3242 exp->write_c_string(") ");
3245 exp->write_string(name);
3247 exp->write_c_string(" (");
3248 const Typed_identifier_list* parameters = fntype->parameters();
3249 if (parameters != NULL)
3251 bool is_varargs = fntype->is_varargs();
3253 for (Typed_identifier_list::const_iterator p = parameters->begin();
3254 p != parameters->end();
3260 exp->write_c_string(", ");
3261 if (!is_varargs || p + 1 != parameters->end())
3262 exp->write_type(p->type());
3265 exp->write_c_string("...");
3266 exp->write_type(p->type()->array_type()->element_type());
3270 exp->write_c_string(")");
3272 const Typed_identifier_list* results = fntype->results();
3273 if (results != NULL)
3275 if (results->size() == 1)
3277 exp->write_c_string(" ");
3278 exp->write_type(results->begin()->type());
3282 exp->write_c_string(" (");
3284 for (Typed_identifier_list::const_iterator p = results->begin();
3285 p != results->end();
3291 exp->write_c_string(", ");
3292 exp->write_type(p->type());
3294 exp->write_c_string(")");
3297 exp->write_c_string(";\n");
3300 // Import a function.
3303 Function::import_func(Import* imp, std::string* pname,
3304 Typed_identifier** preceiver,
3305 Typed_identifier_list** pparameters,
3306 Typed_identifier_list** presults,
3309 imp->require_c_string("func ");
3312 if (imp->peek_char() == '(')
3314 imp->require_c_string("(");
3315 Type* rtype = imp->read_type();
3316 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3318 imp->require_c_string(") ");
3321 *pname = imp->read_identifier();
3323 Typed_identifier_list* parameters;
3324 *is_varargs = false;
3325 imp->require_c_string(" (");
3326 if (imp->peek_char() == ')')
3330 parameters = new Typed_identifier_list();
3333 if (imp->match_c_string("..."))
3339 Type* ptype = imp->read_type();
3341 ptype = Type::make_array_type(ptype, NULL);
3342 parameters->push_back(Typed_identifier(Import::import_marker,
3343 ptype, imp->location()));
3344 if (imp->peek_char() != ',')
3346 go_assert(!*is_varargs);
3347 imp->require_c_string(", ");
3350 imp->require_c_string(")");
3351 *pparameters = parameters;
3353 Typed_identifier_list* results;
3354 if (imp->peek_char() != ' ')
3358 results = new Typed_identifier_list();
3359 imp->require_c_string(" ");
3360 if (imp->peek_char() != '(')
3362 Type* rtype = imp->read_type();
3363 results->push_back(Typed_identifier(Import::import_marker, rtype,
3368 imp->require_c_string("(");
3371 Type* rtype = imp->read_type();
3372 results->push_back(Typed_identifier(Import::import_marker,
3373 rtype, imp->location()));
3374 if (imp->peek_char() != ',')
3376 imp->require_c_string(", ");
3378 imp->require_c_string(")");
3381 imp->require_c_string(";\n");
3382 *presults = results;
3387 Block::Block(Block* enclosing, Location location)
3388 : enclosing_(enclosing), statements_(),
3389 bindings_(new Bindings(enclosing == NULL
3391 : enclosing->bindings())),
3392 start_location_(location),
3393 end_location_(UNKNOWN_LOCATION)
3397 // Add a statement to a block.
3400 Block::add_statement(Statement* statement)
3402 this->statements_.push_back(statement);
3405 // Add a statement to the front of a block. This is slow but is only
3406 // used for reference counts of parameters.
3409 Block::add_statement_at_front(Statement* statement)
3411 this->statements_.insert(this->statements_.begin(), statement);
3414 // Replace a statement in a block.
3417 Block::replace_statement(size_t index, Statement* s)
3419 go_assert(index < this->statements_.size());
3420 this->statements_[index] = s;
3423 // Add a statement before another statement.
3426 Block::insert_statement_before(size_t index, Statement* s)
3428 go_assert(index < this->statements_.size());
3429 this->statements_.insert(this->statements_.begin() + index, s);
3432 // Add a statement after another statement.
3435 Block::insert_statement_after(size_t index, Statement* s)
3437 go_assert(index < this->statements_.size());
3438 this->statements_.insert(this->statements_.begin() + index + 1, s);
3441 // Traverse the tree.
3444 Block::traverse(Traverse* traverse)
3446 unsigned int traverse_mask = traverse->traverse_mask();
3448 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3450 int t = traverse->block(this);
3451 if (t == TRAVERSE_EXIT)
3452 return TRAVERSE_EXIT;
3453 else if (t == TRAVERSE_SKIP_COMPONENTS)
3454 return TRAVERSE_CONTINUE;
3458 & (Traverse::traverse_variables
3459 | Traverse::traverse_constants
3460 | Traverse::traverse_expressions
3461 | Traverse::traverse_types)) != 0)
3463 const unsigned int e_or_t = (Traverse::traverse_expressions
3464 | Traverse::traverse_types);
3465 const unsigned int e_or_t_or_s = (e_or_t
3466 | Traverse::traverse_statements);
3467 for (Bindings::const_definitions_iterator pb =
3468 this->bindings_->begin_definitions();
3469 pb != this->bindings_->end_definitions();
3472 int t = TRAVERSE_CONTINUE;
3473 switch ((*pb)->classification())
3475 case Named_object::NAMED_OBJECT_CONST:
3476 if ((traverse_mask & Traverse::traverse_constants) != 0)
3477 t = traverse->constant(*pb, false);
3478 if (t == TRAVERSE_CONTINUE
3479 && (traverse_mask & e_or_t) != 0)
3481 Type* tc = (*pb)->const_value()->type();
3483 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3484 return TRAVERSE_EXIT;
3485 t = (*pb)->const_value()->traverse_expression(traverse);
3489 case Named_object::NAMED_OBJECT_VAR:
3490 case Named_object::NAMED_OBJECT_RESULT_VAR:
3491 if ((traverse_mask & Traverse::traverse_variables) != 0)
3492 t = traverse->variable(*pb);
3493 if (t == TRAVERSE_CONTINUE
3494 && (traverse_mask & e_or_t) != 0)
3496 if ((*pb)->is_result_variable()
3497 || (*pb)->var_value()->has_type())
3499 Type* tv = ((*pb)->is_variable()
3500 ? (*pb)->var_value()->type()
3501 : (*pb)->result_var_value()->type());
3503 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3504 return TRAVERSE_EXIT;
3507 if (t == TRAVERSE_CONTINUE
3508 && (traverse_mask & e_or_t_or_s) != 0
3509 && (*pb)->is_variable())
3510 t = (*pb)->var_value()->traverse_expression(traverse,
3514 case Named_object::NAMED_OBJECT_FUNC:
3515 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3518 case Named_object::NAMED_OBJECT_TYPE:
3519 if ((traverse_mask & e_or_t) != 0)
3520 t = Type::traverse((*pb)->type_value(), traverse);
3523 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3524 case Named_object::NAMED_OBJECT_UNKNOWN:
3527 case Named_object::NAMED_OBJECT_PACKAGE:
3528 case Named_object::NAMED_OBJECT_SINK: