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 this->add_named_type(Type::make_integer_type("int32", false, 32,
62 RUNTIME_TYPE_KIND_INT32));
63 this->add_named_type(Type::make_integer_type("int64", false, 64,
64 RUNTIME_TYPE_KIND_INT64));
66 this->add_named_type(Type::make_float_type("float32", 32,
67 RUNTIME_TYPE_KIND_FLOAT32));
68 this->add_named_type(Type::make_float_type("float64", 64,
69 RUNTIME_TYPE_KIND_FLOAT64));
71 this->add_named_type(Type::make_complex_type("complex64", 64,
72 RUNTIME_TYPE_KIND_COMPLEX64));
73 this->add_named_type(Type::make_complex_type("complex128", 128,
74 RUNTIME_TYPE_KIND_COMPLEX128));
76 if (int_type_size < 32)
78 this->add_named_type(Type::make_integer_type("uint", true,
80 RUNTIME_TYPE_KIND_UINT));
81 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
82 RUNTIME_TYPE_KIND_INT);
83 this->add_named_type(int_type);
85 // "byte" is an alias for "uint8". Construct a Named_object which
86 // points to UINT8_TYPE. Note that this breaks the normal pairing
87 // in which a Named_object points to a Named_type which points back
88 // to the same Named_object.
89 Named_object* byte_type = this->declare_type("byte", loc);
90 byte_type->set_type_value(uint8_type);
91 uint8_type->integer_type()->set_is_byte();
93 // "rune" is an alias for "int".
94 Named_object* rune_type = this->declare_type("rune", loc);
95 rune_type->set_type_value(int_type);
96 int_type->integer_type()->set_is_rune();
98 this->add_named_type(Type::make_integer_type("uintptr", true,
100 RUNTIME_TYPE_KIND_UINTPTR));
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 Type *error_iface = Type::make_interface_type(methods, loc);
114 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
115 this->add_named_type(error_type);
118 this->globals_->add_constant(Typed_identifier("true",
119 Type::make_boolean_type(),
122 Expression::make_boolean(true, loc),
124 this->globals_->add_constant(Typed_identifier("false",
125 Type::make_boolean_type(),
128 Expression::make_boolean(false, loc),
131 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
134 Expression::make_nil(loc),
137 Type* abstract_int_type = Type::make_abstract_integer_type();
138 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
141 Expression::make_iota(),
144 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
145 new_type->set_is_varargs();
146 new_type->set_is_builtin();
147 this->globals_->add_function_declaration("new", NULL, new_type, loc);
149 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
150 make_type->set_is_varargs();
151 make_type->set_is_builtin();
152 this->globals_->add_function_declaration("make", NULL, make_type, loc);
154 Typed_identifier_list* len_result = new Typed_identifier_list();
155 len_result->push_back(Typed_identifier("", int_type, loc));
156 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
158 len_type->set_is_builtin();
159 this->globals_->add_function_declaration("len", NULL, len_type, loc);
161 Typed_identifier_list* cap_result = new Typed_identifier_list();
162 cap_result->push_back(Typed_identifier("", int_type, loc));
163 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
165 cap_type->set_is_builtin();
166 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
168 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
169 print_type->set_is_varargs();
170 print_type->set_is_builtin();
171 this->globals_->add_function_declaration("print", NULL, print_type, loc);
173 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
174 print_type->set_is_varargs();
175 print_type->set_is_builtin();
176 this->globals_->add_function_declaration("println", NULL, print_type, loc);
178 Type *empty = Type::make_interface_type(NULL, loc);
179 Typed_identifier_list* panic_parms = new Typed_identifier_list();
180 panic_parms->push_back(Typed_identifier("e", empty, loc));
181 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
183 panic_type->set_is_builtin();
184 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
186 Typed_identifier_list* recover_result = new Typed_identifier_list();
187 recover_result->push_back(Typed_identifier("", empty, loc));
188 Function_type* recover_type = Type::make_function_type(NULL, NULL,
191 recover_type->set_is_builtin();
192 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
194 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
195 close_type->set_is_varargs();
196 close_type->set_is_builtin();
197 this->globals_->add_function_declaration("close", NULL, close_type, loc);
199 Typed_identifier_list* copy_result = new Typed_identifier_list();
200 copy_result->push_back(Typed_identifier("", int_type, loc));
201 Function_type* copy_type = Type::make_function_type(NULL, NULL,
203 copy_type->set_is_varargs();
204 copy_type->set_is_builtin();
205 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
207 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
208 append_type->set_is_varargs();
209 append_type->set_is_builtin();
210 this->globals_->add_function_declaration("append", NULL, append_type, loc);
212 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
213 complex_type->set_is_varargs();
214 complex_type->set_is_builtin();
215 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
217 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
218 real_type->set_is_varargs();
219 real_type->set_is_builtin();
220 this->globals_->add_function_declaration("real", NULL, real_type, loc);
222 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
223 imag_type->set_is_varargs();
224 imag_type->set_is_builtin();
225 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
227 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
228 delete_type->set_is_varargs();
229 delete_type->set_is_builtin();
230 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
233 // Munge name for use in an error message.
236 Gogo::message_name(const std::string& name)
238 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
241 // Get the package name.
244 Gogo::package_name() const
246 go_assert(this->package_ != NULL);
247 return this->package_->name();
250 // Set the package name.
253 Gogo::set_package_name(const std::string& package_name,
256 if (this->package_ != NULL && this->package_->name() != package_name)
258 error_at(location, "expected package %<%s%>",
259 Gogo::message_name(this->package_->name()).c_str());
263 // If the user did not specify a unique prefix, we always use "go".
264 // This in effect requires that the package name be unique.
265 if (this->unique_prefix_.empty())
266 this->unique_prefix_ = "go";
268 this->package_ = this->register_package(package_name, this->unique_prefix_,
271 // We used to permit people to qualify symbols with the current
272 // package name (e.g., P.x), but we no longer do.
273 // this->globals_->add_package(package_name, this->package_);
275 if (this->is_main_package())
277 // Declare "main" as a function which takes no parameters and
279 Location uloc = Linemap::unknown_location();
280 this->declare_function("main",
281 Type::make_function_type (NULL, NULL, NULL, uloc),
286 // Return whether this is the "main" package. This is not true if
287 // -fgo-prefix was used.
290 Gogo::is_main_package() const
292 return this->package_name() == "main" && !this->unique_prefix_specified_;
298 Gogo::import_package(const std::string& filename,
299 const std::string& local_name,
300 bool is_local_name_exported,
303 if (filename == "unsafe")
305 this->import_unsafe(local_name, is_local_name_exported, location);
309 Imports::const_iterator p = this->imports_.find(filename);
310 if (p != this->imports_.end())
312 Package* package = p->second;
313 package->set_location(location);
314 package->set_is_imported();
315 std::string ln = local_name;
316 bool is_ln_exported = is_local_name_exported;
319 ln = package->name();
320 is_ln_exported = Lex::is_exported_name(ln);
324 Bindings* bindings = package->bindings();
325 for (Bindings::const_declarations_iterator p =
326 bindings->begin_declarations();
327 p != bindings->end_declarations();
329 this->add_named_object(p->second);
332 package->set_uses_sink_alias();
335 ln = this->pack_hidden_name(ln, is_ln_exported);
336 this->package_->bindings()->add_package(ln, package);
341 Import::Stream* stream = Import::open_package(filename, location);
344 error_at(location, "import file %qs not found", filename.c_str());
348 Import imp(stream, location);
349 imp.register_builtin_types(this);
350 Package* package = imp.import(this, local_name, is_local_name_exported);
353 if (package->name() == this->package_name()
354 && package->unique_prefix() == this->unique_prefix())
356 ("imported package uses same package name and prefix "
357 "as package being compiled (see -fgo-prefix option)"));
359 this->imports_.insert(std::make_pair(filename, package));
360 package->set_is_imported();
366 // Add an import control function for an imported package to the list.
369 Gogo::add_import_init_fn(const std::string& package_name,
370 const std::string& init_name, int prio)
372 for (std::set<Import_init>::const_iterator p =
373 this->imported_init_fns_.begin();
374 p != this->imported_init_fns_.end();
377 if (p->init_name() == init_name
378 && (p->package_name() != package_name || p->priority() != prio))
380 error("duplicate package initialization name %qs",
381 Gogo::message_name(init_name).c_str());
382 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
383 Gogo::message_name(p->package_name()).c_str(),
385 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
386 Gogo::message_name(package_name).c_str(), prio);
391 this->imported_init_fns_.insert(Import_init(package_name, init_name,
395 // Return whether we are at the global binding level.
398 Gogo::in_global_scope() const
400 return this->functions_.empty();
403 // Return the current binding contour.
406 Gogo::current_bindings()
408 if (!this->functions_.empty())
409 return this->functions_.back().blocks.back()->bindings();
410 else if (this->package_ != NULL)
411 return this->package_->bindings();
413 return this->globals_;
417 Gogo::current_bindings() const
419 if (!this->functions_.empty())
420 return this->functions_.back().blocks.back()->bindings();
421 else if (this->package_ != NULL)
422 return this->package_->bindings();
424 return this->globals_;
427 // Return the current block.
430 Gogo::current_block()
432 if (this->functions_.empty())
435 return this->functions_.back().blocks.back();
438 // Look up a name in the current binding contour. If PFUNCTION is not
439 // NULL, set it to the function in which the name is defined, or NULL
440 // if the name is defined in global scope.
443 Gogo::lookup(const std::string& name, Named_object** pfunction) const
445 if (pfunction != NULL)
448 if (Gogo::is_sink_name(name))
449 return Named_object::make_sink();
451 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
452 p != this->functions_.rend();
455 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
458 if (pfunction != NULL)
459 *pfunction = p->function;
464 if (this->package_ != NULL)
466 Named_object* ret = this->package_->bindings()->lookup(name);
469 if (ret->package() != NULL)
470 ret->package()->set_used();
475 // We do not look in the global namespace. If we did, the global
476 // namespace would effectively hide names which were defined in
477 // package scope which we have not yet seen. Instead,
478 // define_global_names is called after parsing is over to connect
479 // undefined names at package scope with names defined at global
485 // Look up a name in the current block, without searching enclosing
489 Gogo::lookup_in_block(const std::string& name) const
491 go_assert(!this->functions_.empty());
492 go_assert(!this->functions_.back().blocks.empty());
493 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
496 // Look up a name in the global namespace.
499 Gogo::lookup_global(const char* name) const
501 return this->globals_->lookup(name);
504 // Add an imported package.
507 Gogo::add_imported_package(const std::string& real_name,
508 const std::string& alias_arg,
509 bool is_alias_exported,
510 const std::string& unique_prefix,
512 bool* padd_to_globals)
514 // FIXME: Now that we compile packages as a whole, should we permit
515 // importing the current package?
516 if (this->package_name() == real_name
517 && this->unique_prefix() == unique_prefix)
519 *padd_to_globals = false;
520 if (!alias_arg.empty() && alias_arg != ".")
522 std::string alias = this->pack_hidden_name(alias_arg,
524 this->package_->bindings()->add_package(alias, this->package_);
526 return this->package_;
528 else if (alias_arg == ".")
530 *padd_to_globals = true;
531 return this->register_package(real_name, unique_prefix, location);
533 else if (alias_arg == "_")
535 Package* ret = this->register_package(real_name, unique_prefix, location);
536 ret->set_uses_sink_alias();
541 *padd_to_globals = false;
542 std::string alias = alias_arg;
546 is_alias_exported = Lex::is_exported_name(alias);
548 alias = this->pack_hidden_name(alias, is_alias_exported);
549 Named_object* no = this->add_package(real_name, alias, unique_prefix,
551 if (!no->is_package())
553 return no->package_value();
560 Gogo::add_package(const std::string& real_name, const std::string& alias,
561 const std::string& unique_prefix, Location location)
563 go_assert(this->in_global_scope());
565 // Register the package. Note that we might have already seen it in
566 // an earlier import.
567 Package* package = this->register_package(real_name, unique_prefix, location);
569 return this->package_->bindings()->add_package(alias, package);
572 // Register a package. This package may or may not be imported. This
573 // returns the Package structure for the package, creating if it
577 Gogo::register_package(const std::string& package_name,
578 const std::string& unique_prefix,
581 go_assert(!unique_prefix.empty() && !package_name.empty());
582 std::string name = unique_prefix + '.' + package_name;
583 Package* package = NULL;
584 std::pair<Packages::iterator, bool> ins =
585 this->packages_.insert(std::make_pair(name, package));
588 // We have seen this package name before.
589 package = ins.first->second;
590 go_assert(package != NULL);
591 go_assert(package->name() == package_name
592 && package->unique_prefix() == unique_prefix);
593 if (Linemap::is_unknown_location(package->location()))
594 package->set_location(location);
598 // First time we have seen this package name.
599 package = new Package(package_name, unique_prefix, location);
600 go_assert(ins.first->second == NULL);
601 ins.first->second = package;
607 // Start compiling a function.
610 Gogo::start_function(const std::string& name, Function_type* type,
611 bool add_method_to_type, Location location)
613 bool at_top_level = this->functions_.empty();
615 Block* block = new Block(NULL, location);
617 Function* enclosing = (at_top_level
619 : this->functions_.back().function->func_value());
621 Function* function = new Function(type, enclosing, block, location);
623 if (type->is_method())
625 const Typed_identifier* receiver = type->receiver();
626 Variable* this_param = new Variable(receiver->type(), NULL, false,
627 true, true, location);
628 std::string name = receiver->name();
631 // We need to give receivers a name since they wind up in
632 // DECL_ARGUMENTS. FIXME.
633 static unsigned int count;
635 snprintf(buf, sizeof buf, "r.%u", count);
639 block->bindings()->add_variable(name, NULL, this_param);
642 const Typed_identifier_list* parameters = type->parameters();
643 bool is_varargs = type->is_varargs();
644 if (parameters != NULL)
646 for (Typed_identifier_list::const_iterator p = parameters->begin();
647 p != parameters->end();
650 Variable* param = new Variable(p->type(), NULL, false, true, false,
652 if (is_varargs && p + 1 == parameters->end())
653 param->set_is_varargs_parameter();
655 std::string name = p->name();
656 if (name.empty() || Gogo::is_sink_name(name))
658 // We need to give parameters a name since they wind up
659 // in DECL_ARGUMENTS. FIXME.
660 static unsigned int count;
662 snprintf(buf, sizeof buf, "p.%u", count);
666 block->bindings()->add_variable(name, NULL, param);
670 function->create_result_variables(this);
672 const std::string* pname;
673 std::string nested_name;
674 bool is_init = false;
675 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
677 if ((type->parameters() != NULL && !type->parameters()->empty())
678 || (type->results() != NULL && !type->results()->empty()))
680 "func init must have no arguments and no return values");
681 // There can be multiple "init" functions, so give them each a
683 static int init_count;
685 snprintf(buf, sizeof buf, ".$init%d", init_count);
688 pname = &nested_name;
691 else if (!name.empty())
695 // Invent a name for a nested function.
696 static int nested_count;
698 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
701 pname = &nested_name;
705 if (Gogo::is_sink_name(*pname))
707 static int sink_count;
709 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
711 ret = Named_object::make_function(buf, NULL, function);
713 else if (!type->is_method())
715 ret = this->package_->bindings()->add_function(*pname, NULL, function);
716 if (!ret->is_function() || ret->func_value() != function)
718 // Redefinition error. Invent a name to avoid knockon
720 static int redefinition_count;
722 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
723 ++redefinition_count;
724 ret = this->package_->bindings()->add_function(buf, NULL, function);
729 if (!add_method_to_type)
730 ret = Named_object::make_function(name, NULL, function);
733 go_assert(at_top_level);
734 Type* rtype = type->receiver()->type();
736 // We want to look through the pointer created by the
737 // parser, without getting an error if the type is not yet
739 if (rtype->classification() == Type::TYPE_POINTER)
740 rtype = rtype->points_to();
742 if (rtype->is_error_type())
743 ret = Named_object::make_function(name, NULL, function);
744 else if (rtype->named_type() != NULL)
746 ret = rtype->named_type()->add_method(name, function);
747 if (!ret->is_function())
749 // Redefinition error.
750 ret = Named_object::make_function(name, NULL, function);
753 else if (rtype->forward_declaration_type() != NULL)
755 Named_object* type_no =
756 rtype->forward_declaration_type()->named_object();
757 if (type_no->is_unknown())
759 // If we are seeing methods it really must be a
760 // type. Declare it as such. An alternative would
761 // be to support lists of methods for unknown
762 // expressions. Either way the error messages if
763 // this is not a type are going to get confusing.
764 Named_object* declared =
765 this->declare_package_type(type_no->name(),
766 type_no->location());
768 == type_no->unknown_value()->real_named_object());
770 ret = rtype->forward_declaration_type()->add_method(name,
776 this->package_->bindings()->add_method(ret);
779 this->functions_.resize(this->functions_.size() + 1);
780 Open_function& of(this->functions_.back());
782 of.blocks.push_back(block);
786 this->init_functions_.push_back(ret);
787 this->need_init_fn_ = true;
793 // Finish compiling a function.
796 Gogo::finish_function(Location location)
798 this->finish_block(location);
799 go_assert(this->functions_.back().blocks.empty());
800 this->functions_.pop_back();
803 // Return the current function.
806 Gogo::current_function() const
808 go_assert(!this->functions_.empty());
809 return this->functions_.back().function;
812 // Start a new block.
815 Gogo::start_block(Location location)
817 go_assert(!this->functions_.empty());
818 Block* block = new Block(this->current_block(), location);
819 this->functions_.back().blocks.push_back(block);
825 Gogo::finish_block(Location location)
827 go_assert(!this->functions_.empty());
828 go_assert(!this->functions_.back().blocks.empty());
829 Block* block = this->functions_.back().blocks.back();
830 this->functions_.back().blocks.pop_back();
831 block->set_end_location(location);
835 // Add an unknown name.
838 Gogo::add_unknown_name(const std::string& name, Location location)
840 return this->package_->bindings()->add_unknown_name(name, location);
843 // Declare a function.
846 Gogo::declare_function(const std::string& name, Function_type* type,
849 if (!type->is_method())
850 return this->current_bindings()->add_function_declaration(name, NULL, type,
854 // We don't bother to add this to the list of global
856 Type* rtype = type->receiver()->type();
858 // We want to look through the pointer created by the
859 // parser, without getting an error if the type is not yet
861 if (rtype->classification() == Type::TYPE_POINTER)
862 rtype = rtype->points_to();
864 if (rtype->is_error_type())
866 else if (rtype->named_type() != NULL)
867 return rtype->named_type()->add_method_declaration(name, NULL, type,
869 else if (rtype->forward_declaration_type() != NULL)
871 Forward_declaration_type* ftype = rtype->forward_declaration_type();
872 return ftype->add_method_declaration(name, type, location);
879 // Add a label definition.
882 Gogo::add_label_definition(const std::string& label_name,
885 go_assert(!this->functions_.empty());
886 Function* func = this->functions_.back().function->func_value();
887 Label* label = func->add_label_definition(this, label_name, location);
888 this->add_statement(Statement::make_label_statement(label, location));
892 // Add a label reference.
895 Gogo::add_label_reference(const std::string& label_name,
896 Location location, bool issue_goto_errors)
898 go_assert(!this->functions_.empty());
899 Function* func = this->functions_.back().function->func_value();
900 return func->add_label_reference(this, label_name, location,
904 // Return the current binding state.
907 Gogo::bindings_snapshot(Location location)
909 return new Bindings_snapshot(this->current_block(), location);
915 Gogo::add_statement(Statement* statement)
917 go_assert(!this->functions_.empty()
918 && !this->functions_.back().blocks.empty());
919 this->functions_.back().blocks.back()->add_statement(statement);
925 Gogo::add_block(Block* block, Location location)
927 go_assert(!this->functions_.empty()
928 && !this->functions_.back().blocks.empty());
929 Statement* statement = Statement::make_block_statement(block, location);
930 this->functions_.back().blocks.back()->add_statement(statement);
936 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
939 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
945 Gogo::add_type(const std::string& name, Type* type, Location location)
947 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
949 if (!this->in_global_scope() && no->is_type())
950 no->type_value()->set_in_function(this->functions_.back().function);
956 Gogo::add_named_type(Named_type* type)
958 go_assert(this->in_global_scope());
959 this->current_bindings()->add_named_type(type);
965 Gogo::declare_type(const std::string& name, Location location)
967 Bindings* bindings = this->current_bindings();
968 Named_object* no = bindings->add_type_declaration(name, NULL, location);
969 if (!this->in_global_scope() && no->is_type_declaration())
971 Named_object* f = this->functions_.back().function;
972 no->type_declaration_value()->set_in_function(f);
977 // Declare a type at the package level.
980 Gogo::declare_package_type(const std::string& name, Location location)
982 return this->package_->bindings()->add_type_declaration(name, NULL, location);
985 // Declare a function at the package level.
988 Gogo::declare_package_function(const std::string& name, Function_type* type,
991 return this->package_->bindings()->add_function_declaration(name, NULL, type,
995 // Define a type which was already declared.
998 Gogo::define_type(Named_object* no, Named_type* type)
1000 this->current_bindings()->define_type(no, type);
1006 Gogo::add_variable(const std::string& name, Variable* variable)
1008 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1011 // In a function the middle-end wants to see a DECL_EXPR node.
1013 && no->is_variable()
1014 && !no->var_value()->is_parameter()
1015 && !this->functions_.empty())
1016 this->add_statement(Statement::make_variable_declaration(no));
1021 // Add a sink--a reference to the blank identifier _.
1026 return Named_object::make_sink();
1029 // Add a named object.
1032 Gogo::add_named_object(Named_object* no)
1034 this->current_bindings()->add_named_object(no);
1037 // Record that we've seen an interface type.
1040 Gogo::record_interface_type(Interface_type* itype)
1042 this->interface_types_.push_back(itype);
1045 // Return a name for a thunk object.
1050 static int thunk_count;
1051 char thunk_name[50];
1052 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1057 // Return whether a function is a thunk.
1060 Gogo::is_thunk(const Named_object* no)
1062 return no->name().compare(0, 6, "$thunk") == 0;
1065 // Define the global names. We do this only after parsing all the
1066 // input files, because the program might define the global names
1070 Gogo::define_global_names()
1072 for (Bindings::const_declarations_iterator p =
1073 this->globals_->begin_declarations();
1074 p != this->globals_->end_declarations();
1077 Named_object* global_no = p->second;
1078 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1079 Named_object* no = this->package_->bindings()->lookup(name);
1083 if (no->is_type_declaration())
1085 if (global_no->is_type())
1087 if (no->type_declaration_value()->has_methods())
1088 error_at(no->location(),
1089 "may not define methods for global type");
1090 no->set_type_value(global_no->type_value());
1094 error_at(no->location(), "expected type");
1095 Type* errtype = Type::make_error_type();
1097 Named_object::make_type("erroneous_type", NULL, errtype,
1098 Linemap::predeclared_location());
1099 no->set_type_value(err->type_value());
1102 else if (no->is_unknown())
1103 no->unknown_value()->set_real_named_object(global_no);
1107 // Clear out names in file scope.
1110 Gogo::clear_file_scope()
1112 this->package_->bindings()->clear_file_scope();
1114 // Warn about packages which were imported but not used.
1115 for (Packages::iterator p = this->packages_.begin();
1116 p != this->packages_.end();
1119 Package* package = p->second;
1120 if (package != this->package_
1121 && package->is_imported()
1123 && !package->uses_sink_alias()
1125 error_at(package->location(), "imported and not used: %s",
1126 Gogo::message_name(package->name()).c_str());
1127 package->clear_is_imported();
1128 package->clear_uses_sink_alias();
1129 package->clear_used();
1133 // Queue up a type specific function for later writing. These are
1134 // written out in write_specific_type_functions, called after the
1135 // parse tree is lowered.
1138 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1139 const std::string& hash_name,
1140 Function_type* hash_fntype,
1141 const std::string& equal_name,
1142 Function_type* equal_fntype)
1144 go_assert(!this->specific_type_functions_are_written_);
1145 go_assert(!this->in_global_scope());
1146 Specific_type_function* tsf = new Specific_type_function(type, name,
1151 this->specific_type_functions_.push_back(tsf);
1154 // Look for types which need specific hash or equality functions.
1156 class Specific_type_functions : public Traverse
1159 Specific_type_functions(Gogo* gogo)
1160 : Traverse(traverse_types),
1172 Specific_type_functions::type(Type* t)
1174 Named_object* hash_fn;
1175 Named_object* equal_fn;
1176 switch (t->classification())
1178 case Type::TYPE_NAMED:
1180 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1181 t->type_functions(this->gogo_, t->named_type(), NULL, NULL, &hash_fn,
1184 // If this is a struct type, we don't want to make functions
1185 // for the unnamed struct.
1186 Type* rt = t->named_type()->real_type();
1187 if (rt->struct_type() == NULL)
1189 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1190 return TRAVERSE_EXIT;
1194 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1195 return TRAVERSE_EXIT;
1198 return TRAVERSE_SKIP_COMPONENTS;
1201 case Type::TYPE_STRUCT:
1202 case Type::TYPE_ARRAY:
1203 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1204 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1211 return TRAVERSE_CONTINUE;
1214 // Write out type specific functions.
1217 Gogo::write_specific_type_functions()
1219 Specific_type_functions stf(this);
1220 this->traverse(&stf);
1222 while (!this->specific_type_functions_.empty())
1224 Specific_type_function* tsf = this->specific_type_functions_.back();
1225 this->specific_type_functions_.pop_back();
1226 tsf->type->write_specific_type_functions(this, tsf->name,
1233 this->specific_type_functions_are_written_ = true;
1236 // Traverse the tree.
1239 Gogo::traverse(Traverse* traverse)
1241 // Traverse the current package first for consistency. The other
1242 // packages will only contain imported types, constants, and
1244 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1246 for (Packages::const_iterator p = this->packages_.begin();
1247 p != this->packages_.end();
1250 if (p->second != this->package_)
1252 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1258 // Traversal class used to verify types.
1260 class Verify_types : public Traverse
1264 : Traverse(traverse_types)
1271 // Verify that a type is correct.
1274 Verify_types::type(Type* t)
1277 return TRAVERSE_SKIP_COMPONENTS;
1278 return TRAVERSE_CONTINUE;
1281 // Verify that all types are correct.
1284 Gogo::verify_types()
1286 Verify_types traverse;
1287 this->traverse(&traverse);
1290 // Traversal class used to lower parse tree.
1292 class Lower_parse_tree : public Traverse
1295 Lower_parse_tree(Gogo* gogo, Named_object* function)
1296 : Traverse(traverse_variables
1297 | traverse_constants
1298 | traverse_functions
1299 | traverse_statements
1300 | traverse_expressions),
1301 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1305 set_inserter(const Statement_inserter* inserter)
1306 { this->inserter_ = *inserter; }
1309 variable(Named_object*);
1312 constant(Named_object*, bool);
1315 function(Named_object*);
1318 statement(Block*, size_t* pindex, Statement*);
1321 expression(Expression**);
1326 // The function we are traversing.
1327 Named_object* function_;
1328 // Value to use for the predeclared constant iota.
1330 // Current statement inserter for use by expressions.
1331 Statement_inserter inserter_;
1337 Lower_parse_tree::variable(Named_object* no)
1339 if (!no->is_variable())
1340 return TRAVERSE_CONTINUE;
1342 if (no->is_variable() && no->var_value()->is_global())
1344 // Global variables can have loops in their initialization
1345 // expressions. This is handled in lower_init_expression.
1346 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1348 return TRAVERSE_CONTINUE;
1351 // This is a local variable. We are going to return
1352 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1353 // initialization expression when we reach the variable declaration
1354 // statement. However, that means that we need to traverse the type
1356 if (no->var_value()->has_type())
1358 Type* type = no->var_value()->type();
1361 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1362 return TRAVERSE_EXIT;
1365 go_assert(!no->var_value()->has_pre_init());
1367 return TRAVERSE_SKIP_COMPONENTS;
1370 // Lower constants. We handle constants specially so that we can set
1371 // the right value for the predeclared constant iota. This works in
1372 // conjunction with the way we lower Const_expression objects.
1375 Lower_parse_tree::constant(Named_object* no, bool)
1377 Named_constant* nc = no->const_value();
1379 // Don't get into trouble if the constant's initializer expression
1380 // refers to the constant itself.
1382 return TRAVERSE_CONTINUE;
1385 go_assert(this->iota_value_ == -1);
1386 this->iota_value_ = nc->iota_value();
1387 nc->traverse_expression(this);
1388 this->iota_value_ = -1;
1390 nc->clear_lowering();
1392 // We will traverse the expression a second time, but that will be
1395 return TRAVERSE_CONTINUE;
1398 // Lower function closure types. Record the function while lowering
1399 // it, so that we can pass it down when lowering an expression.
1402 Lower_parse_tree::function(Named_object* no)
1404 no->func_value()->set_closure_type();
1406 go_assert(this->function_ == NULL);
1407 this->function_ = no;
1408 int t = no->func_value()->traverse(this);
1409 this->function_ = NULL;
1411 if (t == TRAVERSE_EXIT)
1413 return TRAVERSE_SKIP_COMPONENTS;
1416 // Lower statement parse trees.
1419 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1421 // Because we explicitly traverse the statement's contents
1422 // ourselves, we want to skip block statements here. There is
1423 // nothing to lower in a block statement.
1424 if (sorig->is_block_statement())
1425 return TRAVERSE_CONTINUE;
1427 Statement_inserter hold_inserter(this->inserter_);
1428 this->inserter_ = Statement_inserter(block, pindex);
1430 // Lower the expressions first.
1431 int t = sorig->traverse_contents(this);
1432 if (t == TRAVERSE_EXIT)
1434 this->inserter_ = hold_inserter;
1438 // Keep lowering until nothing changes.
1439 Statement* s = sorig;
1442 Statement* snew = s->lower(this->gogo_, this->function_, block,
1447 t = s->traverse_contents(this);
1448 if (t == TRAVERSE_EXIT)
1450 this->inserter_ = hold_inserter;
1456 block->replace_statement(*pindex, s);
1458 this->inserter_ = hold_inserter;
1459 return TRAVERSE_SKIP_COMPONENTS;
1462 // Lower expression parse trees.
1465 Lower_parse_tree::expression(Expression** pexpr)
1467 // We have to lower all subexpressions first, so that we can get
1468 // their type if necessary. This is awkward, because we don't have
1469 // a postorder traversal pass.
1470 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1471 return TRAVERSE_EXIT;
1472 // Keep lowering until nothing changes.
1475 Expression* e = *pexpr;
1476 Expression* enew = e->lower(this->gogo_, this->function_,
1477 &this->inserter_, this->iota_value_);
1482 return TRAVERSE_SKIP_COMPONENTS;
1485 // Lower the parse tree. This is called after the parse is complete,
1486 // when all names should be resolved.
1489 Gogo::lower_parse_tree()
1491 Lower_parse_tree lower_parse_tree(this, NULL);
1492 this->traverse(&lower_parse_tree);
1498 Gogo::lower_block(Named_object* function, Block* block)
1500 Lower_parse_tree lower_parse_tree(this, function);
1501 block->traverse(&lower_parse_tree);
1504 // Lower an expression. INSERTER may be NULL, in which case the
1505 // expression had better not need to create any temporaries.
1508 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1511 Lower_parse_tree lower_parse_tree(this, function);
1512 if (inserter != NULL)
1513 lower_parse_tree.set_inserter(inserter);
1514 lower_parse_tree.expression(pexpr);
1517 // Lower a constant. This is called when lowering a reference to a
1518 // constant. We have to make sure that the constant has already been
1522 Gogo::lower_constant(Named_object* no)
1524 go_assert(no->is_const());
1525 Lower_parse_tree lower(this, NULL);
1526 lower.constant(no, false);
1529 // Look for interface types to finalize methods of inherited
1532 class Finalize_methods : public Traverse
1535 Finalize_methods(Gogo* gogo)
1536 : Traverse(traverse_types),
1547 // Finalize the methods of an interface type.
1550 Finalize_methods::type(Type* t)
1552 // Check the classification so that we don't finalize the methods
1553 // twice for a named interface type.
1554 switch (t->classification())
1556 case Type::TYPE_INTERFACE:
1557 t->interface_type()->finalize_methods();
1560 case Type::TYPE_NAMED:
1562 // We have to finalize the methods of the real type first.
1563 // But if the real type is a struct type, then we only want to
1564 // finalize the methods of the field types, not of the struct
1565 // type itself. We don't want to add methods to the struct,
1566 // since it has a name.
1567 Type* rt = t->named_type()->real_type();
1568 if (rt->classification() != Type::TYPE_STRUCT)
1570 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1571 return TRAVERSE_EXIT;
1575 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1576 return TRAVERSE_EXIT;
1579 t->named_type()->finalize_methods(this->gogo_);
1581 return TRAVERSE_SKIP_COMPONENTS;
1584 case Type::TYPE_STRUCT:
1585 t->struct_type()->finalize_methods(this->gogo_);
1592 return TRAVERSE_CONTINUE;
1595 // Finalize method lists and build stub methods for types.
1598 Gogo::finalize_methods()
1600 Finalize_methods finalize(this);
1601 this->traverse(&finalize);
1604 // Set types for unspecified variables and constants.
1607 Gogo::determine_types()
1609 Bindings* bindings = this->current_bindings();
1610 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1611 p != bindings->end_definitions();
1614 if ((*p)->is_function())
1615 (*p)->func_value()->determine_types();
1616 else if ((*p)->is_variable())
1617 (*p)->var_value()->determine_type();
1618 else if ((*p)->is_const())
1619 (*p)->const_value()->determine_type();
1621 // See if a variable requires us to build an initialization
1622 // function. We know that we will see all global variables
1624 if (!this->need_init_fn_ && (*p)->is_variable())
1626 Variable* variable = (*p)->var_value();
1628 // If this is a global variable which requires runtime
1629 // initialization, we need an initialization function.
1630 if (!variable->is_global())
1632 else if (variable->init() == NULL)
1634 else if (variable->type()->interface_type() != NULL)
1635 this->need_init_fn_ = true;
1636 else if (variable->init()->is_constant())
1638 else if (!variable->init()->is_composite_literal())
1639 this->need_init_fn_ = true;
1640 else if (variable->init()->is_nonconstant_composite_literal())
1641 this->need_init_fn_ = true;
1643 // If this is a global variable which holds a pointer value,
1644 // then we need an initialization function to register it as a
1646 if (variable->is_global() && variable->type()->has_pointer())
1647 this->need_init_fn_ = true;
1651 // Determine the types of constants in packages.
1652 for (Packages::const_iterator p = this->packages_.begin();
1653 p != this->packages_.end();
1655 p->second->determine_types();
1658 // Traversal class used for type checking.
1660 class Check_types_traverse : public Traverse
1663 Check_types_traverse(Gogo* gogo)
1664 : Traverse(traverse_variables
1665 | traverse_constants
1666 | traverse_functions
1667 | traverse_statements
1668 | traverse_expressions),
1673 variable(Named_object*);
1676 constant(Named_object*, bool);
1679 function(Named_object*);
1682 statement(Block*, size_t* pindex, Statement*);
1685 expression(Expression**);
1692 // Check that a variable initializer has the right type.
1695 Check_types_traverse::variable(Named_object* named_object)
1697 if (named_object->is_variable())
1699 Variable* var = named_object->var_value();
1701 // Give error if variable type is not defined.
1702 var->type()->base();
1704 Expression* init = var->init();
1707 && !Type::are_assignable(var->type(), init->type(), &reason))
1710 error_at(var->location(), "incompatible type in initialization");
1712 error_at(var->location(),
1713 "incompatible type in initialization (%s)",
1718 return TRAVERSE_CONTINUE;
1721 // Check that a constant initializer has the right type.
1724 Check_types_traverse::constant(Named_object* named_object, bool)
1726 Named_constant* constant = named_object->const_value();
1727 Type* ctype = constant->type();
1728 if (ctype->integer_type() == NULL
1729 && ctype->float_type() == NULL
1730 && ctype->complex_type() == NULL
1731 && !ctype->is_boolean_type()
1732 && !ctype->is_string_type())
1734 if (ctype->is_nil_type())
1735 error_at(constant->location(), "const initializer cannot be nil");
1736 else if (!ctype->is_error())
1737 error_at(constant->location(), "invalid constant type");
1738 constant->set_error();
1740 else if (!constant->expr()->is_constant())
1742 error_at(constant->expr()->location(), "expression is not constant");
1743 constant->set_error();
1745 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1748 error_at(constant->location(),
1749 "initialization expression has wrong type");
1750 constant->set_error();
1752 return TRAVERSE_CONTINUE;
1755 // There are no types to check in a function, but this is where we
1756 // issue warnings about labels which are defined but not referenced.
1759 Check_types_traverse::function(Named_object* no)
1761 no->func_value()->check_labels();
1762 return TRAVERSE_CONTINUE;
1765 // Check that types are valid in a statement.
1768 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1770 s->check_types(this->gogo_);
1771 return TRAVERSE_CONTINUE;
1774 // Check that types are valid in an expression.
1777 Check_types_traverse::expression(Expression** expr)
1779 (*expr)->check_types(this->gogo_);
1780 return TRAVERSE_CONTINUE;
1783 // Check that types are valid.
1788 Check_types_traverse traverse(this);
1789 this->traverse(&traverse);
1792 // Check the types in a single block.
1795 Gogo::check_types_in_block(Block* block)
1797 Check_types_traverse traverse(this);
1798 block->traverse(&traverse);
1801 // A traversal class used to find a single shortcut operator within an
1804 class Find_shortcut : public Traverse
1808 : Traverse(traverse_blocks
1809 | traverse_statements
1810 | traverse_expressions),
1814 // A pointer to the expression which was found, or NULL if none was
1818 { return this->found_; }
1823 { return TRAVERSE_SKIP_COMPONENTS; }
1826 statement(Block*, size_t*, Statement*)
1827 { return TRAVERSE_SKIP_COMPONENTS; }
1830 expression(Expression**);
1833 Expression** found_;
1836 // Find a shortcut expression.
1839 Find_shortcut::expression(Expression** pexpr)
1841 Expression* expr = *pexpr;
1842 Binary_expression* be = expr->binary_expression();
1844 return TRAVERSE_CONTINUE;
1845 Operator op = be->op();
1846 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1847 return TRAVERSE_CONTINUE;
1848 go_assert(this->found_ == NULL);
1849 this->found_ = pexpr;
1850 return TRAVERSE_EXIT;
1853 // A traversal class used to turn shortcut operators into explicit if
1856 class Shortcuts : public Traverse
1859 Shortcuts(Gogo* gogo)
1860 : Traverse(traverse_variables
1861 | traverse_statements),
1867 variable(Named_object*);
1870 statement(Block*, size_t*, Statement*);
1873 // Convert a shortcut operator.
1875 convert_shortcut(Block* enclosing, Expression** pshortcut);
1881 // Remove shortcut operators in a single statement.
1884 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1886 // FIXME: This approach doesn't work for switch statements, because
1887 // we add the new statements before the whole switch when we need to
1888 // instead add them just before the switch expression. The right
1889 // fix is probably to lower switch statements with nonconstant cases
1890 // to a series of conditionals.
1891 if (s->switch_statement() != NULL)
1892 return TRAVERSE_CONTINUE;
1896 Find_shortcut find_shortcut;
1898 // If S is a variable declaration, then ordinary traversal won't
1899 // do anything. We want to explicitly traverse the
1900 // initialization expression if there is one.
1901 Variable_declaration_statement* vds = s->variable_declaration_statement();
1902 Expression* init = NULL;
1904 s->traverse_contents(&find_shortcut);
1907 init = vds->var()->var_value()->init();
1909 return TRAVERSE_CONTINUE;
1910 init->traverse(&init, &find_shortcut);
1912 Expression** pshortcut = find_shortcut.found();
1913 if (pshortcut == NULL)
1914 return TRAVERSE_CONTINUE;
1916 Statement* snew = this->convert_shortcut(block, pshortcut);
1917 block->insert_statement_before(*pindex, snew);
1920 if (pshortcut == &init)
1921 vds->var()->var_value()->set_init(init);
1925 // Remove shortcut operators in the initializer of a global variable.
1928 Shortcuts::variable(Named_object* no)
1930 if (no->is_result_variable())
1931 return TRAVERSE_CONTINUE;
1932 Variable* var = no->var_value();
1933 Expression* init = var->init();
1934 if (!var->is_global() || init == NULL)
1935 return TRAVERSE_CONTINUE;
1939 Find_shortcut find_shortcut;
1940 init->traverse(&init, &find_shortcut);
1941 Expression** pshortcut = find_shortcut.found();
1942 if (pshortcut == NULL)
1943 return TRAVERSE_CONTINUE;
1945 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1946 var->add_preinit_statement(this->gogo_, snew);
1947 if (pshortcut == &init)
1948 var->set_init(init);
1952 // Given an expression which uses a shortcut operator, return a
1953 // statement which implements it, and update *PSHORTCUT accordingly.
1956 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1958 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1959 Expression* left = shortcut->left();
1960 Expression* right = shortcut->right();
1961 Location loc = shortcut->location();
1963 Block* retblock = new Block(enclosing, loc);
1964 retblock->set_end_location(loc);
1966 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1968 retblock->add_statement(ts);
1970 Block* block = new Block(retblock, loc);
1971 block->set_end_location(loc);
1972 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1973 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1974 block->add_statement(assign);
1976 Expression* cond = Expression::make_temporary_reference(ts, loc);
1977 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1978 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1980 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1982 retblock->add_statement(if_statement);
1984 *pshortcut = Expression::make_temporary_reference(ts, loc);
1988 // Now convert any shortcut operators in LEFT and RIGHT.
1989 Shortcuts shortcuts(this->gogo_);
1990 retblock->traverse(&shortcuts);
1992 return Statement::make_block_statement(retblock, loc);
1995 // Turn shortcut operators into explicit if statements. Doing this
1996 // considerably simplifies the order of evaluation rules.
1999 Gogo::remove_shortcuts()
2001 Shortcuts shortcuts(this);
2002 this->traverse(&shortcuts);
2005 // A traversal class which finds all the expressions which must be
2006 // evaluated in order within a statement or larger expression. This
2007 // is used to implement the rules about order of evaluation.
2009 class Find_eval_ordering : public Traverse
2012 typedef std::vector<Expression**> Expression_pointers;
2015 Find_eval_ordering()
2016 : Traverse(traverse_blocks
2017 | traverse_statements
2018 | traverse_expressions),
2024 { return this->exprs_.size(); }
2026 typedef Expression_pointers::const_iterator const_iterator;
2030 { return this->exprs_.begin(); }
2034 { return this->exprs_.end(); }
2039 { return TRAVERSE_SKIP_COMPONENTS; }
2042 statement(Block*, size_t*, Statement*)
2043 { return TRAVERSE_SKIP_COMPONENTS; }
2046 expression(Expression**);
2049 // A list of pointers to expressions with side-effects.
2050 Expression_pointers exprs_;
2053 // If an expression must be evaluated in order, put it on the list.
2056 Find_eval_ordering::expression(Expression** expression_pointer)
2058 // We have to look at subexpressions before this one.
2059 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2060 return TRAVERSE_EXIT;
2061 if ((*expression_pointer)->must_eval_in_order())
2062 this->exprs_.push_back(expression_pointer);
2063 return TRAVERSE_SKIP_COMPONENTS;
2066 // A traversal class for ordering evaluations.
2068 class Order_eval : public Traverse
2071 Order_eval(Gogo* gogo)
2072 : Traverse(traverse_variables
2073 | traverse_statements),
2078 variable(Named_object*);
2081 statement(Block*, size_t*, Statement*);
2088 // Implement the order of evaluation rules for a statement.
2091 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2093 // FIXME: This approach doesn't work for switch statements, because
2094 // we add the new statements before the whole switch when we need to
2095 // instead add them just before the switch expression. The right
2096 // fix is probably to lower switch statements with nonconstant cases
2097 // to a series of conditionals.
2098 if (s->switch_statement() != NULL)
2099 return TRAVERSE_CONTINUE;
2101 Find_eval_ordering find_eval_ordering;
2103 // If S is a variable declaration, then ordinary traversal won't do
2104 // anything. We want to explicitly traverse the initialization
2105 // expression if there is one.
2106 Variable_declaration_statement* vds = s->variable_declaration_statement();
2107 Expression* init = NULL;
2108 Expression* orig_init = NULL;
2110 s->traverse_contents(&find_eval_ordering);
2113 init = vds->var()->var_value()->init();
2115 return TRAVERSE_CONTINUE;
2118 // It might seem that this could be
2119 // init->traverse_subexpressions. Unfortunately that can fail
2122 // newvar, err := call(arg())
2123 // Here newvar will have an init of call result 0 of
2124 // call(arg()). If we only traverse subexpressions, we will
2125 // only find arg(), and we won't bother to move anything out.
2126 // Then we get to the assignment to err, we will traverse the
2127 // whole statement, and this time we will find both call() and
2128 // arg(), and so we will move them out. This will cause them to
2129 // be put into temporary variables before the assignment to err
2130 // but after the declaration of newvar. To avoid that problem,
2131 // we traverse the entire expression here.
2132 Expression::traverse(&init, &find_eval_ordering);
2135 if (find_eval_ordering.size() <= 1)
2137 // If there is only one expression with a side-effect, we can
2138 // leave it in place.
2139 return TRAVERSE_CONTINUE;
2142 bool is_thunk = s->thunk_statement() != NULL;
2143 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2144 p != find_eval_ordering.end();
2147 Expression** pexpr = *p;
2149 // The last expression in a thunk will be the call passed to go
2150 // or defer, which we must not evaluate early.
2151 if (is_thunk && p + 1 == find_eval_ordering.end())
2154 Location loc = (*pexpr)->location();
2156 if ((*pexpr)->call_expression() == NULL
2157 || (*pexpr)->call_expression()->result_count() < 2)
2159 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2162 *pexpr = Expression::make_temporary_reference(ts, loc);
2166 // A call expression which returns multiple results needs to
2167 // be handled specially. We can't create a temporary
2168 // because there is no type to give it. Any actual uses of
2169 // the values will be done via Call_result_expressions.
2170 s = Statement::make_statement(*pexpr, true);
2173 block->insert_statement_before(*pindex, s);
2177 if (init != orig_init)
2178 vds->var()->var_value()->set_init(init);
2180 return TRAVERSE_CONTINUE;
2183 // Implement the order of evaluation rules for the initializer of a
2187 Order_eval::variable(Named_object* no)
2189 if (no->is_result_variable())
2190 return TRAVERSE_CONTINUE;
2191 Variable* var = no->var_value();
2192 Expression* init = var->init();
2193 if (!var->is_global() || init == NULL)
2194 return TRAVERSE_CONTINUE;
2196 Find_eval_ordering find_eval_ordering;
2197 Expression::traverse(&init, &find_eval_ordering);
2199 if (find_eval_ordering.size() <= 1)
2201 // If there is only one expression with a side-effect, we can
2202 // leave it in place.
2203 return TRAVERSE_SKIP_COMPONENTS;
2206 Expression* orig_init = init;
2208 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2209 p != find_eval_ordering.end();
2212 Expression** pexpr = *p;
2213 Location loc = (*pexpr)->location();
2215 if ((*pexpr)->call_expression() == NULL
2216 || (*pexpr)->call_expression()->result_count() < 2)
2218 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2221 *pexpr = Expression::make_temporary_reference(ts, loc);
2225 // A call expression which returns multiple results needs to
2226 // be handled specially.
2227 s = Statement::make_statement(*pexpr, true);
2229 var->add_preinit_statement(this->gogo_, s);
2232 if (init != orig_init)
2233 var->set_init(init);
2235 return TRAVERSE_SKIP_COMPONENTS;
2238 // Use temporary variables to implement the order of evaluation rules.
2241 Gogo::order_evaluations()
2243 Order_eval order_eval(this);
2244 this->traverse(&order_eval);
2247 // Traversal to convert calls to the predeclared recover function to
2248 // pass in an argument indicating whether it can recover from a panic
2251 class Convert_recover : public Traverse
2254 Convert_recover(Named_object* arg)
2255 : Traverse(traverse_expressions),
2261 expression(Expression**);
2264 // The argument to pass to the function.
2268 // Convert calls to recover.
2271 Convert_recover::expression(Expression** pp)
2273 Call_expression* ce = (*pp)->call_expression();
2274 if (ce != NULL && ce->is_recover_call())
2275 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2277 return TRAVERSE_CONTINUE;
2280 // Traversal for build_recover_thunks.
2282 class Build_recover_thunks : public Traverse
2285 Build_recover_thunks(Gogo* gogo)
2286 : Traverse(traverse_functions),
2291 function(Named_object*);
2295 can_recover_arg(Location);
2301 // If this function calls recover, turn it into a thunk.
2304 Build_recover_thunks::function(Named_object* orig_no)
2306 Function* orig_func = orig_no->func_value();
2307 if (!orig_func->calls_recover()
2308 || orig_func->is_recover_thunk()
2309 || orig_func->has_recover_thunk())
2310 return TRAVERSE_CONTINUE;
2312 Gogo* gogo = this->gogo_;
2313 Location location = orig_func->location();
2318 Function_type* orig_fntype = orig_func->type();
2319 Typed_identifier_list* new_params = new Typed_identifier_list();
2320 std::string receiver_name;
2321 if (orig_fntype->is_method())
2323 const Typed_identifier* receiver = orig_fntype->receiver();
2324 snprintf(buf, sizeof buf, "rt.%u", count);
2326 receiver_name = buf;
2327 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2328 receiver->location()));
2330 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2331 if (orig_params != NULL && !orig_params->empty())
2333 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2334 p != orig_params->end();
2337 snprintf(buf, sizeof buf, "pt.%u", count);
2339 new_params->push_back(Typed_identifier(buf, p->type(),
2343 snprintf(buf, sizeof buf, "pr.%u", count);
2345 std::string can_recover_name = buf;
2346 new_params->push_back(Typed_identifier(can_recover_name,
2347 Type::lookup_bool_type(),
2348 orig_fntype->location()));
2350 const Typed_identifier_list* orig_results = orig_fntype->results();
2351 Typed_identifier_list* new_results;
2352 if (orig_results == NULL || orig_results->empty())
2356 new_results = new Typed_identifier_list();
2357 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2358 p != orig_results->end();
2360 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2363 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2365 orig_fntype->location());
2366 if (orig_fntype->is_varargs())
2367 new_fntype->set_is_varargs();
2369 std::string name = orig_no->name() + "$recover";
2370 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2372 Function *new_func = new_no->func_value();
2373 if (orig_func->enclosing() != NULL)
2374 new_func->set_enclosing(orig_func->enclosing());
2376 // We build the code for the original function attached to the new
2377 // function, and then swap the original and new function bodies.
2378 // This means that existing references to the original function will
2379 // then refer to the new function. That makes this code a little
2380 // confusing, in that the reference to NEW_NO really refers to the
2381 // other function, not the one we are building.
2383 Expression* closure = NULL;
2384 if (orig_func->needs_closure())
2386 Named_object* orig_closure_no = orig_func->closure_var();
2387 Variable* orig_closure_var = orig_closure_no->var_value();
2388 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2389 true, false, location);
2390 snprintf(buf, sizeof buf, "closure.%u", count);
2392 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2394 new_func->set_closure_var(new_closure_no);
2395 closure = Expression::make_var_reference(new_closure_no, location);
2398 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2400 Expression_list* args = new Expression_list();
2401 if (new_params != NULL)
2403 // Note that we skip the last parameter, which is the boolean
2404 // indicating whether recover can succed.
2405 for (Typed_identifier_list::const_iterator p = new_params->begin();
2406 p + 1 != new_params->end();
2409 Named_object* p_no = gogo->lookup(p->name(), NULL);
2410 go_assert(p_no != NULL
2411 && p_no->is_variable()
2412 && p_no->var_value()->is_parameter());
2413 args->push_back(Expression::make_var_reference(p_no, location));
2416 args->push_back(this->can_recover_arg(location));
2418 gogo->start_block(location);
2420 Call_expression* call = Expression::make_call(fn, args, false, location);
2423 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2424 s = Statement::make_statement(call, true);
2427 Expression_list* vals = new Expression_list();
2428 size_t rc = orig_fntype->results()->size();
2430 vals->push_back(call);
2433 for (size_t i = 0; i < rc; ++i)
2434 vals->push_back(Expression::make_call_result(call, i));
2436 s = Statement::make_return_statement(vals, location);
2438 s->determine_types();
2439 gogo->add_statement(s);
2441 Block* b = gogo->finish_block(location);
2443 gogo->add_block(b, location);
2445 // Lower the call in case it returns multiple results.
2446 gogo->lower_block(new_no, b);
2448 gogo->finish_function(location);
2450 // Swap the function bodies and types.
2451 new_func->swap_for_recover(orig_func);
2452 orig_func->set_is_recover_thunk();
2453 new_func->set_calls_recover();
2454 new_func->set_has_recover_thunk();
2456 Bindings* orig_bindings = orig_func->block()->bindings();
2457 Bindings* new_bindings = new_func->block()->bindings();
2458 if (orig_fntype->is_method())
2460 // We changed the receiver to be a regular parameter. We have
2461 // to update the binding accordingly in both functions.
2462 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2463 go_assert(orig_rec_no != NULL
2464 && orig_rec_no->is_variable()
2465 && !orig_rec_no->var_value()->is_receiver());
2466 orig_rec_no->var_value()->set_is_receiver();
2468 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2469 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2470 if (new_rec_no == NULL)
2471 go_assert(saw_errors());
2474 go_assert(new_rec_no->is_variable()
2475 && new_rec_no->var_value()->is_receiver());
2476 new_rec_no->var_value()->set_is_not_receiver();
2480 // Because we flipped blocks but not types, the can_recover
2481 // parameter appears in the (now) old bindings as a parameter.
2482 // Change it to a local variable, whereupon it will be discarded.
2483 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2484 go_assert(can_recover_no != NULL
2485 && can_recover_no->is_variable()
2486 && can_recover_no->var_value()->is_parameter());
2487 orig_bindings->remove_binding(can_recover_no);
2489 // Add the can_recover argument to the (now) new bindings, and
2490 // attach it to any recover statements.
2491 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2492 false, true, false, location);
2493 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2495 Convert_recover convert_recover(can_recover_no);
2496 new_func->traverse(&convert_recover);
2498 // Update the function pointers in any named results.
2499 new_func->update_result_variables();
2500 orig_func->update_result_variables();
2502 return TRAVERSE_CONTINUE;
2505 // Return the expression to pass for the .can_recover parameter to the
2506 // new function. This indicates whether a call to recover may return
2507 // non-nil. The expression is
2508 // __go_can_recover(__builtin_return_address()).
2511 Build_recover_thunks::can_recover_arg(Location location)
2513 static Named_object* builtin_return_address;
2514 if (builtin_return_address == NULL)
2516 const Location bloc = Linemap::predeclared_location();
2518 Typed_identifier_list* param_types = new Typed_identifier_list();
2519 Type* uint_type = Type::lookup_integer_type("uint");
2520 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2522 Typed_identifier_list* return_types = new Typed_identifier_list();
2523 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2524 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2526 Function_type* fntype = Type::make_function_type(NULL, param_types,
2527 return_types, bloc);
2528 builtin_return_address =
2529 Named_object::make_function_declaration("__builtin_return_address",
2530 NULL, fntype, bloc);
2531 const char* n = "__builtin_return_address";
2532 builtin_return_address->func_declaration_value()->set_asm_name(n);
2535 static Named_object* can_recover;
2536 if (can_recover == NULL)
2538 const Location bloc = Linemap::predeclared_location();
2539 Typed_identifier_list* param_types = new Typed_identifier_list();
2540 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2541 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2542 Type* boolean_type = Type::lookup_bool_type();
2543 Typed_identifier_list* results = new Typed_identifier_list();
2544 results->push_back(Typed_identifier("", boolean_type, bloc));
2545 Function_type* fntype = Type::make_function_type(NULL, param_types,
2547 can_recover = Named_object::make_function_declaration("__go_can_recover",
2550 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2553 Expression* fn = Expression::make_func_reference(builtin_return_address,
2557 mpz_init_set_ui(zval, 0UL);
2558 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2560 Expression_list *args = new Expression_list();
2561 args->push_back(zexpr);
2563 Expression* call = Expression::make_call(fn, args, false, location);
2565 args = new Expression_list();
2566 args->push_back(call);
2568 fn = Expression::make_func_reference(can_recover, NULL, location);
2569 return Expression::make_call(fn, args, false, location);
2572 // Build thunks for functions which call recover. We build a new
2573 // function with an extra parameter, which is whether a call to
2574 // recover can succeed. We then move the body of this function to
2575 // that one. We then turn this function into a thunk which calls the
2576 // new one, passing the value of
2577 // __go_can_recover(__builtin_return_address()). The function will be
2578 // marked as not splitting the stack. This will cooperate with the
2579 // implementation of defer to make recover do the right thing.
2582 Gogo::build_recover_thunks()
2584 Build_recover_thunks build_recover_thunks(this);
2585 this->traverse(&build_recover_thunks);
2588 // Look for named types to see whether we need to create an interface
2591 class Build_method_tables : public Traverse
2594 Build_method_tables(Gogo* gogo,
2595 const std::vector<Interface_type*>& interfaces)
2596 : Traverse(traverse_types),
2597 gogo_(gogo), interfaces_(interfaces)
2606 // A list of locally defined interfaces which have hidden methods.
2607 const std::vector<Interface_type*>& interfaces_;
2610 // Build all required interface method tables for types. We need to
2611 // ensure that we have an interface method table for every interface
2612 // which has a hidden method, for every named type which implements
2613 // that interface. Normally we can just build interface method tables
2614 // as we need them. However, in some cases we can require an
2615 // interface method table for an interface defined in a different
2616 // package for a type defined in that package. If that interface and
2617 // type both use a hidden method, that is OK. However, we will not be
2618 // able to build that interface method table when we need it, because
2619 // the type's hidden method will be static. So we have to build it
2620 // here, and just refer it from other packages as needed.
2623 Gogo::build_interface_method_tables()
2625 std::vector<Interface_type*> hidden_interfaces;
2626 hidden_interfaces.reserve(this->interface_types_.size());
2627 for (std::vector<Interface_type*>::const_iterator pi =
2628 this->interface_types_.begin();
2629 pi != this->interface_types_.end();
2632 const Typed_identifier_list* methods = (*pi)->methods();
2633 if (methods == NULL)
2635 for (Typed_identifier_list::const_iterator pm = methods->begin();
2636 pm != methods->end();
2639 if (Gogo::is_hidden_name(pm->name()))
2641 hidden_interfaces.push_back(*pi);
2647 if (!hidden_interfaces.empty())
2649 // Now traverse the tree looking for all named types.
2650 Build_method_tables bmt(this, hidden_interfaces);
2651 this->traverse(&bmt);
2654 // We no longer need the list of interfaces.
2656 this->interface_types_.clear();
2659 // This is called for each type. For a named type, for each of the
2660 // interfaces with hidden methods that it implements, create the
2664 Build_method_tables::type(Type* type)
2666 Named_type* nt = type->named_type();
2669 for (std::vector<Interface_type*>::const_iterator p =
2670 this->interfaces_.begin();
2671 p != this->interfaces_.end();
2674 // We ask whether a pointer to the named type implements the
2675 // interface, because a pointer can implement more methods
2677 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2679 nt->interface_method_table(this->gogo_, *p, false);
2680 nt->interface_method_table(this->gogo_, *p, true);
2684 return TRAVERSE_CONTINUE;
2687 // Traversal class used to check for return statements.
2689 class Check_return_statements_traverse : public Traverse
2692 Check_return_statements_traverse()
2693 : Traverse(traverse_functions)
2697 function(Named_object*);
2700 // Check that a function has a return statement if it needs one.
2703 Check_return_statements_traverse::function(Named_object* no)
2705 Function* func = no->func_value();
2706 const Function_type* fntype = func->type();
2707 const Typed_identifier_list* results = fntype->results();
2709 // We only need a return statement if there is a return value.
2710 if (results == NULL || results->empty())
2711 return TRAVERSE_CONTINUE;
2713 if (func->block()->may_fall_through())
2714 error_at(func->location(), "control reaches end of non-void function");
2716 return TRAVERSE_CONTINUE;
2719 // Check return statements.
2722 Gogo::check_return_statements()
2724 Check_return_statements_traverse traverse;
2725 this->traverse(&traverse);
2728 // Get the unique prefix to use before all exported symbols. This
2729 // must be unique across the entire link.
2732 Gogo::unique_prefix() const
2734 go_assert(!this->unique_prefix_.empty());
2735 return this->unique_prefix_;
2738 // Set the unique prefix to use before all exported symbols. This
2739 // comes from the command line option -fgo-prefix=XXX.
2742 Gogo::set_unique_prefix(const std::string& arg)
2744 go_assert(this->unique_prefix_.empty());
2745 this->unique_prefix_ = arg;
2746 this->unique_prefix_specified_ = true;
2749 // Work out the package priority. It is one more than the maximum
2750 // priority of an imported package.
2753 Gogo::package_priority() const
2756 for (Packages::const_iterator p = this->packages_.begin();
2757 p != this->packages_.end();
2759 if (p->second->priority() > priority)
2760 priority = p->second->priority();
2761 return priority + 1;
2764 // Export identifiers as requested.
2769 // For now we always stream to a section. Later we may want to
2770 // support streaming to a separate file.
2771 Stream_to_section stream;
2773 Export exp(&stream);
2774 exp.register_builtin_types(this);
2775 exp.export_globals(this->package_name(),
2776 this->unique_prefix(),
2777 this->package_priority(),
2778 (this->need_init_fn_ && !this->is_main_package()
2779 ? this->get_init_fn_name()
2781 this->imported_init_fns_,
2782 this->package_->bindings());
2785 // Find the blocks in order to convert named types defined in blocks.
2787 class Convert_named_types : public Traverse
2790 Convert_named_types(Gogo* gogo)
2791 : Traverse(traverse_blocks),
2797 block(Block* block);
2804 Convert_named_types::block(Block* block)
2806 this->gogo_->convert_named_types_in_bindings(block->bindings());
2807 return TRAVERSE_CONTINUE;
2810 // Convert all named types to the backend representation. Since named
2811 // types can refer to other types, this needs to be done in the right
2812 // sequence, which is handled by Named_type::convert. Here we arrange
2813 // to call that for each named type.
2816 Gogo::convert_named_types()
2818 this->convert_named_types_in_bindings(this->globals_);
2819 for (Packages::iterator p = this->packages_.begin();
2820 p != this->packages_.end();
2823 Package* package = p->second;
2824 this->convert_named_types_in_bindings(package->bindings());
2827 Convert_named_types cnt(this);
2828 this->traverse(&cnt);
2830 // Make all the builtin named types used for type descriptors, and
2831 // then convert them. They will only be written out if they are
2833 Type::make_type_descriptor_type();
2834 Type::make_type_descriptor_ptr_type();
2835 Function_type::make_function_type_descriptor_type();
2836 Pointer_type::make_pointer_type_descriptor_type();
2837 Struct_type::make_struct_type_descriptor_type();
2838 Array_type::make_array_type_descriptor_type();
2839 Array_type::make_slice_type_descriptor_type();
2840 Map_type::make_map_type_descriptor_type();
2841 Map_type::make_map_descriptor_type();
2842 Channel_type::make_chan_type_descriptor_type();
2843 Interface_type::make_interface_type_descriptor_type();
2844 Type::convert_builtin_named_types(this);
2846 Runtime::convert_types(this);
2848 Function_type::convert_types(this);
2850 this->named_types_are_converted_ = true;
2853 // Convert all names types in a set of bindings.
2856 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2858 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2859 p != bindings->end_definitions();
2862 if ((*p)->is_type())
2863 (*p)->type_value()->convert(this);
2869 Function::Function(Function_type* type, Function* enclosing, Block* block,
2871 : type_(type), enclosing_(enclosing), results_(NULL),
2872 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2873 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2874 is_recover_thunk_(false), has_recover_thunk_(false)
2878 // Create the named result variables.
2881 Function::create_result_variables(Gogo* gogo)
2883 const Typed_identifier_list* results = this->type_->results();
2884 if (results == NULL || results->empty())
2887 if (!results->front().name().empty())
2888 this->results_are_named_ = true;
2890 this->results_ = new Results();
2891 this->results_->reserve(results->size());
2893 Block* block = this->block_;
2895 for (Typed_identifier_list::const_iterator p = results->begin();
2896 p != results->end();
2899 std::string name = p->name();
2900 if (name.empty() || Gogo::is_sink_name(name))
2902 static int result_counter;
2904 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2906 name = gogo->pack_hidden_name(buf, false);
2908 Result_variable* result = new Result_variable(p->type(), this, index,
2910 Named_object* no = block->bindings()->add_result_variable(name, result);
2911 if (no->is_result_variable())
2912 this->results_->push_back(no);
2915 static int dummy_result_count;
2917 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2918 ++dummy_result_count;
2919 name = gogo->pack_hidden_name(buf, false);
2920 no = block->bindings()->add_result_variable(name, result);
2921 go_assert(no->is_result_variable());
2922 this->results_->push_back(no);
2927 // Update the named result variables when cloning a function which
2931 Function::update_result_variables()
2933 if (this->results_ == NULL)
2936 for (Results::iterator p = this->results_->begin();
2937 p != this->results_->end();
2939 (*p)->result_var_value()->set_function(this);
2942 // Return the closure variable, creating it if necessary.
2945 Function::closure_var()
2947 if (this->closure_var_ == NULL)
2949 // We don't know the type of the variable yet. We add fields as
2951 Location loc = this->type_->location();
2952 Struct_field_list* sfl = new Struct_field_list;
2953 Type* struct_type = Type::make_struct_type(sfl, loc);
2954 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2955 NULL, false, true, false, loc);
2956 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2957 // Note that the new variable is not in any binding contour.
2959 return this->closure_var_;
2962 // Set the type of the closure variable.
2965 Function::set_closure_type()
2967 if (this->closure_var_ == NULL)
2969 Named_object* closure = this->closure_var_;
2970 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2971 unsigned int index = 0;
2972 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2973 p != this->closure_fields_.end();
2976 Named_object* no = p->first;
2978 snprintf(buf, sizeof buf, "%u", index);
2979 std::string n = no->name() + buf;
2981 if (no->is_variable())
2982 var_type = no->var_value()->type();
2984 var_type = no->result_var_value()->type();
2985 Type* field_type = Type::make_pointer_type(var_type);
2986 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2990 // Return whether this function is a method.
2993 Function::is_method() const
2995 return this->type_->is_method();
2998 // Add a label definition.
3001 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3004 Label* lnull = NULL;
3005 std::pair<Labels::iterator, bool> ins =
3006 this->labels_.insert(std::make_pair(label_name, lnull));
3010 // This is a new label.
3011 label = new Label(label_name);
3012 ins.first->second = label;
3016 // The label was already in the hash table.
3017 label = ins.first->second;
3018 if (label->is_defined())
3020 error_at(location, "label %qs already defined",
3021 Gogo::message_name(label_name).c_str());
3022 inform(label->location(), "previous definition of %qs was here",
3023 Gogo::message_name(label_name).c_str());
3024 return new Label(label_name);
3028 label->define(location, gogo->bindings_snapshot(location));
3030 // Issue any errors appropriate for any previous goto's to this
3032 const std::vector<Bindings_snapshot*>& refs(label->refs());
3033 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3036 (*p)->check_goto_to(gogo->current_block());
3037 label->clear_refs();
3042 // Add a reference to a label.
3045 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3046 Location location, bool issue_goto_errors)
3048 Label* lnull = NULL;
3049 std::pair<Labels::iterator, bool> ins =
3050 this->labels_.insert(std::make_pair(label_name, lnull));
3054 // The label was already in the hash table.
3055 label = ins.first->second;
3059 go_assert(ins.first->second == NULL);
3060 label = new Label(label_name);
3061 ins.first->second = label;
3064 label->set_is_used();
3066 if (issue_goto_errors)
3068 Bindings_snapshot* snapshot = label->snapshot();
3069 if (snapshot != NULL)
3070 snapshot->check_goto_from(gogo->current_block(), location);
3072 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3078 // Warn about labels that are defined but not used.
3081 Function::check_labels() const
3083 for (Labels::const_iterator p = this->labels_.begin();
3084 p != this->labels_.end();
3087 Label* label = p->second;
3088 if (!label->is_used())
3089 error_at(label->location(), "label %qs defined and not used",
3090 Gogo::message_name(label->name()).c_str());
3094 // Swap one function with another. This is used when building the
3095 // thunk we use to call a function which calls recover. It may not
3096 // work for any other case.
3099 Function::swap_for_recover(Function *x)
3101 go_assert(this->enclosing_ == x->enclosing_);
3102 std::swap(this->results_, x->results_);
3103 std::swap(this->closure_var_, x->closure_var_);
3104 std::swap(this->block_, x->block_);
3105 go_assert(this->location_ == x->location_);
3106 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3107 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3110 // Traverse the tree.
3113 Function::traverse(Traverse* traverse)
3115 unsigned int traverse_mask = traverse->traverse_mask();
3118 & (Traverse::traverse_types | Traverse::traverse_expressions))
3121 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3122 return TRAVERSE_EXIT;
3125 // FIXME: We should check traverse_functions here if nested
3126 // functions are stored in block bindings.
3127 if (this->block_ != NULL
3129 & (Traverse::traverse_variables
3130 | Traverse::traverse_constants
3131 | Traverse::traverse_blocks
3132 | Traverse::traverse_statements
3133 | Traverse::traverse_expressions
3134 | Traverse::traverse_types)) != 0)
3136 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3137 return TRAVERSE_EXIT;
3140 return TRAVERSE_CONTINUE;
3143 // Work out types for unspecified variables and constants.
3146 Function::determine_types()
3148 if (this->block_ != NULL)
3149 this->block_->determine_types();
3152 // Get a pointer to the variable representing the defer stack for this
3153 // function, making it if necessary. The value of the variable is set
3154 // by the runtime routines to true if the function is returning,
3155 // rather than panicing through. A pointer to this variable is used
3156 // as a marker for the functions on the defer stack associated with
3157 // this function. A function-specific variable permits inlining a
3158 // function which uses defer.
3161 Function::defer_stack(Location location)
3163 if (this->defer_stack_ == NULL)
3165 Type* t = Type::lookup_bool_type();
3166 Expression* n = Expression::make_boolean(false, location);
3167 this->defer_stack_ = Statement::make_temporary(t, n, location);
3168 this->defer_stack_->set_is_address_taken();
3170 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3172 return Expression::make_unary(OPERATOR_AND, ref, location);
3175 // Export the function.
3178 Function::export_func(Export* exp, const std::string& name) const
3180 Function::export_func_with_type(exp, name, this->type_);
3183 // Export a function with a type.
3186 Function::export_func_with_type(Export* exp, const std::string& name,
3187 const Function_type* fntype)
3189 exp->write_c_string("func ");
3191 if (fntype->is_method())
3193 exp->write_c_string("(");
3194 exp->write_type(fntype->receiver()->type());
3195 exp->write_c_string(") ");
3198 exp->write_string(name);
3200 exp->write_c_string(" (");
3201 const Typed_identifier_list* parameters = fntype->parameters();
3202 if (parameters != NULL)
3204 bool is_varargs = fntype->is_varargs();
3206 for (Typed_identifier_list::const_iterator p = parameters->begin();
3207 p != parameters->end();
3213 exp->write_c_string(", ");
3214 if (!is_varargs || p + 1 != parameters->end())
3215 exp->write_type(p->type());
3218 exp->write_c_string("...");
3219 exp->write_type(p->type()->array_type()->element_type());
3223 exp->write_c_string(")");
3225 const Typed_identifier_list* results = fntype->results();
3226 if (results != NULL)
3228 if (results->size() == 1)
3230 exp->write_c_string(" ");
3231 exp->write_type(results->begin()->type());
3235 exp->write_c_string(" (");
3237 for (Typed_identifier_list::const_iterator p = results->begin();
3238 p != results->end();
3244 exp->write_c_string(", ");
3245 exp->write_type(p->type());
3247 exp->write_c_string(")");
3250 exp->write_c_string(";\n");
3253 // Import a function.
3256 Function::import_func(Import* imp, std::string* pname,
3257 Typed_identifier** preceiver,
3258 Typed_identifier_list** pparameters,
3259 Typed_identifier_list** presults,
3262 imp->require_c_string("func ");
3265 if (imp->peek_char() == '(')
3267 imp->require_c_string("(");
3268 Type* rtype = imp->read_type();
3269 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3271 imp->require_c_string(") ");
3274 *pname = imp->read_identifier();
3276 Typed_identifier_list* parameters;
3277 *is_varargs = false;
3278 imp->require_c_string(" (");
3279 if (imp->peek_char() == ')')
3283 parameters = new Typed_identifier_list();
3286 if (imp->match_c_string("..."))
3292 Type* ptype = imp->read_type();
3294 ptype = Type::make_array_type(ptype, NULL);
3295 parameters->push_back(Typed_identifier(Import::import_marker,
3296 ptype, imp->location()));
3297 if (imp->peek_char() != ',')
3299 go_assert(!*is_varargs);
3300 imp->require_c_string(", ");
3303 imp->require_c_string(")");
3304 *pparameters = parameters;
3306 Typed_identifier_list* results;
3307 if (imp->peek_char() != ' ')
3311 results = new Typed_identifier_list();
3312 imp->require_c_string(" ");
3313 if (imp->peek_char() != '(')
3315 Type* rtype = imp->read_type();
3316 results->push_back(Typed_identifier(Import::import_marker, rtype,
3321 imp->require_c_string("(");
3324 Type* rtype = imp->read_type();
3325 results->push_back(Typed_identifier(Import::import_marker,
3326 rtype, imp->location()));
3327 if (imp->peek_char() != ',')
3329 imp->require_c_string(", ");
3331 imp->require_c_string(")");
3334 imp->require_c_string(";\n");
3335 *presults = results;
3340 Block::Block(Block* enclosing, Location location)
3341 : enclosing_(enclosing), statements_(),
3342 bindings_(new Bindings(enclosing == NULL
3344 : enclosing->bindings())),
3345 start_location_(location),
3346 end_location_(UNKNOWN_LOCATION)
3350 // Add a statement to a block.
3353 Block::add_statement(Statement* statement)
3355 this->statements_.push_back(statement);
3358 // Add a statement to the front of a block. This is slow but is only
3359 // used for reference counts of parameters.
3362 Block::add_statement_at_front(Statement* statement)
3364 this->statements_.insert(this->statements_.begin(), statement);
3367 // Replace a statement in a block.
3370 Block::replace_statement(size_t index, Statement* s)
3372 go_assert(index < this->statements_.size());
3373 this->statements_[index] = s;
3376 // Add a statement before another statement.
3379 Block::insert_statement_before(size_t index, Statement* s)
3381 go_assert(index < this->statements_.size());
3382 this->statements_.insert(this->statements_.begin() + index, s);
3385 // Add a statement after another statement.
3388 Block::insert_statement_after(size_t index, Statement* s)
3390 go_assert(index < this->statements_.size());
3391 this->statements_.insert(this->statements_.begin() + index + 1, s);
3394 // Traverse the tree.
3397 Block::traverse(Traverse* traverse)
3399 unsigned int traverse_mask = traverse->traverse_mask();
3401 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3403 int t = traverse->block(this);
3404 if (t == TRAVERSE_EXIT)
3405 return TRAVERSE_EXIT;
3406 else if (t == TRAVERSE_SKIP_COMPONENTS)
3407 return TRAVERSE_CONTINUE;
3411 & (Traverse::traverse_variables
3412 | Traverse::traverse_constants
3413 | Traverse::traverse_expressions
3414 | Traverse::traverse_types)) != 0)
3416 const unsigned int e_or_t = (Traverse::traverse_expressions
3417 | Traverse::traverse_types);
3418 const unsigned int e_or_t_or_s = (e_or_t
3419 | Traverse::traverse_statements);
3420 for (Bindings::const_definitions_iterator pb =
3421 this->bindings_->begin_definitions();
3422 pb != this->bindings_->end_definitions();
3425 int t = TRAVERSE_CONTINUE;
3426 switch ((*pb)->classification())
3428 case Named_object::NAMED_OBJECT_CONST:
3429 if ((traverse_mask & Traverse::traverse_constants) != 0)
3430 t = traverse->constant(*pb, false);
3431 if (t == TRAVERSE_CONTINUE
3432 && (traverse_mask & e_or_t) != 0)
3434 Type* tc = (*pb)->const_value()->type();
3436 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3437 return TRAVERSE_EXIT;
3438 t = (*pb)->const_value()->traverse_expression(traverse);
3442 case Named_object::NAMED_OBJECT_VAR:
3443 case Named_object::NAMED_OBJECT_RESULT_VAR:
3444 if ((traverse_mask & Traverse::traverse_variables) != 0)
3445 t = traverse->variable(*pb);
3446 if (t == TRAVERSE_CONTINUE
3447 && (traverse_mask & e_or_t) != 0)
3449 if ((*pb)->is_result_variable()
3450 || (*pb)->var_value()->has_type())
3452 Type* tv = ((*pb)->is_variable()
3453 ? (*pb)->var_value()->type()
3454 : (*pb)->result_var_value()->type());
3456 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3457 return TRAVERSE_EXIT;
3460 if (t == TRAVERSE_CONTINUE
3461 && (traverse_mask & e_or_t_or_s) != 0
3462 && (*pb)->is_variable())
3463 t = (*pb)->var_value()->traverse_expression(traverse,
3467 case Named_object::NAMED_OBJECT_FUNC:
3468 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3471 case Named_object::NAMED_OBJECT_TYPE:
3472 if ((traverse_mask & e_or_t) != 0)
3473 t = Type::traverse((*pb)->type_value(), traverse);
3476 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3477 case Named_object::NAMED_OBJECT_UNKNOWN:
3480 case Named_object::NAMED_OBJECT_PACKAGE:
3481 case Named_object::NAMED_OBJECT_SINK:
3488 if (t == TRAVERSE_EXIT)
3489 return TRAVERSE_EXIT;
3493 // No point in checking traverse_mask here--if we got here we always
3494 // want to walk the statements. The traversal can insert new
3495 // statements before or after the current statement. Inserting
3496 // statements before the current statement requires updating I via
3497 // the pointer; those statements will not be traversed. Any new
3498 // statements inserted after the current statement will be traversed
3500 for (size_t i = 0; i < this->statements_.size(); ++i)
3502 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3503 return TRAVERSE_EXIT;
3506 return TRAVERSE_CONTINUE;
3509 // Work out types for unspecified variables and constants.
3512 Block::determine_types()
3514 for (Bindings::const_definitions_iterator pb =
3515 this->bindings_->begin_definitions();
3516 pb != this->bindings_->end_definitions();
3519 if ((*pb)->is_variable())
3520 (*pb)->var_value()->determine_type();
3521 else if ((*pb)->is_const())
3522 (*pb)->const_value()->determine_type();
3525 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3526 ps != this->statements_.end();
3528 (*ps)->determine_types();
3531 // Return true if the statements in this block may fall through.
3534 Block::may_fall_through() const
3536 if (this->statements_.empty())
3538 return this->statements_.back()->may_fall_through();
3541 // Convert a block to the backend representation.
3544 Block::get_backend(Translate_context* context)
3546 Gogo* gogo = context->gogo();
3547 Named_object* function = context->function();
3548 std::vector<Bvariable*> vars;
3549 vars.reserve(this->bindings_->size_definitions());
3550 for (Bindings::const_definitions_iterator pv =
3551 this->bindings_->begin_definitions();
3552 pv != this->bindings_->end_definitions();
3555 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3556 vars.push_back((*pv)->get_backend_variable(gogo, function));
3559 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3560 // until we have a proper representation of the init function.
3561 Bfunction* bfunction;
3562 if (function == NULL)
3565 bfunction = tree_to_function(function->func_value()->get_decl());
3566 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3567 vars, this->start_location_,
3568 this->end_location_);
3570 Translate_context subcontext(gogo, function, this, ret);
3571 std::vector<Bstatement*> bstatements;
3572 bstatements.reserve(this->statements_.size());
3573 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3574 p != this->statements_.end();
3576 bstatements.push_back((*p)->get_backend(&subcontext));
3578 context->backend()->block_add_statements(ret, bstatements);
3583 // Class Bindings_snapshot.
3585 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
3586 : block_(b), counts_(), location_(location)
3590 this->counts_.push_back(b->bindings()->size_definitions());
3595 // Report errors appropriate for a goto from B to this.
3598 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
3601 if (!this->check_goto_block(loc, b, this->block_, &dummy))
3603 this->check_goto_defs(loc, this->block_,
3604 this->block_->bindings()->size_definitions(),
3608 // Report errors appropriate for a goto from this to B.
3611 Bindings_snapshot::check_goto_to(const Block* b)
3614 if (!this->check_goto_block(this->location_, this->block_, b, &index))
3616 this->check_goto_defs(this->location_, b, this->counts_[index],
3617 b->bindings()->size_definitions());
3620 // Report errors appropriate for a goto at LOC from BFROM to BTO.
3621 // Return true if all is well, false if we reported an error. If this
3622 // returns true, it sets *PINDEX to the number of blocks BTO is above
3626 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
3627 const Block* bto, size_t* pindex)
3629 // It is an error if BTO is not either BFROM or above BFROM.
3631 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
3635 error_at(loc, "goto jumps into block");
3636 inform(bto->start_location(), "goto target block starts here");
3644 // Report errors appropriate for a goto at LOC ending at BLOCK, where
3645 // CFROM is the number of names defined at the point of the goto and
3646 // CTO is the number of names defined at the point of the label.
3649 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
3650 size_t cfrom, size_t cto)
3654 Bindings::const_definitions_iterator p =
3655 block->bindings()->begin_definitions();
3656 for (size_t i = 0; i < cfrom; ++i)
3658 go_assert(p != block->bindings()->end_definitions());
3661 go_assert(p != block->bindings()->end_definitions());
3663 std::string n = (*p)->message_name();
3664 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
3665 inform((*p)->location(), "%qs defined here", n.c_str());
3671 Variable::Variable(Type* type, Expression* init, bool is_global,
3672 bool is_parameter, bool is_receiver,
3674 : type_(type), init_(init), preinit_(NULL), location_(location),
3675 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3676 is_receiver_(is_receiver), is_varargs_parameter_(false),
3677 is_address_taken_(false), is_non_escaping_address_taken_(false),
3678 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3679 type_from_range_index_(false), type_from_range_value_(false),
3680 type_from_chan_element_(false), is_type_switch_var_(false),
3681 determined_type_(false)
3683 go_assert(type != NULL || init != NULL);
3684 go_assert(!is_parameter || init == NULL);
3687 // Traverse the initializer expression.
3690 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
3692 if (this->preinit_ != NULL)
3694 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3695 return TRAVERSE_EXIT;
3697 if (this->init_ != NULL
3699 & (Traverse::traverse_expressions | Traverse::traverse_types))
3702 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3703 return TRAVERSE_EXIT;
3705 return TRAVERSE_CONTINUE;
3708 // Lower the initialization expression after parsing is complete.
3711 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
3712 Statement_inserter* inserter)
3714 if (this->init_ != NULL && !this->init_is_lowered_)
3718 // We will give an error elsewhere, this is just to prevent
3719 // an infinite loop.
3724 Statement_inserter global_inserter;
3725 if (this->is_global_)
3727 global_inserter = Statement_inserter(gogo, this);
3728 inserter = &global_inserter;
3731 gogo->lower_expression(function, inserter, &this->init_);
3733 this->seen_ = false;
3735 this->init_is_lowered_ = true;
3739 // Get the preinit block.
3742 Variable::preinit_block(Gogo* gogo)
3744 go_assert(this->is_global_);
3745 if (this->preinit_ == NULL)
3746 this->preinit_ = new Block(NULL, this->location());
3748 // If a global variable has a preinitialization statement, then we
3749 // need to have an initialization function.
3750 gogo->set_need_init_fn();
3752 return this->preinit_;
3755 // Add a statement to be run before the initialization expression.
3758 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3760 Block* b = this->preinit_block(gogo);
3761 b->add_statement(s);
3762 b->set_end_location(s->location());
3765 // In an assignment which sets a variable to a tuple of EXPR, return
3766 // the type of the first element of the tuple.
3769 Variable::type_from_tuple(Expression* expr, bool report_error) const
3771 if (expr->map_index_expression() != NULL)
3773 Map_type* mt = expr->map_index_expression()->get_map_type();
3775 return Type::make_error_type();
3776 return mt->val_type();
3778 else if (expr->receive_expression() != NULL)
3780 Expression* channel = expr->receive_expression()->channel();
3781 Type* channel_type = channel->type();
3782 if (channel_type->channel_type() == NULL)
3783 return Type::make_error_type();
3784 return channel_type->channel_type()->element_type();
3789 error_at(this->location(), "invalid tuple definition");
3790 return Type::make_error_type();
3794 // Given EXPR used in a range clause, return either the index type or
3795 // the value type of the range, depending upon GET_INDEX_TYPE.
3798 Variable::type_from_range(Expression* expr, bool get_index_type,
3799 bool report_error) const
3801 Type* t = expr->type();
3802 if (t->array_type() != NULL
3803 || (t->points_to() != NULL
3804 && t->points_to()->array_type() != NULL
3805 && !t->points_to()->is_slice_type()))
3808 return Type::lookup_integer_type("int");
3810 return t->deref()->array_type()->element_type();
3812 else if (t->is_string_type())
3813 return Type::lookup_integer_type("int");
3814 else if (t->map_type() != NULL)
3817 return t->map_type()->key_type();
3819 return t->map_type()->val_type();
3821 else if (t->channel_type() != NULL)
3824 return t->channel_type()->element_type();
3828 error_at(this->location(),
3829 "invalid definition of value variable for channel range");
3830 return Type::make_error_type();
3836 error_at(this->location(), "invalid type for range clause");
3837 return Type::make_error_type();
3841 // EXPR should be a channel. Return the channel's element type.
3844 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3846 Type* t = expr->type();
3847 if (t->channel_type() != NULL)
3848 return t->channel_type()->element_type();
3852 error_at(this->location(), "expected channel");
3853 return Type::make_error_type();
3857 // Return the type of the Variable. This may be called before
3858 // Variable::determine_type is called, which means that we may need to
3859 // get the type from the initializer. FIXME: If we combine lowering
3860 // with type determination, then this should be unnecessary.
3865 // A variable in a type switch with a nil case will have the wrong
3866 // type here. This gets fixed up in determine_type, below.
3867 Type* type = this->type_;
3868 Expression* init = this->init_;
3869 if (this->is_type_switch_var_
3870 && this->type_->is_nil_constant_as_type())
3872 Type_guard_expression* tge = this->init_->type_guard_expression();
3873 go_assert(tge != NULL);
3880 if (this->type_ == NULL || !this->type_->is_error_type())
3882 error_at(this->location_, "variable initializer refers to itself");
3883 this->type_ = Type::make_error_type();
3892 else if (this->type_from_init_tuple_)
3893 type = this->type_from_tuple(init, false);
3894 else if (this->type_from_range_index_ || this->type_from_range_value_)
3895 type = this->type_from_range(init, this->type_from_range_index_, false);
3896 else if (this->type_from_chan_element_)
3897 type = this->type_from_chan_element(init, false);
3900 go_assert(init != NULL);
3901 type = init->type();
3902 go_assert(type != NULL);
3904 // Variables should not have abstract types.
3905 if (type->is_abstract())
3906 type = type->make_non_abstract_type();
3908 if (type->is_void_type())
3909 type = Type::make_error_type();
3912 this->seen_ = false;
3917 // Fetch the type from a const pointer, in which case it should have
3918 // been set already.
3921 Variable::type() const
3923 go_assert(this->type_ != NULL);
3927 // Set the type if necessary.
3930 Variable::determine_type()
3932 if (this->determined_type_)
3934 this->determined_type_ = true;
3936 if (this->preinit_ != NULL)
3937 this->preinit_->determine_types();
3939 // A variable in a type switch with a nil case will have the wrong
3940 // type here. It will have an initializer which is a type guard.
3941 // We want to initialize it to the value without the type guard, and
3942 // use the type of that value as well.
3943 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3945 Type_guard_expression* tge = this->init_->type_guard_expression();
3946 go_assert(tge != NULL);
3948 this->init_ = tge->expr();
3951 if (this->init_ == NULL)
3952 go_assert(this->type_ != NULL && !this->type_->is_abstract());
3953 else if (this->type_from_init_tuple_)
3955 Expression *init = this->init_;
3956 init->determine_type_no_context();
3957 this->type_ = this->type_from_tuple(init, true);
3960 else if (this->type_from_range_index_ || this->type_from_range_value_)
3962 Expression* init = this->init_;
3963 init->determine_type_no_context();
3964 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3968 else if (this->type_from_chan_element_)
3970 Expression* init = this->init_;
3971 init->determine_type_no_context();
3972 this->type_ = this->type_from_chan_element(init, true);
3977 Type_context context(this->type_, false);
3978 this->init_->determine_type(&context);
3979 if (this->type_ == NULL)
3981 Type* type = this->init_->type();
3982 go_assert(type != NULL);
3983 if (type->is_abstract())
3984 type = type->make_non_abstract_type();
3986 if (type->is_void_type())
3988 error_at(this->location_, "variable has no type");
3989 type = Type::make_error_type();
3991 else if (type->is_nil_type())
3993 error_at(this->location_, "variable defined to nil type");
3994 type = Type::make_error_type();
3996 else if (type->is_call_multiple_result_type())
3998 error_at(this->location_,
3999 "single variable set to multiple value function call");
4000 type = Type::make_error_type();
4008 // Export the variable
4011 Variable::export_var(Export* exp, const std::string& name) const
4013 go_assert(this->is_global_);
4014 exp->write_c_string("var ");
4015 exp->write_string(name);
4016 exp->write_c_string(" ");
4017 exp->write_type(this->type());
4018 exp->write_c_string(";\n");
4021 // Import a variable.
4024 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4026 imp->require_c_string("var ");
4027 *pname = imp->read_identifier();
4028 imp->require_c_string(" ");
4029 *ptype = imp->read_type();
4030 imp->require_c_string(";\n");
4033 // Convert a variable to the backend representation.
4036 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4037 const Package* package, const std::string& name)
4039 if (this->backend_ == NULL)
4041 Backend* backend = gogo->backend();
4042 Type* type = this->type_;
4043 if (type->is_error_type()
4044 || (type->is_undefined()
4045 && (!this->is_global_ || package == NULL)))
4046 this->backend_ = backend->error_variable();
4049 bool is_parameter = this->is_parameter_;
4050 if (this->is_receiver_ && type->points_to() == NULL)
4051 is_parameter = false;
4052 if (this->is_in_heap())
4054 is_parameter = false;
4055 type = Type::make_pointer_type(type);
4058 std::string n = Gogo::unpack_hidden_name(name);
4059 Btype* btype = type->get_backend(gogo);
4062 if (this->is_global_)
4063 bvar = backend->global_variable((package == NULL
4064 ? gogo->package_name()
4067 ? gogo->unique_prefix()
4068 : package->unique_prefix()),
4072 Gogo::is_hidden_name(name),
4076 tree fndecl = function->func_value()->get_decl();
4077 Bfunction* bfunction = tree_to_function(fndecl);
4078 bool is_address_taken = (this->is_non_escaping_address_taken_
4079 && !this->is_in_heap());
4081 bvar = backend->parameter_variable(bfunction, n, btype,
4085 bvar = backend->local_variable(bfunction, n, btype,
4089 this->backend_ = bvar;
4092 return this->backend_;
4095 // Class Result_variable.
4097 // Convert a result variable to the backend representation.
4100 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4101 const std::string& name)
4103 if (this->backend_ == NULL)
4105 Backend* backend = gogo->backend();
4106 Type* type = this->type_;
4107 if (type->is_error())
4108 this->backend_ = backend->error_variable();
4111 if (this->is_in_heap())
4112 type = Type::make_pointer_type(type);
4113 Btype* btype = type->get_backend(gogo);
4114 tree fndecl = function->func_value()->get_decl();
4115 Bfunction* bfunction = tree_to_function(fndecl);
4116 std::string n = Gogo::unpack_hidden_name(name);
4117 bool is_address_taken = (this->is_non_escaping_address_taken_
4118 && !this->is_in_heap());
4119 this->backend_ = backend->local_variable(bfunction, n, btype,
4124 return this->backend_;
4127 // Class Named_constant.
4129 // Traverse the initializer expression.
4132 Named_constant::traverse_expression(Traverse* traverse)
4134 return Expression::traverse(&this->expr_, traverse);
4137 // Determine the type of the constant.
4140 Named_constant::determine_type()
4142 if (this->type_ != NULL)
4144 Type_context context(this->type_, false);
4145 this->expr_->determine_type(&context);
4149 // A constant may have an abstract type.
4150 Type_context context(NULL, true);
4151 this->expr_->determine_type(&context);
4152 this->type_ = this->expr_->type();
4153 go_assert(this->type_ != NULL);
4157 // Indicate that we found and reported an error for this constant.
4160 Named_constant::set_error()
4162 this->type_ = Type::make_error_type();
4163 this->expr_ = Expression::make_error(this->location_);
4166 // Export a constant.
4169 Named_constant::export_const(Export* exp, const std::string& name) const
4171 exp->write_c_string("const ");
4172 exp->write_string(name);
4173 exp->write_c_string(" ");
4174 if (!this->type_->is_abstract())
4176 exp->write_type(this->type_);
4177 exp->write_c_string(" ");
4179 exp->write_c_string("= ");
4180 this->expr()->export_expression(exp);
4181 exp->write_c_string(";\n");
4184 // Import a constant.
4187 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4190 imp->require_c_string("const ");
4191 *pname = imp->read_identifier();
4192 imp->require_c_string(" ");
4193 if (imp->peek_char() == '=')
4197 *ptype = imp->read_type();
4198 imp->require_c_string(" ");
4200 imp->require_c_string("= ");
4201 *pexpr = Expression::import_expression(imp);
4202 imp->require_c_string(";\n");
4208 Type_declaration::add_method(const std::string& name, Function* function)
4210 Named_object* ret = Named_object::make_function(name, NULL, function);
4211 this->methods_.push_back(ret);
4215 // Add a method declaration.
4218 Type_declaration::add_method_declaration(const std::string& name,
4219 Function_type* type,
4222 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
4224 this->methods_.push_back(ret);
4228 // Return whether any methods ere defined.
4231 Type_declaration::has_methods() const
4233 return !this->methods_.empty();
4236 // Define methods for the real type.
4239 Type_declaration::define_methods(Named_type* nt)
4241 for (Methods::const_iterator p = this->methods_.begin();
4242 p != this->methods_.end();
4244 nt->add_existing_method(*p);
4247 // We are using the type. Return true if we should issue a warning.
4250 Type_declaration::using_type()
4252 bool ret = !this->issued_warning_;
4253 this->issued_warning_ = true;
4257 // Class Unknown_name.
4259 // Set the real named object.
4262 Unknown_name::set_real_named_object(Named_object* no)
4264 go_assert(this->real_named_object_ == NULL);
4265 go_assert(!no->is_unknown());
4266 this->real_named_object_ = no;
4269 // Class Named_object.
4271 Named_object::Named_object(const std::string& name,
4272 const Package* package,
4273 Classification classification)
4274 : name_(name), package_(package), classification_(classification),
4277 if (Gogo::is_sink_name(name))
4278 go_assert(classification == NAMED_OBJECT_SINK);
4281 // Make an unknown name. This is used by the parser. The name must
4282 // be resolved later. Unknown names are only added in the current
4286 Named_object::make_unknown_name(const std::string& name,
4289 Named_object* named_object = new Named_object(name, NULL,
4290 NAMED_OBJECT_UNKNOWN);
4291 Unknown_name* value = new Unknown_name(location);
4292 named_object->u_.unknown_value = value;
4293 return named_object;
4299 Named_object::make_constant(const Typed_identifier& tid,
4300 const Package* package, Expression* expr,
4303 Named_object* named_object = new Named_object(tid.name(), package,
4304 NAMED_OBJECT_CONST);
4305 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4308 named_object->u_.const_value = named_constant;
4309 return named_object;
4312 // Make a named type.
4315 Named_object::make_type(const std::string& name, const Package* package,
4316 Type* type, Location location)
4318 Named_object* named_object = new Named_object(name, package,
4320 Named_type* named_type = Type::make_named_type(named_object, type, location);
4321 named_object->u_.type_value = named_type;
4322 return named_object;
4325 // Make a type declaration.
4328 Named_object::make_type_declaration(const std::string& name,
4329 const Package* package,
4332 Named_object* named_object = new Named_object(name, package,
4333 NAMED_OBJECT_TYPE_DECLARATION);
4334 Type_declaration* type_declaration = new Type_declaration(location);
4335 named_object->u_.type_declaration = type_declaration;
4336 return named_object;
4342 Named_object::make_variable(const std::string& name, const Package* package,
4345 Named_object* named_object = new Named_object(name, package,
4347 named_object->u_.var_value = variable;
4348 return named_object;
4351 // Make a result variable.
4354 Named_object::make_result_variable(const std::string& name,
4355 Result_variable* result)
4357 Named_object* named_object = new Named_object(name, NULL,
4358 NAMED_OBJECT_RESULT_VAR);
4359 named_object->u_.result_var_value = result;
4360 return named_object;
4363 // Make a sink. This is used for the special blank identifier _.
4366 Named_object::make_sink()
4368 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4371 // Make a named function.
4374 Named_object::make_function(const std::string& name, const Package* package,
4377 Named_object* named_object = new Named_object(name, package,
4379 named_object->u_.func_value = function;
4380 return named_object;
4383 // Make a function declaration.
4386 Named_object::make_function_declaration(const std::string& name,
4387 const Package* package,
4388 Function_type* fntype,
4391 Named_object* named_object = new Named_object(name, package,
4392 NAMED_OBJECT_FUNC_DECLARATION);
4393 Function_declaration *func_decl = new Function_declaration(fntype, location);
4394 named_object->u_.func_declaration_value = func_decl;
4395 return named_object;
4401 Named_object::make_package(const std::string& alias, Package* package)
4403 Named_object* named_object = new Named_object(alias, NULL,
4404 NAMED_OBJECT_PACKAGE);
4405 named_object->u_.package_value = package;
4406 return named_object;
4409 // Return the name to use in an error message.
4412 Named_object::message_name() const
4414 if (this->package_ == NULL)
4415 return Gogo::message_name(this->name_);
4416 std::string ret = Gogo::message_name(this->package_->name());
4418 ret += Gogo::message_name(this->name_);
4422 // Set the type when a declaration is defined.
4425 Named_object::set_type_value(Named_type* named_type)
4427 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4428 Type_declaration* td = this->u_.type_declaration;
4429 td->define_methods(named_type);
4430 Named_object* in_function = td->in_function();
4431 if (in_function != NULL)
4432 named_type->set_in_function(in_function);
4434 this->classification_ = NAMED_OBJECT_TYPE;
4435 this->u_.type_value = named_type;
4438 // Define a function which was previously declared.
4441 Named_object::set_function_value(Function* function)
4443 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4444 this->classification_ = NAMED_OBJECT_FUNC;
4445 // FIXME: We should free the old value.
4446 this->u_.func_value = function;
4449 // Declare an unknown object as a type declaration.
4452 Named_object::declare_as_type()
4454 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4455 Unknown_name* unk = this->u_.unknown_value;
4456 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4457 this->u_.type_declaration = new Type_declaration(unk->location());
4461 // Return the location of a named object.
4464 Named_object::location() const
4466 switch (this->classification_)
4469 case NAMED_OBJECT_UNINITIALIZED:
4472 case NAMED_OBJECT_UNKNOWN:
4473 return this->unknown_value()->location();
4475 case NAMED_OBJECT_CONST:
4476 return this->const_value()->location();
4478 case NAMED_OBJECT_TYPE:
4479 return this->type_value()->location();
4481 case NAMED_OBJECT_TYPE_DECLARATION:
4482 return this->type_declaration_value()->location();
4484 case NAMED_OBJECT_VAR:
4485 return this->var_value()->location();
4487 case NAMED_OBJECT_RESULT_VAR:
4488 return this->result_var_value()->location();
4490 case NAMED_OBJECT_SINK:
4493 case NAMED_OBJECT_FUNC:
4494 return this->func_value()->location();
4496 case NAMED_OBJECT_FUNC_DECLARATION:
4497 return this->func_declaration_value()->location();
4499 case NAMED_OBJECT_PACKAGE:
4500 return this->package_value()->location();
4504 // Export a named object.
4507 Named_object::export_named_object(Export* exp) const
4509 switch (this->classification_)
4512 case NAMED_OBJECT_UNINITIALIZED:
4513 case NAMED_OBJECT_UNKNOWN:
4516 case NAMED_OBJECT_CONST:
4517 this->const_value()->export_const(exp, this->name_);
4520 case NAMED_OBJECT_TYPE:
4521 this->type_value()->export_named_type(exp, this->name_);
4524 case NAMED_OBJECT_TYPE_DECLARATION:
4525 error_at(this->type_declaration_value()->location(),
4526 "attempt to export %<%s%> which was declared but not defined",
4527 this->message_name().c_str());
4530 case NAMED_OBJECT_FUNC_DECLARATION:
4531 this->func_declaration_value()->export_func(exp, this->name_);
4534 case NAMED_OBJECT_VAR:
4535 this->var_value()->export_var(exp, this->name_);
4538 case NAMED_OBJECT_RESULT_VAR:
4539 case NAMED_OBJECT_SINK:
4542 case NAMED_OBJECT_FUNC:
4543 this->func_value()->export_func(exp, this->name_);
4548 // Convert a variable to the backend representation.
4551 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4553 if (this->classification_ == NAMED_OBJECT_VAR)
4554 return this->var_value()->get_backend_variable(gogo, function,
4555 this->package_, this->name_);
4556 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4557 return this->result_var_value()->get_backend_variable(gogo, function,
4565 Bindings::Bindings(Bindings* enclosing)
4566 : enclosing_(enclosing), named_objects_(), bindings_()
4573 Bindings::clear_file_scope()
4575 Contour::iterator p = this->bindings_.begin();
4576 while (p != this->bindings_.end())
4579 if (p->second->package() != NULL)
4581 else if (p->second->is_package())
4583 else if (p->second->is_function()
4584 && !p->second->func_value()->type()->is_method()
4585 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4593 p = this->bindings_.erase(p);
4597 // Look up a symbol.
4600 Bindings::lookup(const std::string& name) const
4602 Contour::const_iterator p = this->bindings_.find(name);
4603 if (p != this->bindings_.end())
4604 return p->second->resolve();
4605 else if (this->enclosing_ != NULL)
4606 return this->enclosing_->lookup(name);
4611 // Look up a symbol locally.
4614 Bindings::lookup_local(const std::string& name) const
4616 Contour::const_iterator p = this->bindings_.find(name);
4617 if (p == this->bindings_.end())
4622 // Remove an object from a set of bindings. This is used for a
4623 // special case in thunks for functions which call recover.
4626 Bindings::remove_binding(Named_object* no)
4628 Contour::iterator pb = this->bindings_.find(no->name());
4629 go_assert(pb != this->bindings_.end());
4630 this->bindings_.erase(pb);
4631 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4632 pn != this->named_objects_.end();
4637 this->named_objects_.erase(pn);
4644 // Add a method to the list of objects. This is not added to the
4645 // lookup table. This is so that we have a single list of objects
4646 // declared at the top level, which we walk through when it's time to
4647 // convert to trees.
4650 Bindings::add_method(Named_object* method)
4652 this->named_objects_.push_back(method);
4655 // Add a generic Named_object to a Contour.
4658 Bindings::add_named_object_to_contour(Contour* contour,
4659 Named_object* named_object)
4661 go_assert(named_object == named_object->resolve());
4662 const std::string& name(named_object->name());
4663 go_assert(!Gogo::is_sink_name(name));
4665 std::pair<Contour::iterator, bool> ins =
4666 contour->insert(std::make_pair(name, named_object));
4669 // The name was already there.
4670 if (named_object->package() != NULL
4671 && ins.first->second->package() == named_object->package()
4672 && (ins.first->second->classification()
4673 == named_object->classification()))
4675 // This is a second import of the same object.
4676 return ins.first->second;
4678 ins.first->second = this->new_definition(ins.first->second,
4680 return ins.first->second;
4684 // Don't push declarations on the list. We push them on when
4685 // and if we find the definitions. That way we genericize the
4686 // functions in order.
4687 if (!named_object->is_type_declaration()
4688 && !named_object->is_function_declaration()
4689 && !named_object->is_unknown())
4690 this->named_objects_.push_back(named_object);
4691 return named_object;
4695 // We had an existing named object OLD_OBJECT, and we've seen a new
4696 // one NEW_OBJECT with the same name. FIXME: This does not free the
4697 // new object when we don't need it.
4700 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4703 switch (old_object->classification())
4706 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4709 case Named_object::NAMED_OBJECT_UNKNOWN:
4711 Named_object* real = old_object->unknown_value()->real_named_object();
4713 return this->new_definition(real, new_object);
4714 go_assert(!new_object->is_unknown());
4715 old_object->unknown_value()->set_real_named_object(new_object);
4716 if (!new_object->is_type_declaration()
4717 && !new_object->is_function_declaration())
4718 this->named_objects_.push_back(new_object);
4722 case Named_object::NAMED_OBJECT_CONST:
4725 case Named_object::NAMED_OBJECT_TYPE:
4726 if (new_object->is_type_declaration())
4730 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4731 if (new_object->is_type_declaration())
4733 if (new_object->is_type())
4735 old_object->set_type_value(new_object->type_value());
4736 new_object->type_value()->set_named_object(old_object);
4737 this->named_objects_.push_back(old_object);
4742 case Named_object::NAMED_OBJECT_VAR:
4743 case Named_object::NAMED_OBJECT_RESULT_VAR:
4744 // We have already given an error in the parser for cases where
4745 // one parameter or result variable redeclares another one.
4746 if ((new_object->is_variable()
4747 && new_object->var_value()->is_parameter())
4748 || new_object->is_result_variable())
4752 case Named_object::NAMED_OBJECT_SINK:
4755 case Named_object::NAMED_OBJECT_FUNC:
4756 if (new_object->is_function_declaration())
4758 if (!new_object->func_declaration_value()->asm_name().empty())
4759 sorry("__asm__ for function definitions");
4760 Function_type* old_type = old_object->func_value()->type();
4761 Function_type* new_type =
4762 new_object->func_declaration_value()->type();
4763 if (old_type->is_valid_redeclaration(new_type, &reason))
4768 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4770 Function_type* old_type = old_object->func_declaration_value()->type();
4771 if (new_object->is_function_declaration())
4773 Function_type* new_type =
4774 new_object->func_declaration_value()->type();
4775 if (old_type->is_valid_redeclaration(new_type, &reason))
4778 if (new_object->is_function())
4780 Function_type* new_type = new_object->func_value()->type();
4781 if (old_type->is_valid_redeclaration(new_type, &reason))
4783 if (!old_object->func_declaration_value()->asm_name().empty())
4784 sorry("__asm__ for function definitions");
4785 old_object->set_function_value(new_object->func_value());
4786 this->named_objects_.push_back(old_object);
4793 case Named_object::NAMED_OBJECT_PACKAGE:
4794 if (new_object->is_package()
4795 && (old_object->package_value()->name()
4796 == new_object->package_value()->name()))
4802 std::string n = old_object->message_name();
4804 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4806 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4809 inform(old_object->location(), "previous definition of %qs was here",
4815 // Add a named type.
4818 Bindings::add_named_type(Named_type* named_type)
4820 return this->add_named_object(named_type->named_object());
4826 Bindings::add_function(const std::string& name, const Package* package,
4829 return this->add_named_object(Named_object::make_function(name, package,
4833 // Add a function declaration.
4836 Bindings::add_function_declaration(const std::string& name,
4837 const Package* package,
4838 Function_type* type,
4841 Named_object* no = Named_object::make_function_declaration(name, package,
4843 return this->add_named_object(no);
4846 // Define a type which was previously declared.
4849 Bindings::define_type(Named_object* no, Named_type* type)
4851 no->set_type_value(type);
4852 this->named_objects_.push_back(no);
4855 // Traverse bindings.
4858 Bindings::traverse(Traverse* traverse, bool is_global)
4860 unsigned int traverse_mask = traverse->traverse_mask();
4862 // We don't use an iterator because we permit the traversal to add
4863 // new global objects.
4864 const unsigned int e_or_t = (Traverse::traverse_expressions
4865 | Traverse::traverse_types);
4866 const unsigned int e_or_t_or_s = (e_or_t
4867 | Traverse::traverse_statements);
4868 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4870 Named_object* p = this->named_objects_[i];
4871 int t = TRAVERSE_CONTINUE;
4872 switch (p->classification())
4874 case Named_object::NAMED_OBJECT_CONST:
4875 if ((traverse_mask & Traverse::traverse_constants) != 0)
4876 t = traverse->constant(p, is_global);
4877 if (t == TRAVERSE_CONTINUE
4878 && (traverse_mask & e_or_t) != 0)
4880 Type* tc = p->const_value()->type();
4882 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
4883 return TRAVERSE_EXIT;
4884 t = p->const_value()->traverse_expression(traverse);
4888 case Named_object::NAMED_OBJECT_VAR:
4889 case Named_object::NAMED_OBJECT_RESULT_VAR:
4890 if ((traverse_mask & Traverse::traverse_variables) != 0)
4891 t = traverse->variable(p);
4892 if (t == TRAVERSE_CONTINUE
4893 && (traverse_mask & e_or_t) != 0)
4895 if (p->is_result_variable()
4896 || p->var_value()->has_type())
4898 Type* tv = (p->is_variable()
4899 ? p->var_value()->type()
4900 : p->result_var_value()->type());
4902 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
4903 return TRAVERSE_EXIT;
4906 if (t == TRAVERSE_CONTINUE
4907 && (traverse_mask & e_or_t_or_s) != 0
4908 && p->is_variable())
4909 t = p->var_value()->traverse_expression(traverse, traverse_mask);
4912 case Named_object::NAMED_OBJECT_FUNC:
4913 if ((traverse_mask & Traverse::traverse_functions) != 0)
4914 t = traverse->function(p);
4916 if (t == TRAVERSE_CONTINUE
4918 & (Traverse::traverse_variables
4919 | Traverse::traverse_constants
4920 | Traverse::traverse_functions
4921 | Traverse::traverse_blocks
4922 | Traverse::traverse_statements
4923 | Traverse::traverse_expressions
4924 | Traverse::traverse_types)) != 0)
4926 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4927 return TRAVERSE_EXIT;
4931 case Named_object::NAMED_OBJECT_PACKAGE:
4932 // These are traversed in Gogo::traverse.
4933 go_assert(is_global);
4936 case Named_object::NAMED_OBJECT_TYPE:
4937 if ((traverse_mask & e_or_t) != 0)
4938 t = Type::traverse(p->type_value(), traverse);
4941 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4942 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4943 case Named_object::NAMED_OBJECT_UNKNOWN:
4946 case Named_object::NAMED_OBJECT_SINK:
4951 if (t == TRAVERSE_EXIT)
4952 return TRAVERSE_EXIT;
4955 return TRAVERSE_CONTINUE;
4960 // Clear any references to this label.
4965 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
4966 p != this->refs_.end();
4969 this->refs_.clear();
4972 // Get the backend representation for a label.
4975 Label::get_backend_label(Translate_context* context)
4977 if (this->blabel_ == NULL)
4979 Function* function = context->function()->func_value();
4980 tree fndecl = function->get_decl();
4981 Bfunction* bfunction = tree_to_function(fndecl);
4982 this->blabel_ = context->backend()->label(bfunction, this->name_,
4985 return this->blabel_;
4988 // Return an expression for the address of this label.
4991 Label::get_addr(Translate_context* context, Location location)
4993 Blabel* label = this->get_backend_label(context);
4994 return context->backend()->label_address(label, location);
4997 // Class Unnamed_label.
4999 // Get the backend representation for an unnamed label.
5002 Unnamed_label::get_blabel(Translate_context* context)
5004 if (this->blabel_ == NULL)
5006 Function* function = context->function()->func_value();
5007 tree fndecl = function->get_decl();
5008 Bfunction* bfunction = tree_to_function(fndecl);
5009 this->blabel_ = context->backend()->label(bfunction, "",
5012 return this->blabel_;
5015 // Return a statement which defines this unnamed label.
5018 Unnamed_label::get_definition(Translate_context* context)
5020 Blabel* blabel = this->get_blabel(context);
5021 return context->backend()->label_definition_statement(blabel);
5024 // Return a goto statement to this unnamed label.
5027 Unnamed_label::get_goto(Translate_context* context, Location location)
5029 Blabel* blabel = this->get_blabel(context);
5030 return context->backend()->goto_statement(blabel, location);
5035 Package::Package(const std::string& name, const std::string& unique_prefix,
5037 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
5038 priority_(0), location_(location), used_(false), is_imported_(false),
5039 uses_sink_alias_(false)
5041 go_assert(!name.empty() && !unique_prefix.empty());
5044 // Set the priority. We may see multiple priorities for an imported
5045 // package; we want to use the largest one.
5048 Package::set_priority(int priority)
5050 if (priority > this->priority_)
5051 this->priority_ = priority;
5054 // Determine types of constants. Everything else in a package
5055 // (variables, function declarations) should already have a fixed
5056 // type. Constants may have abstract types.
5059 Package::determine_types()
5061 Bindings* bindings = this->bindings_;
5062 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5063 p != bindings->end_definitions();
5066 if ((*p)->is_const())
5067 (*p)->const_value()->determine_type();
5075 Traverse::~Traverse()
5077 if (this->types_seen_ != NULL)
5078 delete this->types_seen_;
5079 if (this->expressions_seen_ != NULL)
5080 delete this->expressions_seen_;
5083 // Record that we are looking at a type, and return true if we have
5087 Traverse::remember_type(const Type* type)
5089 if (type->is_error_type())
5091 go_assert((this->traverse_mask() & traverse_types) != 0
5092 || (this->traverse_mask() & traverse_expressions) != 0);
5093 // We only have to remember named types, as they are the only ones
5094 // we can see multiple times in a traversal.
5095 if (type->classification() != Type::TYPE_NAMED)
5097 if (this->types_seen_ == NULL)
5098 this->types_seen_ = new Types_seen();
5099 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5103 // Record that we are looking at an expression, and return true if we
5104 // have already seen it.
5107 Traverse::remember_expression(const Expression* expression)
5109 go_assert((this->traverse_mask() & traverse_types) != 0
5110 || (this->traverse_mask() & traverse_expressions) != 0);
5111 if (this->expressions_seen_ == NULL)
5112 this->expressions_seen_ = new Expressions_seen();
5113 std::pair<Expressions_seen::iterator, bool> ins =
5114 this->expressions_seen_->insert(expression);
5118 // The default versions of these functions should never be called: the
5119 // traversal mask indicates which functions may be called.
5122 Traverse::variable(Named_object*)
5128 Traverse::constant(Named_object*, bool)
5134 Traverse::function(Named_object*)
5140 Traverse::block(Block*)
5146 Traverse::statement(Block*, size_t*, Statement*)
5152 Traverse::expression(Expression**)
5158 Traverse::type(Type*)
5163 // Class Statement_inserter.
5166 Statement_inserter::insert(Statement* s)
5168 if (this->block_ != NULL)
5170 go_assert(this->pindex_ != NULL);
5171 this->block_->insert_statement_before(*this->pindex_, s);
5174 else if (this->var_ != NULL)
5175 this->var_->add_preinit_statement(this->gogo_, s);