Merged revisions 196716,196830,198094,198116,198502,198877,199007,199262,199319,19946...
[official-gcc.git] / main / gcc / go / gofrontend / gogo.cc
blob9f918cb81c7bc25eed0ea34a6d52b21a70dbba59
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.
7 #include "go-system.h"
9 #include "filenames.h"
11 #include "go-c.h"
12 #include "go-dump.h"
13 #include "lex.h"
14 #include "types.h"
15 #include "statements.h"
16 #include "expressions.h"
17 #include "dataflow.h"
18 #include "runtime.h"
19 #include "import.h"
20 #include "export.h"
21 #include "backend.h"
22 #include "gogo.h"
24 // Class Gogo.
26 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
27 : backend_(backend),
28 linemap_(linemap),
29 package_(NULL),
30 functions_(),
31 globals_(new Bindings(NULL)),
32 file_block_names_(),
33 imports_(),
34 imported_unsafe_(false),
35 packages_(),
36 init_functions_(),
37 var_deps_(),
38 need_init_fn_(false),
39 init_fn_name_(),
40 imported_init_fns_(),
41 pkgpath_(),
42 pkgpath_symbol_(),
43 prefix_(),
44 pkgpath_set_(false),
45 pkgpath_from_option_(false),
46 prefix_from_option_(false),
47 relative_import_path_(),
48 verify_types_(),
49 interface_types_(),
50 specific_type_functions_(),
51 specific_type_functions_are_written_(false),
52 named_types_are_converted_(false)
54 const Location loc = Linemap::predeclared_location();
56 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
57 RUNTIME_TYPE_KIND_UINT8);
58 this->add_named_type(uint8_type);
59 this->add_named_type(Type::make_integer_type("uint16", true, 16,
60 RUNTIME_TYPE_KIND_UINT16));
61 this->add_named_type(Type::make_integer_type("uint32", true, 32,
62 RUNTIME_TYPE_KIND_UINT32));
63 this->add_named_type(Type::make_integer_type("uint64", true, 64,
64 RUNTIME_TYPE_KIND_UINT64));
66 this->add_named_type(Type::make_integer_type("int8", false, 8,
67 RUNTIME_TYPE_KIND_INT8));
68 this->add_named_type(Type::make_integer_type("int16", false, 16,
69 RUNTIME_TYPE_KIND_INT16));
70 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
71 RUNTIME_TYPE_KIND_INT32);
72 this->add_named_type(int32_type);
73 this->add_named_type(Type::make_integer_type("int64", false, 64,
74 RUNTIME_TYPE_KIND_INT64));
76 this->add_named_type(Type::make_float_type("float32", 32,
77 RUNTIME_TYPE_KIND_FLOAT32));
78 this->add_named_type(Type::make_float_type("float64", 64,
79 RUNTIME_TYPE_KIND_FLOAT64));
81 this->add_named_type(Type::make_complex_type("complex64", 64,
82 RUNTIME_TYPE_KIND_COMPLEX64));
83 this->add_named_type(Type::make_complex_type("complex128", 128,
84 RUNTIME_TYPE_KIND_COMPLEX128));
86 int int_type_size = pointer_size;
87 if (int_type_size < 32)
88 int_type_size = 32;
89 this->add_named_type(Type::make_integer_type("uint", true,
90 int_type_size,
91 RUNTIME_TYPE_KIND_UINT));
92 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
93 RUNTIME_TYPE_KIND_INT);
94 this->add_named_type(int_type);
96 this->add_named_type(Type::make_integer_type("uintptr", true,
97 pointer_size,
98 RUNTIME_TYPE_KIND_UINTPTR));
100 // "byte" is an alias for "uint8".
101 uint8_type->integer_type()->set_is_byte();
102 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
103 loc);
104 this->add_named_type(byte_type->type_value());
106 // "rune" is an alias for "int32".
107 int32_type->integer_type()->set_is_rune();
108 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
109 loc);
110 this->add_named_type(rune_type->type_value());
112 this->add_named_type(Type::make_named_bool_type());
114 this->add_named_type(Type::make_named_string_type());
116 // "error" is interface { Error() string }.
118 Typed_identifier_list *methods = new Typed_identifier_list;
119 Typed_identifier_list *results = new Typed_identifier_list;
120 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
121 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
122 methods->push_back(Typed_identifier("Error", method_type, loc));
123 Interface_type *error_iface = Type::make_interface_type(methods, loc);
124 error_iface->finalize_methods();
125 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
126 this->add_named_type(error_type);
129 this->globals_->add_constant(Typed_identifier("true",
130 Type::make_boolean_type(),
131 loc),
132 NULL,
133 Expression::make_boolean(true, loc),
135 this->globals_->add_constant(Typed_identifier("false",
136 Type::make_boolean_type(),
137 loc),
138 NULL,
139 Expression::make_boolean(false, loc),
142 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
143 loc),
144 NULL,
145 Expression::make_nil(loc),
148 Type* abstract_int_type = Type::make_abstract_integer_type();
149 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
150 loc),
151 NULL,
152 Expression::make_iota(),
155 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
156 new_type->set_is_varargs();
157 new_type->set_is_builtin();
158 this->globals_->add_function_declaration("new", NULL, new_type, loc);
160 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
161 make_type->set_is_varargs();
162 make_type->set_is_builtin();
163 this->globals_->add_function_declaration("make", NULL, make_type, loc);
165 Typed_identifier_list* len_result = new Typed_identifier_list();
166 len_result->push_back(Typed_identifier("", int_type, loc));
167 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
168 loc);
169 len_type->set_is_builtin();
170 this->globals_->add_function_declaration("len", NULL, len_type, loc);
172 Typed_identifier_list* cap_result = new Typed_identifier_list();
173 cap_result->push_back(Typed_identifier("", int_type, loc));
174 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
175 loc);
176 cap_type->set_is_builtin();
177 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
179 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
180 print_type->set_is_varargs();
181 print_type->set_is_builtin();
182 this->globals_->add_function_declaration("print", NULL, print_type, loc);
184 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
185 print_type->set_is_varargs();
186 print_type->set_is_builtin();
187 this->globals_->add_function_declaration("println", NULL, print_type, loc);
189 Type *empty = Type::make_empty_interface_type(loc);
190 Typed_identifier_list* panic_parms = new Typed_identifier_list();
191 panic_parms->push_back(Typed_identifier("e", empty, loc));
192 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
193 NULL, loc);
194 panic_type->set_is_builtin();
195 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
197 Typed_identifier_list* recover_result = new Typed_identifier_list();
198 recover_result->push_back(Typed_identifier("", empty, loc));
199 Function_type* recover_type = Type::make_function_type(NULL, NULL,
200 recover_result,
201 loc);
202 recover_type->set_is_builtin();
203 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
205 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
206 close_type->set_is_varargs();
207 close_type->set_is_builtin();
208 this->globals_->add_function_declaration("close", NULL, close_type, loc);
210 Typed_identifier_list* copy_result = new Typed_identifier_list();
211 copy_result->push_back(Typed_identifier("", int_type, loc));
212 Function_type* copy_type = Type::make_function_type(NULL, NULL,
213 copy_result, loc);
214 copy_type->set_is_varargs();
215 copy_type->set_is_builtin();
216 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
218 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
219 append_type->set_is_varargs();
220 append_type->set_is_builtin();
221 this->globals_->add_function_declaration("append", NULL, append_type, loc);
223 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
224 complex_type->set_is_varargs();
225 complex_type->set_is_builtin();
226 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
228 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
229 real_type->set_is_varargs();
230 real_type->set_is_builtin();
231 this->globals_->add_function_declaration("real", NULL, real_type, loc);
233 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
234 imag_type->set_is_varargs();
235 imag_type->set_is_builtin();
236 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
238 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
239 delete_type->set_is_varargs();
240 delete_type->set_is_builtin();
241 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
244 // Convert a pkgpath into a string suitable for a symbol. Note that
245 // this transformation is convenient but imperfect. A -fgo-pkgpath
246 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
247 // possibly leading to link time errors.
249 std::string
250 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
252 std::string s = pkgpath;
253 for (size_t i = 0; i < s.length(); ++i)
255 char c = s[i];
256 if ((c >= 'a' && c <= 'z')
257 || (c >= 'A' && c <= 'Z')
258 || (c >= '0' && c <= '9')
259 || c == '_'
260 || c == '.'
261 || c == '$')
263 else
264 s[i] = '_';
266 return s;
269 // Get the package path to use for type reflection data. This should
270 // ideally be unique across the entire link.
272 const std::string&
273 Gogo::pkgpath() const
275 go_assert(this->pkgpath_set_);
276 return this->pkgpath_;
279 // Set the package path from the -fgo-pkgpath command line option.
281 void
282 Gogo::set_pkgpath(const std::string& arg)
284 go_assert(!this->pkgpath_set_);
285 this->pkgpath_ = arg;
286 this->pkgpath_set_ = true;
287 this->pkgpath_from_option_ = true;
290 // Get the package path to use for symbol names.
292 const std::string&
293 Gogo::pkgpath_symbol() const
295 go_assert(this->pkgpath_set_);
296 return this->pkgpath_symbol_;
299 // Set the unique prefix to use to determine the package path, from
300 // the -fgo-prefix command line option.
302 void
303 Gogo::set_prefix(const std::string& arg)
305 go_assert(!this->prefix_from_option_);
306 this->prefix_ = arg;
307 this->prefix_from_option_ = true;
310 // Munge name for use in an error message.
312 std::string
313 Gogo::message_name(const std::string& name)
315 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
318 // Get the package name.
320 const std::string&
321 Gogo::package_name() const
323 go_assert(this->package_ != NULL);
324 return this->package_->package_name();
327 // Set the package name.
329 void
330 Gogo::set_package_name(const std::string& package_name,
331 Location location)
333 if (this->package_ != NULL)
335 if (this->package_->package_name() != package_name)
336 error_at(location, "expected package %<%s%>",
337 Gogo::message_name(this->package_->package_name()).c_str());
338 return;
341 // Now that we know the name of the package we are compiling, set
342 // the package path to use for reflect.Type.PkgPath and global
343 // symbol names.
344 if (!this->pkgpath_set_)
346 if (!this->prefix_from_option_ && package_name == "main")
347 this->pkgpath_ = package_name;
348 else
350 if (!this->prefix_from_option_)
351 this->prefix_ = "go";
352 this->pkgpath_ = this->prefix_ + '.' + package_name;
354 this->pkgpath_set_ = true;
357 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
359 this->package_ = this->register_package(this->pkgpath_, location);
360 this->package_->set_package_name(package_name, location);
362 if (this->is_main_package())
364 // Declare "main" as a function which takes no parameters and
365 // returns no value.
366 Location uloc = Linemap::unknown_location();
367 this->declare_function(Gogo::pack_hidden_name("main", false),
368 Type::make_function_type (NULL, NULL, NULL, uloc),
369 uloc);
373 // Return whether this is the "main" package. This is not true if
374 // -fgo-pkgpath or -fgo-prefix was used.
376 bool
377 Gogo::is_main_package() const
379 return (this->package_name() == "main"
380 && !this->pkgpath_from_option_
381 && !this->prefix_from_option_);
384 // Import a package.
386 void
387 Gogo::import_package(const std::string& filename,
388 const std::string& local_name,
389 bool is_local_name_exported,
390 Location location)
392 if (filename.empty())
394 error_at(location, "import path is empty");
395 return;
398 const char *pf = filename.data();
399 const char *pend = pf + filename.length();
400 while (pf < pend)
402 unsigned int c;
403 int adv = Lex::fetch_char(pf, &c);
404 if (adv == 0)
406 error_at(location, "import path contains invalid UTF-8 sequence");
407 return;
409 if (c == '\0')
411 error_at(location, "import path contains NUL");
412 return;
414 if (c < 0x20 || c == 0x7f)
416 error_at(location, "import path contains control character");
417 return;
419 if (c == '\\')
421 error_at(location, "import path contains backslash; use slash");
422 return;
424 if (Lex::is_unicode_space(c))
426 error_at(location, "import path contains space character");
427 return;
429 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
431 error_at(location, "import path contains invalid character '%c'", c);
432 return;
434 pf += adv;
437 if (IS_ABSOLUTE_PATH(filename.c_str()))
439 error_at(location, "import path cannot be absolute path");
440 return;
443 if (filename == "unsafe")
445 this->import_unsafe(local_name, is_local_name_exported, location);
446 return;
449 Imports::const_iterator p = this->imports_.find(filename);
450 if (p != this->imports_.end())
452 Package* package = p->second;
453 package->set_location(location);
454 package->set_is_imported();
455 std::string ln = local_name;
456 bool is_ln_exported = is_local_name_exported;
457 if (ln.empty())
459 ln = package->package_name();
460 go_assert(!ln.empty());
461 is_ln_exported = Lex::is_exported_name(ln);
463 if (ln == ".")
465 Bindings* bindings = package->bindings();
466 for (Bindings::const_declarations_iterator p =
467 bindings->begin_declarations();
468 p != bindings->end_declarations();
469 ++p)
470 this->add_named_object(p->second);
472 else if (ln == "_")
473 package->set_uses_sink_alias();
474 else
476 ln = this->pack_hidden_name(ln, is_ln_exported);
477 this->package_->bindings()->add_package(ln, package);
479 return;
482 Import::Stream* stream = Import::open_package(filename, location,
483 this->relative_import_path_);
484 if (stream == NULL)
486 error_at(location, "import file %qs not found", filename.c_str());
487 return;
490 Import imp(stream, location);
491 imp.register_builtin_types(this);
492 Package* package = imp.import(this, local_name, is_local_name_exported);
493 if (package != NULL)
495 if (package->pkgpath() == this->pkgpath())
496 error_at(location,
497 ("imported package uses same package path as package "
498 "being compiled (see -fgo-pkgpath option)"));
500 this->imports_.insert(std::make_pair(filename, package));
501 package->set_is_imported();
504 delete stream;
507 // Add an import control function for an imported package to the list.
509 void
510 Gogo::add_import_init_fn(const std::string& package_name,
511 const std::string& init_name, int prio)
513 for (std::set<Import_init>::const_iterator p =
514 this->imported_init_fns_.begin();
515 p != this->imported_init_fns_.end();
516 ++p)
518 if (p->init_name() == init_name)
520 // If a test of package P1, built as part of package P1,
521 // imports package P2, and P2 imports P1 (perhaps
522 // indirectly), then we will see the same import name with
523 // different import priorities. That is OK, so don't give
524 // an error about it.
525 if (p->package_name() != package_name)
527 error("duplicate package initialization name %qs",
528 Gogo::message_name(init_name).c_str());
529 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
530 Gogo::message_name(p->package_name()).c_str(),
531 p->priority());
532 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
533 Gogo::message_name(package_name).c_str(), prio);
535 return;
539 this->imported_init_fns_.insert(Import_init(package_name, init_name,
540 prio));
543 // Return whether we are at the global binding level.
545 bool
546 Gogo::in_global_scope() const
548 return this->functions_.empty();
551 // Return the current binding contour.
553 Bindings*
554 Gogo::current_bindings()
556 if (!this->functions_.empty())
557 return this->functions_.back().blocks.back()->bindings();
558 else if (this->package_ != NULL)
559 return this->package_->bindings();
560 else
561 return this->globals_;
564 const Bindings*
565 Gogo::current_bindings() const
567 if (!this->functions_.empty())
568 return this->functions_.back().blocks.back()->bindings();
569 else if (this->package_ != NULL)
570 return this->package_->bindings();
571 else
572 return this->globals_;
575 // Return the current block.
577 Block*
578 Gogo::current_block()
580 if (this->functions_.empty())
581 return NULL;
582 else
583 return this->functions_.back().blocks.back();
586 // Look up a name in the current binding contour. If PFUNCTION is not
587 // NULL, set it to the function in which the name is defined, or NULL
588 // if the name is defined in global scope.
590 Named_object*
591 Gogo::lookup(const std::string& name, Named_object** pfunction) const
593 if (pfunction != NULL)
594 *pfunction = NULL;
596 if (Gogo::is_sink_name(name))
597 return Named_object::make_sink();
599 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
600 p != this->functions_.rend();
601 ++p)
603 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
604 if (ret != NULL)
606 if (pfunction != NULL)
607 *pfunction = p->function;
608 return ret;
612 if (this->package_ != NULL)
614 Named_object* ret = this->package_->bindings()->lookup(name);
615 if (ret != NULL)
617 if (ret->package() != NULL)
618 ret->package()->set_used();
619 return ret;
623 // We do not look in the global namespace. If we did, the global
624 // namespace would effectively hide names which were defined in
625 // package scope which we have not yet seen. Instead,
626 // define_global_names is called after parsing is over to connect
627 // undefined names at package scope with names defined at global
628 // scope.
630 return NULL;
633 // Look up a name in the current block, without searching enclosing
634 // blocks.
636 Named_object*
637 Gogo::lookup_in_block(const std::string& name) const
639 go_assert(!this->functions_.empty());
640 go_assert(!this->functions_.back().blocks.empty());
641 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
644 // Look up a name in the global namespace.
646 Named_object*
647 Gogo::lookup_global(const char* name) const
649 return this->globals_->lookup(name);
652 // Add an imported package.
654 Package*
655 Gogo::add_imported_package(const std::string& real_name,
656 const std::string& alias_arg,
657 bool is_alias_exported,
658 const std::string& pkgpath,
659 Location location,
660 bool* padd_to_globals)
662 Package* ret = this->register_package(pkgpath, location);
663 ret->set_package_name(real_name, location);
665 *padd_to_globals = false;
667 if (alias_arg == ".")
668 *padd_to_globals = true;
669 else if (alias_arg == "_")
670 ret->set_uses_sink_alias();
671 else
673 std::string alias = alias_arg;
674 if (alias.empty())
676 alias = real_name;
677 is_alias_exported = Lex::is_exported_name(alias);
679 alias = this->pack_hidden_name(alias, is_alias_exported);
680 Named_object* no = this->package_->bindings()->add_package(alias, ret);
681 if (!no->is_package())
682 return NULL;
685 return ret;
688 // Register a package. This package may or may not be imported. This
689 // returns the Package structure for the package, creating if it
690 // necessary. LOCATION is the location of the import statement that
691 // led us to see this package.
693 Package*
694 Gogo::register_package(const std::string& pkgpath, Location location)
696 Package* package = NULL;
697 std::pair<Packages::iterator, bool> ins =
698 this->packages_.insert(std::make_pair(pkgpath, package));
699 if (!ins.second)
701 // We have seen this package name before.
702 package = ins.first->second;
703 go_assert(package != NULL && package->pkgpath() == pkgpath);
704 if (Linemap::is_unknown_location(package->location()))
705 package->set_location(location);
707 else
709 // First time we have seen this package name.
710 package = new Package(pkgpath, location);
711 go_assert(ins.first->second == NULL);
712 ins.first->second = package;
715 return package;
718 // Start compiling a function.
720 Named_object*
721 Gogo::start_function(const std::string& name, Function_type* type,
722 bool add_method_to_type, Location location)
724 bool at_top_level = this->functions_.empty();
726 Block* block = new Block(NULL, location);
728 Function* enclosing = (at_top_level
729 ? NULL
730 : this->functions_.back().function->func_value());
732 Function* function = new Function(type, enclosing, block, location);
734 if (type->is_method())
736 const Typed_identifier* receiver = type->receiver();
737 Variable* this_param = new Variable(receiver->type(), NULL, false,
738 true, true, location);
739 std::string rname = receiver->name();
740 if (rname.empty() || Gogo::is_sink_name(rname))
742 // We need to give receivers a name since they wind up in
743 // DECL_ARGUMENTS. FIXME.
744 static unsigned int count;
745 char buf[50];
746 snprintf(buf, sizeof buf, "r.%u", count);
747 ++count;
748 rname = buf;
750 block->bindings()->add_variable(rname, NULL, this_param);
753 const Typed_identifier_list* parameters = type->parameters();
754 bool is_varargs = type->is_varargs();
755 if (parameters != NULL)
757 for (Typed_identifier_list::const_iterator p = parameters->begin();
758 p != parameters->end();
759 ++p)
761 Variable* param = new Variable(p->type(), NULL, false, true, false,
762 location);
763 if (is_varargs && p + 1 == parameters->end())
764 param->set_is_varargs_parameter();
766 std::string pname = p->name();
767 if (pname.empty() || Gogo::is_sink_name(pname))
769 // We need to give parameters a name since they wind up
770 // in DECL_ARGUMENTS. FIXME.
771 static unsigned int count;
772 char buf[50];
773 snprintf(buf, sizeof buf, "p.%u", count);
774 ++count;
775 pname = buf;
777 block->bindings()->add_variable(pname, NULL, param);
781 function->create_result_variables(this);
783 const std::string* pname;
784 std::string nested_name;
785 bool is_init = false;
786 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
788 if ((type->parameters() != NULL && !type->parameters()->empty())
789 || (type->results() != NULL && !type->results()->empty()))
790 error_at(location,
791 "func init must have no arguments and no return values");
792 // There can be multiple "init" functions, so give them each a
793 // different name.
794 static int init_count;
795 char buf[30];
796 snprintf(buf, sizeof buf, ".$init%d", init_count);
797 ++init_count;
798 nested_name = buf;
799 pname = &nested_name;
800 is_init = true;
802 else if (!name.empty())
803 pname = &name;
804 else
806 // Invent a name for a nested function.
807 static int nested_count;
808 char buf[30];
809 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
810 ++nested_count;
811 nested_name = buf;
812 pname = &nested_name;
815 Named_object* ret;
816 if (Gogo::is_sink_name(*pname))
818 static int sink_count;
819 char buf[30];
820 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
821 ++sink_count;
822 ret = this->package_->bindings()->add_function(buf, NULL, function);
823 ret->func_value()->set_is_sink();
825 else if (!type->is_method())
827 ret = this->package_->bindings()->add_function(*pname, NULL, function);
828 if (!ret->is_function() || ret->func_value() != function)
830 // Redefinition error. Invent a name to avoid knockon
831 // errors.
832 static int redefinition_count;
833 char buf[30];
834 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
835 ++redefinition_count;
836 ret = this->package_->bindings()->add_function(buf, NULL, function);
839 else
841 if (!add_method_to_type)
842 ret = Named_object::make_function(name, NULL, function);
843 else
845 go_assert(at_top_level);
846 Type* rtype = type->receiver()->type();
848 // We want to look through the pointer created by the
849 // parser, without getting an error if the type is not yet
850 // defined.
851 if (rtype->classification() == Type::TYPE_POINTER)
852 rtype = rtype->points_to();
854 if (rtype->is_error_type())
855 ret = Named_object::make_function(name, NULL, function);
856 else if (rtype->named_type() != NULL)
858 ret = rtype->named_type()->add_method(name, function);
859 if (!ret->is_function())
861 // Redefinition error.
862 ret = Named_object::make_function(name, NULL, function);
865 else if (rtype->forward_declaration_type() != NULL)
867 Named_object* type_no =
868 rtype->forward_declaration_type()->named_object();
869 if (type_no->is_unknown())
871 // If we are seeing methods it really must be a
872 // type. Declare it as such. An alternative would
873 // be to support lists of methods for unknown
874 // expressions. Either way the error messages if
875 // this is not a type are going to get confusing.
876 Named_object* declared =
877 this->declare_package_type(type_no->name(),
878 type_no->location());
879 go_assert(declared
880 == type_no->unknown_value()->real_named_object());
882 ret = rtype->forward_declaration_type()->add_method(name,
883 function);
885 else
886 go_unreachable();
888 this->package_->bindings()->add_method(ret);
891 this->functions_.resize(this->functions_.size() + 1);
892 Open_function& of(this->functions_.back());
893 of.function = ret;
894 of.blocks.push_back(block);
896 if (is_init)
898 this->init_functions_.push_back(ret);
899 this->need_init_fn_ = true;
902 return ret;
905 // Finish compiling a function.
907 void
908 Gogo::finish_function(Location location)
910 this->finish_block(location);
911 go_assert(this->functions_.back().blocks.empty());
912 this->functions_.pop_back();
915 // Return the current function.
917 Named_object*
918 Gogo::current_function() const
920 go_assert(!this->functions_.empty());
921 return this->functions_.back().function;
924 // Start a new block.
926 void
927 Gogo::start_block(Location location)
929 go_assert(!this->functions_.empty());
930 Block* block = new Block(this->current_block(), location);
931 this->functions_.back().blocks.push_back(block);
934 // Finish a block.
936 Block*
937 Gogo::finish_block(Location location)
939 go_assert(!this->functions_.empty());
940 go_assert(!this->functions_.back().blocks.empty());
941 Block* block = this->functions_.back().blocks.back();
942 this->functions_.back().blocks.pop_back();
943 block->set_end_location(location);
944 return block;
947 // Add an erroneous name.
949 Named_object*
950 Gogo::add_erroneous_name(const std::string& name)
952 return this->package_->bindings()->add_erroneous_name(name);
955 // Add an unknown name.
957 Named_object*
958 Gogo::add_unknown_name(const std::string& name, Location location)
960 return this->package_->bindings()->add_unknown_name(name, location);
963 // Declare a function.
965 Named_object*
966 Gogo::declare_function(const std::string& name, Function_type* type,
967 Location location)
969 if (!type->is_method())
970 return this->current_bindings()->add_function_declaration(name, NULL, type,
971 location);
972 else
974 // We don't bother to add this to the list of global
975 // declarations.
976 Type* rtype = type->receiver()->type();
978 // We want to look through the pointer created by the
979 // parser, without getting an error if the type is not yet
980 // defined.
981 if (rtype->classification() == Type::TYPE_POINTER)
982 rtype = rtype->points_to();
984 if (rtype->is_error_type())
985 return NULL;
986 else if (rtype->named_type() != NULL)
987 return rtype->named_type()->add_method_declaration(name, NULL, type,
988 location);
989 else if (rtype->forward_declaration_type() != NULL)
991 Forward_declaration_type* ftype = rtype->forward_declaration_type();
992 return ftype->add_method_declaration(name, NULL, type, location);
994 else
995 go_unreachable();
999 // Add a label definition.
1001 Label*
1002 Gogo::add_label_definition(const std::string& label_name,
1003 Location location)
1005 go_assert(!this->functions_.empty());
1006 Function* func = this->functions_.back().function->func_value();
1007 Label* label = func->add_label_definition(this, label_name, location);
1008 this->add_statement(Statement::make_label_statement(label, location));
1009 return label;
1012 // Add a label reference.
1014 Label*
1015 Gogo::add_label_reference(const std::string& label_name,
1016 Location location, bool issue_goto_errors)
1018 go_assert(!this->functions_.empty());
1019 Function* func = this->functions_.back().function->func_value();
1020 return func->add_label_reference(this, label_name, location,
1021 issue_goto_errors);
1024 // Return the current binding state.
1026 Bindings_snapshot*
1027 Gogo::bindings_snapshot(Location location)
1029 return new Bindings_snapshot(this->current_block(), location);
1032 // Add a statement.
1034 void
1035 Gogo::add_statement(Statement* statement)
1037 go_assert(!this->functions_.empty()
1038 && !this->functions_.back().blocks.empty());
1039 this->functions_.back().blocks.back()->add_statement(statement);
1042 // Add a block.
1044 void
1045 Gogo::add_block(Block* block, Location location)
1047 go_assert(!this->functions_.empty()
1048 && !this->functions_.back().blocks.empty());
1049 Statement* statement = Statement::make_block_statement(block, location);
1050 this->functions_.back().blocks.back()->add_statement(statement);
1053 // Add a constant.
1055 Named_object*
1056 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
1057 int iota_value)
1059 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
1062 // Add a type.
1064 void
1065 Gogo::add_type(const std::string& name, Type* type, Location location)
1067 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
1068 location);
1069 if (!this->in_global_scope() && no->is_type())
1071 Named_object* f = this->functions_.back().function;
1072 unsigned int index;
1073 if (f->is_function())
1074 index = f->func_value()->new_local_type_index();
1075 else
1076 index = 0;
1077 no->type_value()->set_in_function(f, index);
1081 // Add a named type.
1083 void
1084 Gogo::add_named_type(Named_type* type)
1086 go_assert(this->in_global_scope());
1087 this->current_bindings()->add_named_type(type);
1090 // Declare a type.
1092 Named_object*
1093 Gogo::declare_type(const std::string& name, Location location)
1095 Bindings* bindings = this->current_bindings();
1096 Named_object* no = bindings->add_type_declaration(name, NULL, location);
1097 if (!this->in_global_scope() && no->is_type_declaration())
1099 Named_object* f = this->functions_.back().function;
1100 unsigned int index;
1101 if (f->is_function())
1102 index = f->func_value()->new_local_type_index();
1103 else
1104 index = 0;
1105 no->type_declaration_value()->set_in_function(f, index);
1107 return no;
1110 // Declare a type at the package level.
1112 Named_object*
1113 Gogo::declare_package_type(const std::string& name, Location location)
1115 return this->package_->bindings()->add_type_declaration(name, NULL, location);
1118 // Declare a function at the package level.
1120 Named_object*
1121 Gogo::declare_package_function(const std::string& name, Function_type* type,
1122 Location location)
1124 return this->package_->bindings()->add_function_declaration(name, NULL, type,
1125 location);
1128 // Define a type which was already declared.
1130 void
1131 Gogo::define_type(Named_object* no, Named_type* type)
1133 this->current_bindings()->define_type(no, type);
1136 // Add a variable.
1138 Named_object*
1139 Gogo::add_variable(const std::string& name, Variable* variable)
1141 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1142 variable);
1144 // In a function the middle-end wants to see a DECL_EXPR node.
1145 if (no != NULL
1146 && no->is_variable()
1147 && !no->var_value()->is_parameter()
1148 && !this->functions_.empty())
1149 this->add_statement(Statement::make_variable_declaration(no));
1151 return no;
1154 // Add a sink--a reference to the blank identifier _.
1156 Named_object*
1157 Gogo::add_sink()
1159 return Named_object::make_sink();
1162 // Add a named object.
1164 void
1165 Gogo::add_named_object(Named_object* no)
1167 this->current_bindings()->add_named_object(no);
1170 // Mark all local variables used. This is used when some types of
1171 // parse error occur.
1173 void
1174 Gogo::mark_locals_used()
1176 for (Open_functions::iterator pf = this->functions_.begin();
1177 pf != this->functions_.end();
1178 ++pf)
1180 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
1181 pb != pf->blocks.end();
1182 ++pb)
1183 (*pb)->bindings()->mark_locals_used();
1187 // Record that we've seen an interface type.
1189 void
1190 Gogo::record_interface_type(Interface_type* itype)
1192 this->interface_types_.push_back(itype);
1195 // Return an erroneous name that indicates that an error has already
1196 // been reported.
1198 std::string
1199 Gogo::erroneous_name()
1201 static int erroneous_count;
1202 char name[50];
1203 snprintf(name, sizeof name, "$erroneous%d", erroneous_count);
1204 ++erroneous_count;
1205 return name;
1208 // Return whether a name is an erroneous name.
1210 bool
1211 Gogo::is_erroneous_name(const std::string& name)
1213 return name.compare(0, 10, "$erroneous") == 0;
1216 // Return a name for a thunk object.
1218 std::string
1219 Gogo::thunk_name()
1221 static int thunk_count;
1222 char thunk_name[50];
1223 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1224 ++thunk_count;
1225 return thunk_name;
1228 // Return whether a function is a thunk.
1230 bool
1231 Gogo::is_thunk(const Named_object* no)
1233 return no->name().compare(0, 6, "$thunk") == 0;
1236 // Define the global names. We do this only after parsing all the
1237 // input files, because the program might define the global names
1238 // itself.
1240 void
1241 Gogo::define_global_names()
1243 for (Bindings::const_declarations_iterator p =
1244 this->globals_->begin_declarations();
1245 p != this->globals_->end_declarations();
1246 ++p)
1248 Named_object* global_no = p->second;
1249 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1250 Named_object* no = this->package_->bindings()->lookup(name);
1251 if (no == NULL)
1252 continue;
1253 no = no->resolve();
1254 if (no->is_type_declaration())
1256 if (global_no->is_type())
1258 if (no->type_declaration_value()->has_methods())
1259 error_at(no->location(),
1260 "may not define methods for global type");
1261 no->set_type_value(global_no->type_value());
1263 else
1265 error_at(no->location(), "expected type");
1266 Type* errtype = Type::make_error_type();
1267 Named_object* err =
1268 Named_object::make_type("erroneous_type", NULL, errtype,
1269 Linemap::predeclared_location());
1270 no->set_type_value(err->type_value());
1273 else if (no->is_unknown())
1274 no->unknown_value()->set_real_named_object(global_no);
1277 // Give an error if any name is defined in both the package block
1278 // and the file block. For example, this can happen if one file
1279 // imports "fmt" and another file defines a global variable fmt.
1280 for (Bindings::const_declarations_iterator p =
1281 this->package_->bindings()->begin_declarations();
1282 p != this->package_->bindings()->end_declarations();
1283 ++p)
1285 if (p->second->is_unknown()
1286 && p->second->unknown_value()->real_named_object() == NULL)
1288 // No point in warning about an undefined name, as we will
1289 // get other errors later anyhow.
1290 continue;
1292 File_block_names::const_iterator pf =
1293 this->file_block_names_.find(p->second->name());
1294 if (pf != this->file_block_names_.end())
1296 std::string n = p->second->message_name();
1297 error_at(p->second->location(),
1298 "%qs defined as both imported name and global name",
1299 n.c_str());
1300 inform(pf->second, "%qs imported here", n.c_str());
1303 // No package scope identifier may be named "init".
1304 if (!p->second->is_function()
1305 && Gogo::unpack_hidden_name(p->second->name()) == "init")
1307 error_at(p->second->location(),
1308 "cannot declare init - must be func");
1313 // Clear out names in file scope.
1315 void
1316 Gogo::clear_file_scope()
1318 this->package_->bindings()->clear_file_scope(this);
1320 // Warn about packages which were imported but not used.
1321 bool quiet = saw_errors();
1322 for (Packages::iterator p = this->packages_.begin();
1323 p != this->packages_.end();
1324 ++p)
1326 Package* package = p->second;
1327 if (package != this->package_
1328 && package->is_imported()
1329 && !package->used()
1330 && !package->uses_sink_alias()
1331 && !quiet)
1332 error_at(package->location(), "imported and not used: %s",
1333 Gogo::message_name(package->package_name()).c_str());
1334 package->clear_is_imported();
1335 package->clear_uses_sink_alias();
1336 package->clear_used();
1340 // Queue up a type specific function for later writing. These are
1341 // written out in write_specific_type_functions, called after the
1342 // parse tree is lowered.
1344 void
1345 Gogo::queue_specific_type_function(Type* type, Named_type* name,
1346 const std::string& hash_name,
1347 Function_type* hash_fntype,
1348 const std::string& equal_name,
1349 Function_type* equal_fntype)
1351 go_assert(!this->specific_type_functions_are_written_);
1352 go_assert(!this->in_global_scope());
1353 Specific_type_function* tsf = new Specific_type_function(type, name,
1354 hash_name,
1355 hash_fntype,
1356 equal_name,
1357 equal_fntype);
1358 this->specific_type_functions_.push_back(tsf);
1361 // Look for types which need specific hash or equality functions.
1363 class Specific_type_functions : public Traverse
1365 public:
1366 Specific_type_functions(Gogo* gogo)
1367 : Traverse(traverse_types),
1368 gogo_(gogo)
1372 type(Type*);
1374 private:
1375 Gogo* gogo_;
1379 Specific_type_functions::type(Type* t)
1381 Named_object* hash_fn;
1382 Named_object* equal_fn;
1383 switch (t->classification())
1385 case Type::TYPE_NAMED:
1387 Named_type* nt = t->named_type();
1388 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1389 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
1391 // If this is a struct type, we don't want to make functions
1392 // for the unnamed struct.
1393 Type* rt = nt->real_type();
1394 if (rt->struct_type() == NULL)
1396 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1397 return TRAVERSE_EXIT;
1399 else
1401 // If this type is defined in another package, then we don't
1402 // need to worry about the unexported fields.
1403 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
1404 const Struct_field_list* fields = rt->struct_type()->fields();
1405 for (Struct_field_list::const_iterator p = fields->begin();
1406 p != fields->end();
1407 ++p)
1409 if (is_defined_elsewhere
1410 && Gogo::is_hidden_name(p->field_name()))
1411 continue;
1412 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
1413 return TRAVERSE_EXIT;
1417 return TRAVERSE_SKIP_COMPONENTS;
1420 case Type::TYPE_STRUCT:
1421 case Type::TYPE_ARRAY:
1422 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
1423 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
1424 break;
1426 default:
1427 break;
1430 return TRAVERSE_CONTINUE;
1433 // Write out type specific functions.
1435 void
1436 Gogo::write_specific_type_functions()
1438 Specific_type_functions stf(this);
1439 this->traverse(&stf);
1441 while (!this->specific_type_functions_.empty())
1443 Specific_type_function* tsf = this->specific_type_functions_.back();
1444 this->specific_type_functions_.pop_back();
1445 tsf->type->write_specific_type_functions(this, tsf->name,
1446 tsf->hash_name,
1447 tsf->hash_fntype,
1448 tsf->equal_name,
1449 tsf->equal_fntype);
1450 delete tsf;
1452 this->specific_type_functions_are_written_ = true;
1455 // Traverse the tree.
1457 void
1458 Gogo::traverse(Traverse* traverse)
1460 // Traverse the current package first for consistency. The other
1461 // packages will only contain imported types, constants, and
1462 // declarations.
1463 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1464 return;
1465 for (Packages::const_iterator p = this->packages_.begin();
1466 p != this->packages_.end();
1467 ++p)
1469 if (p->second != this->package_)
1471 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1472 break;
1477 // Add a type to verify. This is used for types of sink variables, in
1478 // order to give appropriate error messages.
1480 void
1481 Gogo::add_type_to_verify(Type* type)
1483 this->verify_types_.push_back(type);
1486 // Traversal class used to verify types.
1488 class Verify_types : public Traverse
1490 public:
1491 Verify_types()
1492 : Traverse(traverse_types)
1496 type(Type*);
1499 // Verify that a type is correct.
1502 Verify_types::type(Type* t)
1504 if (!t->verify())
1505 return TRAVERSE_SKIP_COMPONENTS;
1506 return TRAVERSE_CONTINUE;
1509 // Verify that all types are correct.
1511 void
1512 Gogo::verify_types()
1514 Verify_types traverse;
1515 this->traverse(&traverse);
1517 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
1518 p != this->verify_types_.end();
1519 ++p)
1520 (*p)->verify();
1521 this->verify_types_.clear();
1524 // Traversal class used to lower parse tree.
1526 class Lower_parse_tree : public Traverse
1528 public:
1529 Lower_parse_tree(Gogo* gogo, Named_object* function)
1530 : Traverse(traverse_variables
1531 | traverse_constants
1532 | traverse_functions
1533 | traverse_statements
1534 | traverse_expressions),
1535 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
1538 void
1539 set_inserter(const Statement_inserter* inserter)
1540 { this->inserter_ = *inserter; }
1543 variable(Named_object*);
1546 constant(Named_object*, bool);
1549 function(Named_object*);
1552 statement(Block*, size_t* pindex, Statement*);
1555 expression(Expression**);
1557 private:
1558 // General IR.
1559 Gogo* gogo_;
1560 // The function we are traversing.
1561 Named_object* function_;
1562 // Value to use for the predeclared constant iota.
1563 int iota_value_;
1564 // Current statement inserter for use by expressions.
1565 Statement_inserter inserter_;
1568 // Lower variables.
1571 Lower_parse_tree::variable(Named_object* no)
1573 if (!no->is_variable())
1574 return TRAVERSE_CONTINUE;
1576 if (no->is_variable() && no->var_value()->is_global())
1578 // Global variables can have loops in their initialization
1579 // expressions. This is handled in lower_init_expression.
1580 no->var_value()->lower_init_expression(this->gogo_, this->function_,
1581 &this->inserter_);
1582 return TRAVERSE_CONTINUE;
1585 // This is a local variable. We are going to return
1586 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
1587 // initialization expression when we reach the variable declaration
1588 // statement. However, that means that we need to traverse the type
1589 // ourselves.
1590 if (no->var_value()->has_type())
1592 Type* type = no->var_value()->type();
1593 if (type != NULL)
1595 if (Type::traverse(type, this) == TRAVERSE_EXIT)
1596 return TRAVERSE_EXIT;
1599 go_assert(!no->var_value()->has_pre_init());
1601 return TRAVERSE_SKIP_COMPONENTS;
1604 // Lower constants. We handle constants specially so that we can set
1605 // the right value for the predeclared constant iota. This works in
1606 // conjunction with the way we lower Const_expression objects.
1609 Lower_parse_tree::constant(Named_object* no, bool)
1611 Named_constant* nc = no->const_value();
1613 // Don't get into trouble if the constant's initializer expression
1614 // refers to the constant itself.
1615 if (nc->lowering())
1616 return TRAVERSE_CONTINUE;
1617 nc->set_lowering();
1619 go_assert(this->iota_value_ == -1);
1620 this->iota_value_ = nc->iota_value();
1621 nc->traverse_expression(this);
1622 this->iota_value_ = -1;
1624 nc->clear_lowering();
1626 // We will traverse the expression a second time, but that will be
1627 // fast.
1629 return TRAVERSE_CONTINUE;
1632 // Lower the body of a function, and set the closure type. Record the
1633 // function while lowering it, so that we can pass it down when
1634 // lowering an expression.
1637 Lower_parse_tree::function(Named_object* no)
1639 no->func_value()->set_closure_type();
1641 go_assert(this->function_ == NULL);
1642 this->function_ = no;
1643 int t = no->func_value()->traverse(this);
1644 this->function_ = NULL;
1646 if (t == TRAVERSE_EXIT)
1647 return t;
1648 return TRAVERSE_SKIP_COMPONENTS;
1651 // Lower statement parse trees.
1654 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1656 // Because we explicitly traverse the statement's contents
1657 // ourselves, we want to skip block statements here. There is
1658 // nothing to lower in a block statement.
1659 if (sorig->is_block_statement())
1660 return TRAVERSE_CONTINUE;
1662 Statement_inserter hold_inserter(this->inserter_);
1663 this->inserter_ = Statement_inserter(block, pindex);
1665 // Lower the expressions first.
1666 int t = sorig->traverse_contents(this);
1667 if (t == TRAVERSE_EXIT)
1669 this->inserter_ = hold_inserter;
1670 return t;
1673 // Keep lowering until nothing changes.
1674 Statement* s = sorig;
1675 while (true)
1677 Statement* snew = s->lower(this->gogo_, this->function_, block,
1678 &this->inserter_);
1679 if (snew == s)
1680 break;
1681 s = snew;
1682 t = s->traverse_contents(this);
1683 if (t == TRAVERSE_EXIT)
1685 this->inserter_ = hold_inserter;
1686 return t;
1690 if (s != sorig)
1691 block->replace_statement(*pindex, s);
1693 this->inserter_ = hold_inserter;
1694 return TRAVERSE_SKIP_COMPONENTS;
1697 // Lower expression parse trees.
1700 Lower_parse_tree::expression(Expression** pexpr)
1702 // We have to lower all subexpressions first, so that we can get
1703 // their type if necessary. This is awkward, because we don't have
1704 // a postorder traversal pass.
1705 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1706 return TRAVERSE_EXIT;
1707 // Keep lowering until nothing changes.
1708 while (true)
1710 Expression* e = *pexpr;
1711 Expression* enew = e->lower(this->gogo_, this->function_,
1712 &this->inserter_, this->iota_value_);
1713 if (enew == e)
1714 break;
1715 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
1716 return TRAVERSE_EXIT;
1717 *pexpr = enew;
1719 return TRAVERSE_SKIP_COMPONENTS;
1722 // Lower the parse tree. This is called after the parse is complete,
1723 // when all names should be resolved.
1725 void
1726 Gogo::lower_parse_tree()
1728 Lower_parse_tree lower_parse_tree(this, NULL);
1729 this->traverse(&lower_parse_tree);
1732 // Lower a block.
1734 void
1735 Gogo::lower_block(Named_object* function, Block* block)
1737 Lower_parse_tree lower_parse_tree(this, function);
1738 block->traverse(&lower_parse_tree);
1741 // Lower an expression. INSERTER may be NULL, in which case the
1742 // expression had better not need to create any temporaries.
1744 void
1745 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
1746 Expression** pexpr)
1748 Lower_parse_tree lower_parse_tree(this, function);
1749 if (inserter != NULL)
1750 lower_parse_tree.set_inserter(inserter);
1751 lower_parse_tree.expression(pexpr);
1754 // Lower a constant. This is called when lowering a reference to a
1755 // constant. We have to make sure that the constant has already been
1756 // lowered.
1758 void
1759 Gogo::lower_constant(Named_object* no)
1761 go_assert(no->is_const());
1762 Lower_parse_tree lower(this, NULL);
1763 lower.constant(no, false);
1766 // Traverse the tree to create function descriptors as needed.
1768 class Create_function_descriptors : public Traverse
1770 public:
1771 Create_function_descriptors(Gogo* gogo)
1772 : Traverse(traverse_functions | traverse_expressions),
1773 gogo_(gogo)
1777 function(Named_object*);
1780 expression(Expression**);
1782 private:
1783 Gogo* gogo_;
1786 // Create a descriptor for every top-level exported function.
1789 Create_function_descriptors::function(Named_object* no)
1791 if (no->is_function()
1792 && no->func_value()->enclosing() == NULL
1793 && !no->func_value()->is_method()
1794 && !Gogo::is_hidden_name(no->name())
1795 && !Gogo::is_thunk(no))
1796 no->func_value()->descriptor(this->gogo_, no);
1798 return TRAVERSE_CONTINUE;
1801 // If we see a function referenced in any way other than calling it,
1802 // create a descriptor for it.
1805 Create_function_descriptors::expression(Expression** pexpr)
1807 Expression* expr = *pexpr;
1809 Func_expression* fe = expr->func_expression();
1810 if (fe != NULL)
1812 // We would not get here for a call to this function, so this is
1813 // a reference to a function other than calling it. We need a
1814 // descriptor.
1815 if (fe->closure() != NULL)
1816 return TRAVERSE_CONTINUE;
1817 Named_object* no = fe->named_object();
1818 if (no->is_function() && !no->func_value()->is_method())
1819 no->func_value()->descriptor(this->gogo_, no);
1820 else if (no->is_function_declaration()
1821 && !no->func_declaration_value()->type()->is_method()
1822 && !Linemap::is_predeclared_location(no->location()))
1823 no->func_declaration_value()->descriptor(this->gogo_, no);
1824 return TRAVERSE_CONTINUE;
1827 Bound_method_expression* bme = expr->bound_method_expression();
1828 if (bme != NULL)
1830 // We would not get here for a call to this method, so this is a
1831 // method value. We need to create a thunk.
1832 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
1833 bme->function());
1834 return TRAVERSE_CONTINUE;
1837 Interface_field_reference_expression* ifre =
1838 expr->interface_field_reference_expression();
1839 if (ifre != NULL)
1841 // We would not get here for a call to this interface method, so
1842 // this is a method value. We need to create a thunk.
1843 Interface_type* type = ifre->expr()->type()->interface_type();
1844 if (type != NULL)
1845 Interface_field_reference_expression::create_thunk(this->gogo_, type,
1846 ifre->name());
1847 return TRAVERSE_CONTINUE;
1850 Call_expression* ce = expr->call_expression();
1851 if (ce != NULL)
1853 Expression* fn = ce->fn();
1854 if (fn->func_expression() != NULL
1855 || fn->bound_method_expression() != NULL
1856 || fn->interface_field_reference_expression() != NULL)
1858 // Traverse the arguments but not the function.
1859 Expression_list* args = ce->args();
1860 if (args != NULL)
1862 if (args->traverse(this) == TRAVERSE_EXIT)
1863 return TRAVERSE_EXIT;
1865 return TRAVERSE_SKIP_COMPONENTS;
1869 return TRAVERSE_CONTINUE;
1872 // Create function descriptors as needed. We need a function
1873 // descriptor for all exported functions and for all functions that
1874 // are referenced without being called.
1876 void
1877 Gogo::create_function_descriptors()
1879 // Create a function descriptor for any exported function that is
1880 // declared in this package. This is so that we have a descriptor
1881 // for functions written in assembly. Gather the descriptors first
1882 // so that we don't add declarations while looping over them.
1883 std::vector<Named_object*> fndecls;
1884 Bindings* b = this->package_->bindings();
1885 for (Bindings::const_declarations_iterator p = b->begin_declarations();
1886 p != b->end_declarations();
1887 ++p)
1889 Named_object* no = p->second;
1890 if (no->is_function_declaration()
1891 && !no->func_declaration_value()->type()->is_method()
1892 && !Linemap::is_predeclared_location(no->location())
1893 && !Gogo::is_hidden_name(no->name()))
1894 fndecls.push_back(no);
1896 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
1897 p != fndecls.end();
1898 ++p)
1899 (*p)->func_declaration_value()->descriptor(this, *p);
1900 fndecls.clear();
1902 Create_function_descriptors cfd(this);
1903 this->traverse(&cfd);
1906 // Look for interface types to finalize methods of inherited
1907 // interfaces.
1909 class Finalize_methods : public Traverse
1911 public:
1912 Finalize_methods(Gogo* gogo)
1913 : Traverse(traverse_types),
1914 gogo_(gogo)
1918 type(Type*);
1920 private:
1921 Gogo* gogo_;
1924 // Finalize the methods of an interface type.
1927 Finalize_methods::type(Type* t)
1929 // Check the classification so that we don't finalize the methods
1930 // twice for a named interface type.
1931 switch (t->classification())
1933 case Type::TYPE_INTERFACE:
1934 t->interface_type()->finalize_methods();
1935 break;
1937 case Type::TYPE_NAMED:
1939 // We have to finalize the methods of the real type first.
1940 // But if the real type is a struct type, then we only want to
1941 // finalize the methods of the field types, not of the struct
1942 // type itself. We don't want to add methods to the struct,
1943 // since it has a name.
1944 Named_type* nt = t->named_type();
1945 Type* rt = nt->real_type();
1946 if (rt->classification() != Type::TYPE_STRUCT)
1948 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1949 return TRAVERSE_EXIT;
1951 else
1953 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1954 return TRAVERSE_EXIT;
1957 nt->finalize_methods(this->gogo_);
1959 // If this type is defined in a different package, then finalize the
1960 // types of all the methods, since we won't see them otherwise.
1961 if (nt->named_object()->package() != NULL && nt->has_any_methods())
1963 const Methods* methods = nt->methods();
1964 for (Methods::const_iterator p = methods->begin();
1965 p != methods->end();
1966 ++p)
1968 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
1969 return TRAVERSE_EXIT;
1973 // Finalize the types of all methods that are declared but not
1974 // defined, since we won't see the declarations otherwise.
1975 if (nt->named_object()->package() == NULL
1976 && nt->local_methods() != NULL)
1978 const Bindings* methods = nt->local_methods();
1979 for (Bindings::const_declarations_iterator p =
1980 methods->begin_declarations();
1981 p != methods->end_declarations();
1982 p++)
1984 if (p->second->is_function_declaration())
1986 Type* mt = p->second->func_declaration_value()->type();
1987 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
1988 return TRAVERSE_EXIT;
1993 return TRAVERSE_SKIP_COMPONENTS;
1996 case Type::TYPE_STRUCT:
1997 // Traverse the field types first in case there is an embedded
1998 // field with methods that the struct should inherit.
1999 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
2000 return TRAVERSE_EXIT;
2001 t->struct_type()->finalize_methods(this->gogo_);
2002 return TRAVERSE_SKIP_COMPONENTS;
2004 default:
2005 break;
2008 return TRAVERSE_CONTINUE;
2011 // Finalize method lists and build stub methods for types.
2013 void
2014 Gogo::finalize_methods()
2016 Finalize_methods finalize(this);
2017 this->traverse(&finalize);
2020 // Set types for unspecified variables and constants.
2022 void
2023 Gogo::determine_types()
2025 Bindings* bindings = this->current_bindings();
2026 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2027 p != bindings->end_definitions();
2028 ++p)
2030 if ((*p)->is_function())
2031 (*p)->func_value()->determine_types();
2032 else if ((*p)->is_variable())
2033 (*p)->var_value()->determine_type();
2034 else if ((*p)->is_const())
2035 (*p)->const_value()->determine_type();
2037 // See if a variable requires us to build an initialization
2038 // function. We know that we will see all global variables
2039 // here.
2040 if (!this->need_init_fn_ && (*p)->is_variable())
2042 Variable* variable = (*p)->var_value();
2044 // If this is a global variable which requires runtime
2045 // initialization, we need an initialization function.
2046 if (!variable->is_global())
2048 else if (variable->init() == NULL)
2050 else if (variable->type()->interface_type() != NULL)
2051 this->need_init_fn_ = true;
2052 else if (variable->init()->is_constant())
2054 else if (!variable->init()->is_composite_literal())
2055 this->need_init_fn_ = true;
2056 else if (variable->init()->is_nonconstant_composite_literal())
2057 this->need_init_fn_ = true;
2059 // If this is a global variable which holds a pointer value,
2060 // then we need an initialization function to register it as a
2061 // GC root.
2062 if (variable->is_global() && variable->type()->has_pointer())
2063 this->need_init_fn_ = true;
2067 // Determine the types of constants in packages.
2068 for (Packages::const_iterator p = this->packages_.begin();
2069 p != this->packages_.end();
2070 ++p)
2071 p->second->determine_types();
2074 // Traversal class used for type checking.
2076 class Check_types_traverse : public Traverse
2078 public:
2079 Check_types_traverse(Gogo* gogo)
2080 : Traverse(traverse_variables
2081 | traverse_constants
2082 | traverse_functions
2083 | traverse_statements
2084 | traverse_expressions),
2085 gogo_(gogo)
2089 variable(Named_object*);
2092 constant(Named_object*, bool);
2095 function(Named_object*);
2098 statement(Block*, size_t* pindex, Statement*);
2101 expression(Expression**);
2103 private:
2104 // General IR.
2105 Gogo* gogo_;
2108 // Check that a variable initializer has the right type.
2111 Check_types_traverse::variable(Named_object* named_object)
2113 if (named_object->is_variable())
2115 Variable* var = named_object->var_value();
2117 // Give error if variable type is not defined.
2118 var->type()->base();
2120 Expression* init = var->init();
2121 std::string reason;
2122 if (init != NULL
2123 && !Type::are_assignable(var->type(), init->type(), &reason))
2125 if (reason.empty())
2126 error_at(var->location(), "incompatible type in initialization");
2127 else
2128 error_at(var->location(),
2129 "incompatible type in initialization (%s)",
2130 reason.c_str());
2131 var->clear_init();
2133 else if (!var->is_used()
2134 && !var->is_global()
2135 && !var->is_parameter()
2136 && !var->is_receiver()
2137 && !var->type()->is_error()
2138 && (init == NULL || !init->is_error_expression())
2139 && !Lex::is_invalid_identifier(named_object->name()))
2140 error_at(var->location(), "%qs declared and not used",
2141 named_object->message_name().c_str());
2143 return TRAVERSE_CONTINUE;
2146 // Check that a constant initializer has the right type.
2149 Check_types_traverse::constant(Named_object* named_object, bool)
2151 Named_constant* constant = named_object->const_value();
2152 Type* ctype = constant->type();
2153 if (ctype->integer_type() == NULL
2154 && ctype->float_type() == NULL
2155 && ctype->complex_type() == NULL
2156 && !ctype->is_boolean_type()
2157 && !ctype->is_string_type())
2159 if (ctype->is_nil_type())
2160 error_at(constant->location(), "const initializer cannot be nil");
2161 else if (!ctype->is_error())
2162 error_at(constant->location(), "invalid constant type");
2163 constant->set_error();
2165 else if (!constant->expr()->is_constant())
2167 error_at(constant->expr()->location(), "expression is not constant");
2168 constant->set_error();
2170 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
2171 NULL))
2173 error_at(constant->location(),
2174 "initialization expression has wrong type");
2175 constant->set_error();
2177 return TRAVERSE_CONTINUE;
2180 // There are no types to check in a function, but this is where we
2181 // issue warnings about labels which are defined but not referenced.
2184 Check_types_traverse::function(Named_object* no)
2186 no->func_value()->check_labels();
2187 return TRAVERSE_CONTINUE;
2190 // Check that types are valid in a statement.
2193 Check_types_traverse::statement(Block*, size_t*, Statement* s)
2195 s->check_types(this->gogo_);
2196 return TRAVERSE_CONTINUE;
2199 // Check that types are valid in an expression.
2202 Check_types_traverse::expression(Expression** expr)
2204 (*expr)->check_types(this->gogo_);
2205 return TRAVERSE_CONTINUE;
2208 // Check that types are valid.
2210 void
2211 Gogo::check_types()
2213 Check_types_traverse traverse(this);
2214 this->traverse(&traverse);
2217 // Check the types in a single block.
2219 void
2220 Gogo::check_types_in_block(Block* block)
2222 Check_types_traverse traverse(this);
2223 block->traverse(&traverse);
2226 // A traversal class used to find a single shortcut operator within an
2227 // expression.
2229 class Find_shortcut : public Traverse
2231 public:
2232 Find_shortcut()
2233 : Traverse(traverse_blocks
2234 | traverse_statements
2235 | traverse_expressions),
2236 found_(NULL)
2239 // A pointer to the expression which was found, or NULL if none was
2240 // found.
2241 Expression**
2242 found() const
2243 { return this->found_; }
2245 protected:
2247 block(Block*)
2248 { return TRAVERSE_SKIP_COMPONENTS; }
2251 statement(Block*, size_t*, Statement*)
2252 { return TRAVERSE_SKIP_COMPONENTS; }
2255 expression(Expression**);
2257 private:
2258 Expression** found_;
2261 // Find a shortcut expression.
2264 Find_shortcut::expression(Expression** pexpr)
2266 Expression* expr = *pexpr;
2267 Binary_expression* be = expr->binary_expression();
2268 if (be == NULL)
2269 return TRAVERSE_CONTINUE;
2270 Operator op = be->op();
2271 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
2272 return TRAVERSE_CONTINUE;
2273 go_assert(this->found_ == NULL);
2274 this->found_ = pexpr;
2275 return TRAVERSE_EXIT;
2278 // A traversal class used to turn shortcut operators into explicit if
2279 // statements.
2281 class Shortcuts : public Traverse
2283 public:
2284 Shortcuts(Gogo* gogo)
2285 : Traverse(traverse_variables
2286 | traverse_statements),
2287 gogo_(gogo)
2290 protected:
2292 variable(Named_object*);
2295 statement(Block*, size_t*, Statement*);
2297 private:
2298 // Convert a shortcut operator.
2299 Statement*
2300 convert_shortcut(Block* enclosing, Expression** pshortcut);
2302 // The IR.
2303 Gogo* gogo_;
2306 // Remove shortcut operators in a single statement.
2309 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
2311 // FIXME: This approach doesn't work for switch statements, because
2312 // we add the new statements before the whole switch when we need to
2313 // instead add them just before the switch expression. The right
2314 // fix is probably to lower switch statements with nonconstant cases
2315 // to a series of conditionals.
2316 if (s->switch_statement() != NULL)
2317 return TRAVERSE_CONTINUE;
2319 while (true)
2321 Find_shortcut find_shortcut;
2323 // If S is a variable declaration, then ordinary traversal won't
2324 // do anything. We want to explicitly traverse the
2325 // initialization expression if there is one.
2326 Variable_declaration_statement* vds = s->variable_declaration_statement();
2327 Expression* init = NULL;
2328 if (vds == NULL)
2329 s->traverse_contents(&find_shortcut);
2330 else
2332 init = vds->var()->var_value()->init();
2333 if (init == NULL)
2334 return TRAVERSE_CONTINUE;
2335 init->traverse(&init, &find_shortcut);
2337 Expression** pshortcut = find_shortcut.found();
2338 if (pshortcut == NULL)
2339 return TRAVERSE_CONTINUE;
2341 Statement* snew = this->convert_shortcut(block, pshortcut);
2342 block->insert_statement_before(*pindex, snew);
2343 ++*pindex;
2345 if (pshortcut == &init)
2346 vds->var()->var_value()->set_init(init);
2350 // Remove shortcut operators in the initializer of a global variable.
2353 Shortcuts::variable(Named_object* no)
2355 if (no->is_result_variable())
2356 return TRAVERSE_CONTINUE;
2357 Variable* var = no->var_value();
2358 Expression* init = var->init();
2359 if (!var->is_global() || init == NULL)
2360 return TRAVERSE_CONTINUE;
2362 while (true)
2364 Find_shortcut find_shortcut;
2365 init->traverse(&init, &find_shortcut);
2366 Expression** pshortcut = find_shortcut.found();
2367 if (pshortcut == NULL)
2368 return TRAVERSE_CONTINUE;
2370 Statement* snew = this->convert_shortcut(NULL, pshortcut);
2371 var->add_preinit_statement(this->gogo_, snew);
2372 if (pshortcut == &init)
2373 var->set_init(init);
2377 // Given an expression which uses a shortcut operator, return a
2378 // statement which implements it, and update *PSHORTCUT accordingly.
2380 Statement*
2381 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
2383 Binary_expression* shortcut = (*pshortcut)->binary_expression();
2384 Expression* left = shortcut->left();
2385 Expression* right = shortcut->right();
2386 Location loc = shortcut->location();
2388 Block* retblock = new Block(enclosing, loc);
2389 retblock->set_end_location(loc);
2391 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
2392 left, loc);
2393 retblock->add_statement(ts);
2395 Block* block = new Block(retblock, loc);
2396 block->set_end_location(loc);
2397 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
2398 Statement* assign = Statement::make_assignment(tmpref, right, loc);
2399 block->add_statement(assign);
2401 Expression* cond = Expression::make_temporary_reference(ts, loc);
2402 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
2403 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
2405 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
2406 loc);
2407 retblock->add_statement(if_statement);
2409 *pshortcut = Expression::make_temporary_reference(ts, loc);
2411 delete shortcut;
2413 // Now convert any shortcut operators in LEFT and RIGHT.
2414 Shortcuts shortcuts(this->gogo_);
2415 retblock->traverse(&shortcuts);
2417 return Statement::make_block_statement(retblock, loc);
2420 // Turn shortcut operators into explicit if statements. Doing this
2421 // considerably simplifies the order of evaluation rules.
2423 void
2424 Gogo::remove_shortcuts()
2426 Shortcuts shortcuts(this);
2427 this->traverse(&shortcuts);
2430 // A traversal class which finds all the expressions which must be
2431 // evaluated in order within a statement or larger expression. This
2432 // is used to implement the rules about order of evaluation.
2434 class Find_eval_ordering : public Traverse
2436 private:
2437 typedef std::vector<Expression**> Expression_pointers;
2439 public:
2440 Find_eval_ordering()
2441 : Traverse(traverse_blocks
2442 | traverse_statements
2443 | traverse_expressions),
2444 exprs_()
2447 size_t
2448 size() const
2449 { return this->exprs_.size(); }
2451 typedef Expression_pointers::const_iterator const_iterator;
2453 const_iterator
2454 begin() const
2455 { return this->exprs_.begin(); }
2457 const_iterator
2458 end() const
2459 { return this->exprs_.end(); }
2461 protected:
2463 block(Block*)
2464 { return TRAVERSE_SKIP_COMPONENTS; }
2467 statement(Block*, size_t*, Statement*)
2468 { return TRAVERSE_SKIP_COMPONENTS; }
2471 expression(Expression**);
2473 private:
2474 // A list of pointers to expressions with side-effects.
2475 Expression_pointers exprs_;
2478 // If an expression must be evaluated in order, put it on the list.
2481 Find_eval_ordering::expression(Expression** expression_pointer)
2483 // We have to look at subexpressions before this one.
2484 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2485 return TRAVERSE_EXIT;
2486 if ((*expression_pointer)->must_eval_in_order())
2487 this->exprs_.push_back(expression_pointer);
2488 return TRAVERSE_SKIP_COMPONENTS;
2491 // A traversal class for ordering evaluations.
2493 class Order_eval : public Traverse
2495 public:
2496 Order_eval(Gogo* gogo)
2497 : Traverse(traverse_variables
2498 | traverse_statements),
2499 gogo_(gogo)
2503 variable(Named_object*);
2506 statement(Block*, size_t*, Statement*);
2508 private:
2509 // The IR.
2510 Gogo* gogo_;
2513 // Implement the order of evaluation rules for a statement.
2516 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
2518 // FIXME: This approach doesn't work for switch statements, because
2519 // we add the new statements before the whole switch when we need to
2520 // instead add them just before the switch expression. The right
2521 // fix is probably to lower switch statements with nonconstant cases
2522 // to a series of conditionals.
2523 if (s->switch_statement() != NULL)
2524 return TRAVERSE_CONTINUE;
2526 Find_eval_ordering find_eval_ordering;
2528 // If S is a variable declaration, then ordinary traversal won't do
2529 // anything. We want to explicitly traverse the initialization
2530 // expression if there is one.
2531 Variable_declaration_statement* vds = s->variable_declaration_statement();
2532 Expression* init = NULL;
2533 Expression* orig_init = NULL;
2534 if (vds == NULL)
2535 s->traverse_contents(&find_eval_ordering);
2536 else
2538 init = vds->var()->var_value()->init();
2539 if (init == NULL)
2540 return TRAVERSE_CONTINUE;
2541 orig_init = init;
2543 // It might seem that this could be
2544 // init->traverse_subexpressions. Unfortunately that can fail
2545 // in a case like
2546 // var err os.Error
2547 // newvar, err := call(arg())
2548 // Here newvar will have an init of call result 0 of
2549 // call(arg()). If we only traverse subexpressions, we will
2550 // only find arg(), and we won't bother to move anything out.
2551 // Then we get to the assignment to err, we will traverse the
2552 // whole statement, and this time we will find both call() and
2553 // arg(), and so we will move them out. This will cause them to
2554 // be put into temporary variables before the assignment to err
2555 // but after the declaration of newvar. To avoid that problem,
2556 // we traverse the entire expression here.
2557 Expression::traverse(&init, &find_eval_ordering);
2560 size_t c = find_eval_ordering.size();
2561 if (c == 0)
2562 return TRAVERSE_CONTINUE;
2564 // If there is only one expression with a side-effect, we can
2565 // usually leave it in place.
2566 if (c == 1)
2568 switch (s->classification())
2570 case Statement::STATEMENT_ASSIGNMENT:
2571 // For an assignment statement, we need to evaluate an
2572 // expression on the right hand side before we evaluate any
2573 // index expression on the left hand side, so for that case
2574 // we always move the expression. Otherwise we mishandle
2575 // m[0] = len(m) where m is a map.
2576 break;
2578 case Statement::STATEMENT_EXPRESSION:
2580 // If this is a call statement that doesn't return any
2581 // values, it will not have been counted as a value to
2582 // move. We need to move any subexpressions in case they
2583 // are themselves call statements that require passing a
2584 // closure.
2585 Expression* expr = s->expression_statement()->expr();
2586 if (expr->call_expression() != NULL
2587 && expr->call_expression()->result_count() == 0)
2588 break;
2589 return TRAVERSE_CONTINUE;
2592 default:
2593 // We can leave the expression in place.
2594 return TRAVERSE_CONTINUE;
2598 bool is_thunk = s->thunk_statement() != NULL;
2599 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2600 p != find_eval_ordering.end();
2601 ++p)
2603 Expression** pexpr = *p;
2605 // The last expression in a thunk will be the call passed to go
2606 // or defer, which we must not evaluate early.
2607 if (is_thunk && p + 1 == find_eval_ordering.end())
2608 break;
2610 Location loc = (*pexpr)->location();
2611 Statement* s;
2612 if ((*pexpr)->call_expression() == NULL
2613 || (*pexpr)->call_expression()->result_count() < 2)
2615 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2616 loc);
2617 s = ts;
2618 *pexpr = Expression::make_temporary_reference(ts, loc);
2620 else
2622 // A call expression which returns multiple results needs to
2623 // be handled specially. We can't create a temporary
2624 // because there is no type to give it. Any actual uses of
2625 // the values will be done via Call_result_expressions.
2626 s = Statement::make_statement(*pexpr, true);
2629 block->insert_statement_before(*pindex, s);
2630 ++*pindex;
2633 if (init != orig_init)
2634 vds->var()->var_value()->set_init(init);
2636 return TRAVERSE_CONTINUE;
2639 // Implement the order of evaluation rules for the initializer of a
2640 // global variable.
2643 Order_eval::variable(Named_object* no)
2645 if (no->is_result_variable())
2646 return TRAVERSE_CONTINUE;
2647 Variable* var = no->var_value();
2648 Expression* init = var->init();
2649 if (!var->is_global() || init == NULL)
2650 return TRAVERSE_CONTINUE;
2652 Find_eval_ordering find_eval_ordering;
2653 Expression::traverse(&init, &find_eval_ordering);
2655 if (find_eval_ordering.size() <= 1)
2657 // If there is only one expression with a side-effect, we can
2658 // leave it in place.
2659 return TRAVERSE_SKIP_COMPONENTS;
2662 Expression* orig_init = init;
2664 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
2665 p != find_eval_ordering.end();
2666 ++p)
2668 Expression** pexpr = *p;
2669 Location loc = (*pexpr)->location();
2670 Statement* s;
2671 if ((*pexpr)->call_expression() == NULL
2672 || (*pexpr)->call_expression()->result_count() < 2)
2674 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
2675 loc);
2676 s = ts;
2677 *pexpr = Expression::make_temporary_reference(ts, loc);
2679 else
2681 // A call expression which returns multiple results needs to
2682 // be handled specially.
2683 s = Statement::make_statement(*pexpr, true);
2685 var->add_preinit_statement(this->gogo_, s);
2688 if (init != orig_init)
2689 var->set_init(init);
2691 return TRAVERSE_SKIP_COMPONENTS;
2694 // Use temporary variables to implement the order of evaluation rules.
2696 void
2697 Gogo::order_evaluations()
2699 Order_eval order_eval(this);
2700 this->traverse(&order_eval);
2703 // Traversal to convert calls to the predeclared recover function to
2704 // pass in an argument indicating whether it can recover from a panic
2705 // or not.
2707 class Convert_recover : public Traverse
2709 public:
2710 Convert_recover(Named_object* arg)
2711 : Traverse(traverse_expressions),
2712 arg_(arg)
2715 protected:
2717 expression(Expression**);
2719 private:
2720 // The argument to pass to the function.
2721 Named_object* arg_;
2724 // Convert calls to recover.
2727 Convert_recover::expression(Expression** pp)
2729 Call_expression* ce = (*pp)->call_expression();
2730 if (ce != NULL && ce->is_recover_call())
2731 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2732 ce->location()));
2733 return TRAVERSE_CONTINUE;
2736 // Traversal for build_recover_thunks.
2738 class Build_recover_thunks : public Traverse
2740 public:
2741 Build_recover_thunks(Gogo* gogo)
2742 : Traverse(traverse_functions),
2743 gogo_(gogo)
2747 function(Named_object*);
2749 private:
2750 Expression*
2751 can_recover_arg(Location);
2753 // General IR.
2754 Gogo* gogo_;
2757 // If this function calls recover, turn it into a thunk.
2760 Build_recover_thunks::function(Named_object* orig_no)
2762 Function* orig_func = orig_no->func_value();
2763 if (!orig_func->calls_recover()
2764 || orig_func->is_recover_thunk()
2765 || orig_func->has_recover_thunk())
2766 return TRAVERSE_CONTINUE;
2768 Gogo* gogo = this->gogo_;
2769 Location location = orig_func->location();
2771 static int count;
2772 char buf[50];
2774 Function_type* orig_fntype = orig_func->type();
2775 Typed_identifier_list* new_params = new Typed_identifier_list();
2776 std::string receiver_name;
2777 if (orig_fntype->is_method())
2779 const Typed_identifier* receiver = orig_fntype->receiver();
2780 snprintf(buf, sizeof buf, "rt.%u", count);
2781 ++count;
2782 receiver_name = buf;
2783 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2784 receiver->location()));
2786 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2787 if (orig_params != NULL && !orig_params->empty())
2789 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2790 p != orig_params->end();
2791 ++p)
2793 snprintf(buf, sizeof buf, "pt.%u", count);
2794 ++count;
2795 new_params->push_back(Typed_identifier(buf, p->type(),
2796 p->location()));
2799 snprintf(buf, sizeof buf, "pr.%u", count);
2800 ++count;
2801 std::string can_recover_name = buf;
2802 new_params->push_back(Typed_identifier(can_recover_name,
2803 Type::lookup_bool_type(),
2804 orig_fntype->location()));
2806 const Typed_identifier_list* orig_results = orig_fntype->results();
2807 Typed_identifier_list* new_results;
2808 if (orig_results == NULL || orig_results->empty())
2809 new_results = NULL;
2810 else
2812 new_results = new Typed_identifier_list();
2813 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2814 p != orig_results->end();
2815 ++p)
2816 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2819 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2820 new_results,
2821 orig_fntype->location());
2822 if (orig_fntype->is_varargs())
2823 new_fntype->set_is_varargs();
2825 std::string name = orig_no->name() + "$recover";
2826 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2827 location);
2828 Function *new_func = new_no->func_value();
2829 if (orig_func->enclosing() != NULL)
2830 new_func->set_enclosing(orig_func->enclosing());
2832 // We build the code for the original function attached to the new
2833 // function, and then swap the original and new function bodies.
2834 // This means that existing references to the original function will
2835 // then refer to the new function. That makes this code a little
2836 // confusing, in that the reference to NEW_NO really refers to the
2837 // other function, not the one we are building.
2839 Expression* closure = NULL;
2840 if (orig_func->needs_closure())
2842 // For the new function we are creating, declare a new parameter
2843 // variable NEW_CLOSURE_NO and set it to be the closure variable
2844 // of the function. This will be set to the closure value
2845 // passed in by the caller. Then pass a reference to this
2846 // variable as the closure value when calling the original
2847 // function. In other words, simply pass the closure value
2848 // through the thunk we are creating.
2849 Named_object* orig_closure_no = orig_func->closure_var();
2850 Variable* orig_closure_var = orig_closure_no->var_value();
2851 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2852 false, false, location);
2853 snprintf(buf, sizeof buf, "closure.%u", count);
2854 ++count;
2855 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2856 new_var);
2857 new_func->set_closure_var(new_closure_no);
2858 closure = Expression::make_var_reference(new_closure_no, location);
2861 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2863 Expression_list* args = new Expression_list();
2864 if (new_params != NULL)
2866 // Note that we skip the last parameter, which is the boolean
2867 // indicating whether recover can succed.
2868 for (Typed_identifier_list::const_iterator p = new_params->begin();
2869 p + 1 != new_params->end();
2870 ++p)
2872 Named_object* p_no = gogo->lookup(p->name(), NULL);
2873 go_assert(p_no != NULL
2874 && p_no->is_variable()
2875 && p_no->var_value()->is_parameter());
2876 args->push_back(Expression::make_var_reference(p_no, location));
2879 args->push_back(this->can_recover_arg(location));
2881 gogo->start_block(location);
2883 Call_expression* call = Expression::make_call(fn, args, false, location);
2885 // Any varargs call has already been lowered.
2886 call->set_varargs_are_lowered();
2888 Statement* s = Statement::make_return_from_call(call, location);
2889 s->determine_types();
2890 gogo->add_statement(s);
2892 Block* b = gogo->finish_block(location);
2894 gogo->add_block(b, location);
2896 // Lower the call in case it returns multiple results.
2897 gogo->lower_block(new_no, b);
2899 gogo->finish_function(location);
2901 // Swap the function bodies and types.
2902 new_func->swap_for_recover(orig_func);
2903 orig_func->set_is_recover_thunk();
2904 new_func->set_calls_recover();
2905 new_func->set_has_recover_thunk();
2907 Bindings* orig_bindings = orig_func->block()->bindings();
2908 Bindings* new_bindings = new_func->block()->bindings();
2909 if (orig_fntype->is_method())
2911 // We changed the receiver to be a regular parameter. We have
2912 // to update the binding accordingly in both functions.
2913 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2914 go_assert(orig_rec_no != NULL
2915 && orig_rec_no->is_variable()
2916 && !orig_rec_no->var_value()->is_receiver());
2917 orig_rec_no->var_value()->set_is_receiver();
2919 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2920 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2921 if (new_rec_no == NULL)
2922 go_assert(saw_errors());
2923 else
2925 go_assert(new_rec_no->is_variable()
2926 && new_rec_no->var_value()->is_receiver());
2927 new_rec_no->var_value()->set_is_not_receiver();
2931 // Because we flipped blocks but not types, the can_recover
2932 // parameter appears in the (now) old bindings as a parameter.
2933 // Change it to a local variable, whereupon it will be discarded.
2934 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2935 go_assert(can_recover_no != NULL
2936 && can_recover_no->is_variable()
2937 && can_recover_no->var_value()->is_parameter());
2938 orig_bindings->remove_binding(can_recover_no);
2940 // Add the can_recover argument to the (now) new bindings, and
2941 // attach it to any recover statements.
2942 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2943 false, true, false, location);
2944 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2945 can_recover_var);
2946 Convert_recover convert_recover(can_recover_no);
2947 new_func->traverse(&convert_recover);
2949 // Update the function pointers in any named results.
2950 new_func->update_result_variables();
2951 orig_func->update_result_variables();
2953 return TRAVERSE_CONTINUE;
2956 // Return the expression to pass for the .can_recover parameter to the
2957 // new function. This indicates whether a call to recover may return
2958 // non-nil. The expression is
2959 // __go_can_recover(__builtin_return_address()).
2961 Expression*
2962 Build_recover_thunks::can_recover_arg(Location location)
2964 static Named_object* builtin_return_address;
2965 if (builtin_return_address == NULL)
2967 const Location bloc = Linemap::predeclared_location();
2969 Typed_identifier_list* param_types = new Typed_identifier_list();
2970 Type* uint_type = Type::lookup_integer_type("uint");
2971 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2973 Typed_identifier_list* return_types = new Typed_identifier_list();
2974 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2975 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2977 Function_type* fntype = Type::make_function_type(NULL, param_types,
2978 return_types, bloc);
2979 builtin_return_address =
2980 Named_object::make_function_declaration("__builtin_return_address",
2981 NULL, fntype, bloc);
2982 const char* n = "__builtin_return_address";
2983 builtin_return_address->func_declaration_value()->set_asm_name(n);
2986 static Named_object* can_recover;
2987 if (can_recover == NULL)
2989 const Location bloc = Linemap::predeclared_location();
2990 Typed_identifier_list* param_types = new Typed_identifier_list();
2991 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2992 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2993 Type* boolean_type = Type::lookup_bool_type();
2994 Typed_identifier_list* results = new Typed_identifier_list();
2995 results->push_back(Typed_identifier("", boolean_type, bloc));
2996 Function_type* fntype = Type::make_function_type(NULL, param_types,
2997 results, bloc);
2998 can_recover = Named_object::make_function_declaration("__go_can_recover",
2999 NULL, fntype,
3000 bloc);
3001 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
3004 Expression* fn = Expression::make_func_reference(builtin_return_address,
3005 NULL, location);
3007 mpz_t zval;
3008 mpz_init_set_ui(zval, 0UL);
3009 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
3010 mpz_clear(zval);
3011 Expression_list *args = new Expression_list();
3012 args->push_back(zexpr);
3014 Expression* call = Expression::make_call(fn, args, false, location);
3016 args = new Expression_list();
3017 args->push_back(call);
3019 fn = Expression::make_func_reference(can_recover, NULL, location);
3020 return Expression::make_call(fn, args, false, location);
3023 // Build thunks for functions which call recover. We build a new
3024 // function with an extra parameter, which is whether a call to
3025 // recover can succeed. We then move the body of this function to
3026 // that one. We then turn this function into a thunk which calls the
3027 // new one, passing the value of
3028 // __go_can_recover(__builtin_return_address()). The function will be
3029 // marked as not splitting the stack. This will cooperate with the
3030 // implementation of defer to make recover do the right thing.
3032 void
3033 Gogo::build_recover_thunks()
3035 Build_recover_thunks build_recover_thunks(this);
3036 this->traverse(&build_recover_thunks);
3039 // Look for named types to see whether we need to create an interface
3040 // method table.
3042 class Build_method_tables : public Traverse
3044 public:
3045 Build_method_tables(Gogo* gogo,
3046 const std::vector<Interface_type*>& interfaces)
3047 : Traverse(traverse_types),
3048 gogo_(gogo), interfaces_(interfaces)
3052 type(Type*);
3054 private:
3055 // The IR.
3056 Gogo* gogo_;
3057 // A list of locally defined interfaces which have hidden methods.
3058 const std::vector<Interface_type*>& interfaces_;
3061 // Build all required interface method tables for types. We need to
3062 // ensure that we have an interface method table for every interface
3063 // which has a hidden method, for every named type which implements
3064 // that interface. Normally we can just build interface method tables
3065 // as we need them. However, in some cases we can require an
3066 // interface method table for an interface defined in a different
3067 // package for a type defined in that package. If that interface and
3068 // type both use a hidden method, that is OK. However, we will not be
3069 // able to build that interface method table when we need it, because
3070 // the type's hidden method will be static. So we have to build it
3071 // here, and just refer it from other packages as needed.
3073 void
3074 Gogo::build_interface_method_tables()
3076 if (saw_errors())
3077 return;
3079 std::vector<Interface_type*> hidden_interfaces;
3080 hidden_interfaces.reserve(this->interface_types_.size());
3081 for (std::vector<Interface_type*>::const_iterator pi =
3082 this->interface_types_.begin();
3083 pi != this->interface_types_.end();
3084 ++pi)
3086 const Typed_identifier_list* methods = (*pi)->methods();
3087 if (methods == NULL)
3088 continue;
3089 for (Typed_identifier_list::const_iterator pm = methods->begin();
3090 pm != methods->end();
3091 ++pm)
3093 if (Gogo::is_hidden_name(pm->name()))
3095 hidden_interfaces.push_back(*pi);
3096 break;
3101 if (!hidden_interfaces.empty())
3103 // Now traverse the tree looking for all named types.
3104 Build_method_tables bmt(this, hidden_interfaces);
3105 this->traverse(&bmt);
3108 // We no longer need the list of interfaces.
3110 this->interface_types_.clear();
3113 // This is called for each type. For a named type, for each of the
3114 // interfaces with hidden methods that it implements, create the
3115 // method table.
3118 Build_method_tables::type(Type* type)
3120 Named_type* nt = type->named_type();
3121 Struct_type* st = type->struct_type();
3122 if (nt != NULL || st != NULL)
3124 for (std::vector<Interface_type*>::const_iterator p =
3125 this->interfaces_.begin();
3126 p != this->interfaces_.end();
3127 ++p)
3129 // We ask whether a pointer to the named type implements the
3130 // interface, because a pointer can implement more methods
3131 // than a value.
3132 if (nt != NULL)
3134 if ((*p)->implements_interface(Type::make_pointer_type(nt),
3135 NULL))
3137 nt->interface_method_table(this->gogo_, *p, false);
3138 nt->interface_method_table(this->gogo_, *p, true);
3141 else
3143 if ((*p)->implements_interface(Type::make_pointer_type(st),
3144 NULL))
3146 st->interface_method_table(this->gogo_, *p, false);
3147 st->interface_method_table(this->gogo_, *p, true);
3152 return TRAVERSE_CONTINUE;
3155 // Traversal class used to check for return statements.
3157 class Check_return_statements_traverse : public Traverse
3159 public:
3160 Check_return_statements_traverse()
3161 : Traverse(traverse_functions)
3165 function(Named_object*);
3168 // Check that a function has a return statement if it needs one.
3171 Check_return_statements_traverse::function(Named_object* no)
3173 Function* func = no->func_value();
3174 const Function_type* fntype = func->type();
3175 const Typed_identifier_list* results = fntype->results();
3177 // We only need a return statement if there is a return value.
3178 if (results == NULL || results->empty())
3179 return TRAVERSE_CONTINUE;
3181 if (func->block()->may_fall_through())
3182 error_at(func->block()->end_location(),
3183 "missing return at end of function");
3185 return TRAVERSE_CONTINUE;
3188 // Check return statements.
3190 void
3191 Gogo::check_return_statements()
3193 Check_return_statements_traverse traverse;
3194 this->traverse(&traverse);
3197 // Work out the package priority. It is one more than the maximum
3198 // priority of an imported package.
3201 Gogo::package_priority() const
3203 int priority = 0;
3204 for (Packages::const_iterator p = this->packages_.begin();
3205 p != this->packages_.end();
3206 ++p)
3207 if (p->second->priority() > priority)
3208 priority = p->second->priority();
3209 return priority + 1;
3212 // Export identifiers as requested.
3214 void
3215 Gogo::do_exports()
3217 // For now we always stream to a section. Later we may want to
3218 // support streaming to a separate file.
3219 Stream_to_section stream;
3221 Export exp(&stream);
3222 exp.register_builtin_types(this);
3223 exp.export_globals(this->package_name(),
3224 this->pkgpath(),
3225 this->package_priority(),
3226 this->imports_,
3227 (this->need_init_fn_ && !this->is_main_package()
3228 ? this->get_init_fn_name()
3229 : ""),
3230 this->imported_init_fns_,
3231 this->package_->bindings());
3234 // Find the blocks in order to convert named types defined in blocks.
3236 class Convert_named_types : public Traverse
3238 public:
3239 Convert_named_types(Gogo* gogo)
3240 : Traverse(traverse_blocks),
3241 gogo_(gogo)
3244 protected:
3246 block(Block* block);
3248 private:
3249 Gogo* gogo_;
3253 Convert_named_types::block(Block* block)
3255 this->gogo_->convert_named_types_in_bindings(block->bindings());
3256 return TRAVERSE_CONTINUE;
3259 // Convert all named types to the backend representation. Since named
3260 // types can refer to other types, this needs to be done in the right
3261 // sequence, which is handled by Named_type::convert. Here we arrange
3262 // to call that for each named type.
3264 void
3265 Gogo::convert_named_types()
3267 this->convert_named_types_in_bindings(this->globals_);
3268 for (Packages::iterator p = this->packages_.begin();
3269 p != this->packages_.end();
3270 ++p)
3272 Package* package = p->second;
3273 this->convert_named_types_in_bindings(package->bindings());
3276 Convert_named_types cnt(this);
3277 this->traverse(&cnt);
3279 // Make all the builtin named types used for type descriptors, and
3280 // then convert them. They will only be written out if they are
3281 // needed.
3282 Type::make_type_descriptor_type();
3283 Type::make_type_descriptor_ptr_type();
3284 Function_type::make_function_type_descriptor_type();
3285 Pointer_type::make_pointer_type_descriptor_type();
3286 Struct_type::make_struct_type_descriptor_type();
3287 Array_type::make_array_type_descriptor_type();
3288 Array_type::make_slice_type_descriptor_type();
3289 Map_type::make_map_type_descriptor_type();
3290 Map_type::make_map_descriptor_type();
3291 Channel_type::make_chan_type_descriptor_type();
3292 Interface_type::make_interface_type_descriptor_type();
3293 Expression::make_func_descriptor_type();
3294 Type::convert_builtin_named_types(this);
3296 Runtime::convert_types(this);
3298 this->named_types_are_converted_ = true;
3301 // Convert all names types in a set of bindings.
3303 void
3304 Gogo::convert_named_types_in_bindings(Bindings* bindings)
3306 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3307 p != bindings->end_definitions();
3308 ++p)
3310 if ((*p)->is_type())
3311 (*p)->type_value()->convert(this);
3315 // Class Function.
3317 Function::Function(Function_type* type, Function* enclosing, Block* block,
3318 Location location)
3319 : type_(type), enclosing_(enclosing), results_(NULL),
3320 closure_var_(NULL), block_(block), location_(location), labels_(),
3321 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
3322 is_sink_(false), results_are_named_(false), nointerface_(false),
3323 calls_recover_(false), is_recover_thunk_(false), has_recover_thunk_(false),
3324 in_unique_section_(false)
3328 // Create the named result variables.
3330 void
3331 Function::create_result_variables(Gogo* gogo)
3333 const Typed_identifier_list* results = this->type_->results();
3334 if (results == NULL || results->empty())
3335 return;
3337 if (!results->front().name().empty())
3338 this->results_are_named_ = true;
3340 this->results_ = new Results();
3341 this->results_->reserve(results->size());
3343 Block* block = this->block_;
3344 int index = 0;
3345 for (Typed_identifier_list::const_iterator p = results->begin();
3346 p != results->end();
3347 ++p, ++index)
3349 std::string name = p->name();
3350 if (name.empty() || Gogo::is_sink_name(name))
3352 static int result_counter;
3353 char buf[100];
3354 snprintf(buf, sizeof buf, "$ret%d", result_counter);
3355 ++result_counter;
3356 name = gogo->pack_hidden_name(buf, false);
3358 Result_variable* result = new Result_variable(p->type(), this, index,
3359 p->location());
3360 Named_object* no = block->bindings()->add_result_variable(name, result);
3361 if (no->is_result_variable())
3362 this->results_->push_back(no);
3363 else
3365 static int dummy_result_count;
3366 char buf[100];
3367 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
3368 ++dummy_result_count;
3369 name = gogo->pack_hidden_name(buf, false);
3370 no = block->bindings()->add_result_variable(name, result);
3371 go_assert(no->is_result_variable());
3372 this->results_->push_back(no);
3377 // Update the named result variables when cloning a function which
3378 // calls recover.
3380 void
3381 Function::update_result_variables()
3383 if (this->results_ == NULL)
3384 return;
3386 for (Results::iterator p = this->results_->begin();
3387 p != this->results_->end();
3388 ++p)
3389 (*p)->result_var_value()->set_function(this);
3392 // Return the closure variable, creating it if necessary.
3394 Named_object*
3395 Function::closure_var()
3397 if (this->closure_var_ == NULL)
3399 go_assert(this->descriptor_ == NULL);
3400 // We don't know the type of the variable yet. We add fields as
3401 // we find them.
3402 Location loc = this->type_->location();
3403 Struct_field_list* sfl = new Struct_field_list;
3404 Type* struct_type = Type::make_struct_type(sfl, loc);
3405 Variable* var = new Variable(Type::make_pointer_type(struct_type),
3406 NULL, false, false, false, loc);
3407 var->set_is_used();
3408 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
3409 // Note that the new variable is not in any binding contour.
3411 return this->closure_var_;
3414 // Set the type of the closure variable.
3416 void
3417 Function::set_closure_type()
3419 if (this->closure_var_ == NULL)
3420 return;
3421 Named_object* closure = this->closure_var_;
3422 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
3424 // The first field of a closure is always a pointer to the function
3425 // code.
3426 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
3427 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
3428 this->location_)));
3430 unsigned int index = 1;
3431 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
3432 p != this->closure_fields_.end();
3433 ++p, ++index)
3435 Named_object* no = p->first;
3436 char buf[20];
3437 snprintf(buf, sizeof buf, "%u", index);
3438 std::string n = no->name() + buf;
3439 Type* var_type;
3440 if (no->is_variable())
3441 var_type = no->var_value()->type();
3442 else
3443 var_type = no->result_var_value()->type();
3444 Type* field_type = Type::make_pointer_type(var_type);
3445 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
3449 // Return whether this function is a method.
3451 bool
3452 Function::is_method() const
3454 return this->type_->is_method();
3457 // Add a label definition.
3459 Label*
3460 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
3461 Location location)
3463 Label* lnull = NULL;
3464 std::pair<Labels::iterator, bool> ins =
3465 this->labels_.insert(std::make_pair(label_name, lnull));
3466 Label* label;
3467 if (ins.second)
3469 // This is a new label.
3470 label = new Label(label_name);
3471 ins.first->second = label;
3473 else
3475 // The label was already in the hash table.
3476 label = ins.first->second;
3477 if (label->is_defined())
3479 error_at(location, "label %qs already defined",
3480 Gogo::message_name(label_name).c_str());
3481 inform(label->location(), "previous definition of %qs was here",
3482 Gogo::message_name(label_name).c_str());
3483 return new Label(label_name);
3487 label->define(location, gogo->bindings_snapshot(location));
3489 // Issue any errors appropriate for any previous goto's to this
3490 // label.
3491 const std::vector<Bindings_snapshot*>& refs(label->refs());
3492 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
3493 p != refs.end();
3494 ++p)
3495 (*p)->check_goto_to(gogo->current_block());
3496 label->clear_refs();
3498 return label;
3501 // Add a reference to a label.
3503 Label*
3504 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
3505 Location location, bool issue_goto_errors)
3507 Label* lnull = NULL;
3508 std::pair<Labels::iterator, bool> ins =
3509 this->labels_.insert(std::make_pair(label_name, lnull));
3510 Label* label;
3511 if (!ins.second)
3513 // The label was already in the hash table.
3514 label = ins.first->second;
3516 else
3518 go_assert(ins.first->second == NULL);
3519 label = new Label(label_name);
3520 ins.first->second = label;
3523 label->set_is_used();
3525 if (issue_goto_errors)
3527 Bindings_snapshot* snapshot = label->snapshot();
3528 if (snapshot != NULL)
3529 snapshot->check_goto_from(gogo->current_block(), location);
3530 else
3531 label->add_snapshot_ref(gogo->bindings_snapshot(location));
3534 return label;
3537 // Warn about labels that are defined but not used.
3539 void
3540 Function::check_labels() const
3542 for (Labels::const_iterator p = this->labels_.begin();
3543 p != this->labels_.end();
3544 p++)
3546 Label* label = p->second;
3547 if (!label->is_used())
3548 error_at(label->location(), "label %qs defined and not used",
3549 Gogo::message_name(label->name()).c_str());
3553 // Swap one function with another. This is used when building the
3554 // thunk we use to call a function which calls recover. It may not
3555 // work for any other case.
3557 void
3558 Function::swap_for_recover(Function *x)
3560 go_assert(this->enclosing_ == x->enclosing_);
3561 std::swap(this->results_, x->results_);
3562 std::swap(this->closure_var_, x->closure_var_);
3563 std::swap(this->block_, x->block_);
3564 go_assert(this->location_ == x->location_);
3565 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
3566 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
3569 // Traverse the tree.
3572 Function::traverse(Traverse* traverse)
3574 unsigned int traverse_mask = traverse->traverse_mask();
3576 if ((traverse_mask
3577 & (Traverse::traverse_types | Traverse::traverse_expressions))
3578 != 0)
3580 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
3581 return TRAVERSE_EXIT;
3584 // FIXME: We should check traverse_functions here if nested
3585 // functions are stored in block bindings.
3586 if (this->block_ != NULL
3587 && (traverse_mask
3588 & (Traverse::traverse_variables
3589 | Traverse::traverse_constants
3590 | Traverse::traverse_blocks
3591 | Traverse::traverse_statements
3592 | Traverse::traverse_expressions
3593 | Traverse::traverse_types)) != 0)
3595 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
3596 return TRAVERSE_EXIT;
3599 return TRAVERSE_CONTINUE;
3602 // Work out types for unspecified variables and constants.
3604 void
3605 Function::determine_types()
3607 if (this->block_ != NULL)
3608 this->block_->determine_types();
3611 // Return the function descriptor, the value you get when you refer to
3612 // the function in Go code without calling it.
3614 Expression*
3615 Function::descriptor(Gogo*, Named_object* no)
3617 go_assert(!this->is_method());
3618 go_assert(this->closure_var_ == NULL);
3619 if (this->descriptor_ == NULL)
3620 this->descriptor_ = Expression::make_func_descriptor(no);
3621 return this->descriptor_;
3624 // Get a pointer to the variable representing the defer stack for this
3625 // function, making it if necessary. The value of the variable is set
3626 // by the runtime routines to true if the function is returning,
3627 // rather than panicing through. A pointer to this variable is used
3628 // as a marker for the functions on the defer stack associated with
3629 // this function. A function-specific variable permits inlining a
3630 // function which uses defer.
3632 Expression*
3633 Function::defer_stack(Location location)
3635 if (this->defer_stack_ == NULL)
3637 Type* t = Type::lookup_bool_type();
3638 Expression* n = Expression::make_boolean(false, location);
3639 this->defer_stack_ = Statement::make_temporary(t, n, location);
3640 this->defer_stack_->set_is_address_taken();
3642 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
3643 location);
3644 return Expression::make_unary(OPERATOR_AND, ref, location);
3647 // Export the function.
3649 void
3650 Function::export_func(Export* exp, const std::string& name) const
3652 Function::export_func_with_type(exp, name, this->type_);
3655 // Export a function with a type.
3657 void
3658 Function::export_func_with_type(Export* exp, const std::string& name,
3659 const Function_type* fntype)
3661 exp->write_c_string("func ");
3663 if (fntype->is_method())
3665 exp->write_c_string("(");
3666 const Typed_identifier* receiver = fntype->receiver();
3667 exp->write_name(receiver->name());
3668 exp->write_c_string(" ");
3669 exp->write_type(receiver->type());
3670 exp->write_c_string(") ");
3673 exp->write_string(name);
3675 exp->write_c_string(" (");
3676 const Typed_identifier_list* parameters = fntype->parameters();
3677 if (parameters != NULL)
3679 bool is_varargs = fntype->is_varargs();
3680 bool first = true;
3681 for (Typed_identifier_list::const_iterator p = parameters->begin();
3682 p != parameters->end();
3683 ++p)
3685 if (first)
3686 first = false;
3687 else
3688 exp->write_c_string(", ");
3689 exp->write_name(p->name());
3690 exp->write_c_string(" ");
3691 if (!is_varargs || p + 1 != parameters->end())
3692 exp->write_type(p->type());
3693 else
3695 exp->write_c_string("...");
3696 exp->write_type(p->type()->array_type()->element_type());
3700 exp->write_c_string(")");
3702 const Typed_identifier_list* results = fntype->results();
3703 if (results != NULL)
3705 if (results->size() == 1 && results->begin()->name().empty())
3707 exp->write_c_string(" ");
3708 exp->write_type(results->begin()->type());
3710 else
3712 exp->write_c_string(" (");
3713 bool first = true;
3714 for (Typed_identifier_list::const_iterator p = results->begin();
3715 p != results->end();
3716 ++p)
3718 if (first)
3719 first = false;
3720 else
3721 exp->write_c_string(", ");
3722 exp->write_name(p->name());
3723 exp->write_c_string(" ");
3724 exp->write_type(p->type());
3726 exp->write_c_string(")");
3729 exp->write_c_string(";\n");
3732 // Import a function.
3734 void
3735 Function::import_func(Import* imp, std::string* pname,
3736 Typed_identifier** preceiver,
3737 Typed_identifier_list** pparameters,
3738 Typed_identifier_list** presults,
3739 bool* is_varargs)
3741 imp->require_c_string("func ");
3743 *preceiver = NULL;
3744 if (imp->peek_char() == '(')
3746 imp->require_c_string("(");
3747 std::string name = imp->read_name();
3748 imp->require_c_string(" ");
3749 Type* rtype = imp->read_type();
3750 *preceiver = new Typed_identifier(name, rtype, imp->location());
3751 imp->require_c_string(") ");
3754 *pname = imp->read_identifier();
3756 Typed_identifier_list* parameters;
3757 *is_varargs = false;
3758 imp->require_c_string(" (");
3759 if (imp->peek_char() == ')')
3760 parameters = NULL;
3761 else
3763 parameters = new Typed_identifier_list();
3764 while (true)
3766 std::string name = imp->read_name();
3767 imp->require_c_string(" ");
3769 if (imp->match_c_string("..."))
3771 imp->advance(3);
3772 *is_varargs = true;
3775 Type* ptype = imp->read_type();
3776 if (*is_varargs)
3777 ptype = Type::make_array_type(ptype, NULL);
3778 parameters->push_back(Typed_identifier(name, ptype,
3779 imp->location()));
3780 if (imp->peek_char() != ',')
3781 break;
3782 go_assert(!*is_varargs);
3783 imp->require_c_string(", ");
3786 imp->require_c_string(")");
3787 *pparameters = parameters;
3789 Typed_identifier_list* results;
3790 if (imp->peek_char() != ' ')
3791 results = NULL;
3792 else
3794 results = new Typed_identifier_list();
3795 imp->require_c_string(" ");
3796 if (imp->peek_char() != '(')
3798 Type* rtype = imp->read_type();
3799 results->push_back(Typed_identifier("", rtype, imp->location()));
3801 else
3803 imp->require_c_string("(");
3804 while (true)
3806 std::string name = imp->read_name();
3807 imp->require_c_string(" ");
3808 Type* rtype = imp->read_type();
3809 results->push_back(Typed_identifier(name, rtype,
3810 imp->location()));
3811 if (imp->peek_char() != ',')
3812 break;
3813 imp->require_c_string(", ");
3815 imp->require_c_string(")");
3818 imp->require_c_string(";\n");
3819 *presults = results;
3822 // Class Block.
3824 Block::Block(Block* enclosing, Location location)
3825 : enclosing_(enclosing), statements_(),
3826 bindings_(new Bindings(enclosing == NULL
3827 ? NULL
3828 : enclosing->bindings())),
3829 start_location_(location),
3830 end_location_(UNKNOWN_LOCATION)
3834 // Add a statement to a block.
3836 void
3837 Block::add_statement(Statement* statement)
3839 this->statements_.push_back(statement);
3842 // Add a statement to the front of a block. This is slow but is only
3843 // used for reference counts of parameters.
3845 void
3846 Block::add_statement_at_front(Statement* statement)
3848 this->statements_.insert(this->statements_.begin(), statement);
3851 // Replace a statement in a block.
3853 void
3854 Block::replace_statement(size_t index, Statement* s)
3856 go_assert(index < this->statements_.size());
3857 this->statements_[index] = s;
3860 // Add a statement before another statement.
3862 void
3863 Block::insert_statement_before(size_t index, Statement* s)
3865 go_assert(index < this->statements_.size());
3866 this->statements_.insert(this->statements_.begin() + index, s);
3869 // Add a statement after another statement.
3871 void
3872 Block::insert_statement_after(size_t index, Statement* s)
3874 go_assert(index < this->statements_.size());
3875 this->statements_.insert(this->statements_.begin() + index + 1, s);
3878 // Traverse the tree.
3881 Block::traverse(Traverse* traverse)
3883 unsigned int traverse_mask = traverse->traverse_mask();
3885 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3887 int t = traverse->block(this);
3888 if (t == TRAVERSE_EXIT)
3889 return TRAVERSE_EXIT;
3890 else if (t == TRAVERSE_SKIP_COMPONENTS)
3891 return TRAVERSE_CONTINUE;
3894 if ((traverse_mask
3895 & (Traverse::traverse_variables
3896 | Traverse::traverse_constants
3897 | Traverse::traverse_expressions
3898 | Traverse::traverse_types)) != 0)
3900 const unsigned int e_or_t = (Traverse::traverse_expressions
3901 | Traverse::traverse_types);
3902 const unsigned int e_or_t_or_s = (e_or_t
3903 | Traverse::traverse_statements);
3904 for (Bindings::const_definitions_iterator pb =
3905 this->bindings_->begin_definitions();
3906 pb != this->bindings_->end_definitions();
3907 ++pb)
3909 int t = TRAVERSE_CONTINUE;
3910 switch ((*pb)->classification())
3912 case Named_object::NAMED_OBJECT_CONST:
3913 if ((traverse_mask & Traverse::traverse_constants) != 0)
3914 t = traverse->constant(*pb, false);
3915 if (t == TRAVERSE_CONTINUE
3916 && (traverse_mask & e_or_t) != 0)
3918 Type* tc = (*pb)->const_value()->type();
3919 if (tc != NULL
3920 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
3921 return TRAVERSE_EXIT;
3922 t = (*pb)->const_value()->traverse_expression(traverse);
3924 break;
3926 case Named_object::NAMED_OBJECT_VAR:
3927 case Named_object::NAMED_OBJECT_RESULT_VAR:
3928 if ((traverse_mask & Traverse::traverse_variables) != 0)
3929 t = traverse->variable(*pb);
3930 if (t == TRAVERSE_CONTINUE
3931 && (traverse_mask & e_or_t) != 0)
3933 if ((*pb)->is_result_variable()
3934 || (*pb)->var_value()->has_type())
3936 Type* tv = ((*pb)->is_variable()
3937 ? (*pb)->var_value()->type()
3938 : (*pb)->result_var_value()->type());
3939 if (tv != NULL
3940 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
3941 return TRAVERSE_EXIT;
3944 if (t == TRAVERSE_CONTINUE
3945 && (traverse_mask & e_or_t_or_s) != 0
3946 && (*pb)->is_variable())
3947 t = (*pb)->var_value()->traverse_expression(traverse,
3948 traverse_mask);
3949 break;
3951 case Named_object::NAMED_OBJECT_FUNC:
3952 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3953 go_unreachable();
3955 case Named_object::NAMED_OBJECT_TYPE:
3956 if ((traverse_mask & e_or_t) != 0)
3957 t = Type::traverse((*pb)->type_value(), traverse);
3958 break;
3960 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3961 case Named_object::NAMED_OBJECT_UNKNOWN:
3962 case Named_object::NAMED_OBJECT_ERRONEOUS:
3963 break;
3965 case Named_object::NAMED_OBJECT_PACKAGE:
3966 case Named_object::NAMED_OBJECT_SINK:
3967 go_unreachable();
3969 default:
3970 go_unreachable();
3973 if (t == TRAVERSE_EXIT)
3974 return TRAVERSE_EXIT;
3978 // No point in checking traverse_mask here--if we got here we always
3979 // want to walk the statements. The traversal can insert new
3980 // statements before or after the current statement. Inserting
3981 // statements before the current statement requires updating I via
3982 // the pointer; those statements will not be traversed. Any new
3983 // statements inserted after the current statement will be traversed
3984 // in their turn.
3985 for (size_t i = 0; i < this->statements_.size(); ++i)
3987 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3988 return TRAVERSE_EXIT;
3991 return TRAVERSE_CONTINUE;
3994 // Work out types for unspecified variables and constants.
3996 void
3997 Block::determine_types()
3999 for (Bindings::const_definitions_iterator pb =
4000 this->bindings_->begin_definitions();
4001 pb != this->bindings_->end_definitions();
4002 ++pb)
4004 if ((*pb)->is_variable())
4005 (*pb)->var_value()->determine_type();
4006 else if ((*pb)->is_const())
4007 (*pb)->const_value()->determine_type();
4010 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
4011 ps != this->statements_.end();
4012 ++ps)
4013 (*ps)->determine_types();
4016 // Return true if the statements in this block may fall through.
4018 bool
4019 Block::may_fall_through() const
4021 if (this->statements_.empty())
4022 return true;
4023 return this->statements_.back()->may_fall_through();
4026 // Convert a block to the backend representation.
4028 Bblock*
4029 Block::get_backend(Translate_context* context)
4031 Gogo* gogo = context->gogo();
4032 Named_object* function = context->function();
4033 std::vector<Bvariable*> vars;
4034 vars.reserve(this->bindings_->size_definitions());
4035 for (Bindings::const_definitions_iterator pv =
4036 this->bindings_->begin_definitions();
4037 pv != this->bindings_->end_definitions();
4038 ++pv)
4040 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
4041 vars.push_back((*pv)->get_backend_variable(gogo, function));
4044 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
4045 // until we have a proper representation of the init function.
4046 Bfunction* bfunction;
4047 if (function == NULL)
4048 bfunction = NULL;
4049 else
4050 bfunction = tree_to_function(function->func_value()->get_decl());
4051 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
4052 vars, this->start_location_,
4053 this->end_location_);
4055 Translate_context subcontext(gogo, function, this, ret);
4056 std::vector<Bstatement*> bstatements;
4057 bstatements.reserve(this->statements_.size());
4058 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
4059 p != this->statements_.end();
4060 ++p)
4061 bstatements.push_back((*p)->get_backend(&subcontext));
4063 context->backend()->block_add_statements(ret, bstatements);
4065 return ret;
4068 // Class Bindings_snapshot.
4070 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
4071 : block_(b), counts_(), location_(location)
4073 while (b != NULL)
4075 this->counts_.push_back(b->bindings()->size_definitions());
4076 b = b->enclosing();
4080 // Report errors appropriate for a goto from B to this.
4082 void
4083 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
4085 size_t dummy;
4086 if (!this->check_goto_block(loc, b, this->block_, &dummy))
4087 return;
4088 this->check_goto_defs(loc, this->block_,
4089 this->block_->bindings()->size_definitions(),
4090 this->counts_[0]);
4093 // Report errors appropriate for a goto from this to B.
4095 void
4096 Bindings_snapshot::check_goto_to(const Block* b)
4098 size_t index;
4099 if (!this->check_goto_block(this->location_, this->block_, b, &index))
4100 return;
4101 this->check_goto_defs(this->location_, b, this->counts_[index],
4102 b->bindings()->size_definitions());
4105 // Report errors appropriate for a goto at LOC from BFROM to BTO.
4106 // Return true if all is well, false if we reported an error. If this
4107 // returns true, it sets *PINDEX to the number of blocks BTO is above
4108 // BFROM.
4110 bool
4111 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
4112 const Block* bto, size_t* pindex)
4114 // It is an error if BTO is not either BFROM or above BFROM.
4115 size_t index = 0;
4116 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
4118 if (pb == NULL)
4120 error_at(loc, "goto jumps into block");
4121 inform(bto->start_location(), "goto target block starts here");
4122 return false;
4125 *pindex = index;
4126 return true;
4129 // Report errors appropriate for a goto at LOC ending at BLOCK, where
4130 // CFROM is the number of names defined at the point of the goto and
4131 // CTO is the number of names defined at the point of the label.
4133 void
4134 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
4135 size_t cfrom, size_t cto)
4137 if (cfrom < cto)
4139 Bindings::const_definitions_iterator p =
4140 block->bindings()->begin_definitions();
4141 for (size_t i = 0; i < cfrom; ++i)
4143 go_assert(p != block->bindings()->end_definitions());
4144 ++p;
4146 go_assert(p != block->bindings()->end_definitions());
4148 std::string n = (*p)->message_name();
4149 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
4150 inform((*p)->location(), "%qs defined here", n.c_str());
4154 // Class Function_declaration.
4156 // Return the function descriptor.
4158 Expression*
4159 Function_declaration::descriptor(Gogo*, Named_object* no)
4161 go_assert(!this->fntype_->is_method());
4162 if (this->descriptor_ == NULL)
4163 this->descriptor_ = Expression::make_func_descriptor(no);
4164 return this->descriptor_;
4167 // Class Variable.
4169 Variable::Variable(Type* type, Expression* init, bool is_global,
4170 bool is_parameter, bool is_receiver,
4171 Location location)
4172 : type_(type), init_(init), preinit_(NULL), location_(location),
4173 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
4174 is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
4175 is_address_taken_(false), is_non_escaping_address_taken_(false),
4176 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
4177 type_from_range_index_(false), type_from_range_value_(false),
4178 type_from_chan_element_(false), is_type_switch_var_(false),
4179 determined_type_(false), in_unique_section_(false)
4181 go_assert(type != NULL || init != NULL);
4182 go_assert(!is_parameter || init == NULL);
4185 // Traverse the initializer expression.
4188 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
4190 if (this->preinit_ != NULL)
4192 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
4193 return TRAVERSE_EXIT;
4195 if (this->init_ != NULL
4196 && ((traverse_mask
4197 & (Traverse::traverse_expressions | Traverse::traverse_types))
4198 != 0))
4200 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
4201 return TRAVERSE_EXIT;
4203 return TRAVERSE_CONTINUE;
4206 // Lower the initialization expression after parsing is complete.
4208 void
4209 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
4210 Statement_inserter* inserter)
4212 Named_object* dep = gogo->var_depends_on(this);
4213 if (dep != NULL && dep->is_variable())
4214 dep->var_value()->lower_init_expression(gogo, function, inserter);
4216 if (this->init_ != NULL && !this->init_is_lowered_)
4218 if (this->seen_)
4220 // We will give an error elsewhere, this is just to prevent
4221 // an infinite loop.
4222 return;
4224 this->seen_ = true;
4226 Statement_inserter global_inserter;
4227 if (this->is_global_)
4229 global_inserter = Statement_inserter(gogo, this);
4230 inserter = &global_inserter;
4233 gogo->lower_expression(function, inserter, &this->init_);
4235 this->seen_ = false;
4237 this->init_is_lowered_ = true;
4241 // Get the preinit block.
4243 Block*
4244 Variable::preinit_block(Gogo* gogo)
4246 go_assert(this->is_global_);
4247 if (this->preinit_ == NULL)
4248 this->preinit_ = new Block(NULL, this->location());
4250 // If a global variable has a preinitialization statement, then we
4251 // need to have an initialization function.
4252 gogo->set_need_init_fn();
4254 return this->preinit_;
4257 // Add a statement to be run before the initialization expression.
4259 void
4260 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
4262 Block* b = this->preinit_block(gogo);
4263 b->add_statement(s);
4264 b->set_end_location(s->location());
4267 // Whether this variable has a type.
4269 bool
4270 Variable::has_type() const
4272 if (this->type_ == NULL)
4273 return false;
4275 // A variable created in a type switch case nil does not actually
4276 // have a type yet. It will be changed to use the initializer's
4277 // type in determine_type.
4278 if (this->is_type_switch_var_
4279 && this->type_->is_nil_constant_as_type())
4280 return false;
4282 return true;
4285 // In an assignment which sets a variable to a tuple of EXPR, return
4286 // the type of the first element of the tuple.
4288 Type*
4289 Variable::type_from_tuple(Expression* expr, bool report_error) const
4291 if (expr->map_index_expression() != NULL)
4293 Map_type* mt = expr->map_index_expression()->get_map_type();
4294 if (mt == NULL)
4295 return Type::make_error_type();
4296 return mt->val_type();
4298 else if (expr->receive_expression() != NULL)
4300 Expression* channel = expr->receive_expression()->channel();
4301 Type* channel_type = channel->type();
4302 if (channel_type->channel_type() == NULL)
4303 return Type::make_error_type();
4304 return channel_type->channel_type()->element_type();
4306 else
4308 if (report_error)
4309 error_at(this->location(), "invalid tuple definition");
4310 return Type::make_error_type();
4314 // Given EXPR used in a range clause, return either the index type or
4315 // the value type of the range, depending upon GET_INDEX_TYPE.
4317 Type*
4318 Variable::type_from_range(Expression* expr, bool get_index_type,
4319 bool report_error) const
4321 Type* t = expr->type();
4322 if (t->array_type() != NULL
4323 || (t->points_to() != NULL
4324 && t->points_to()->array_type() != NULL
4325 && !t->points_to()->is_slice_type()))
4327 if (get_index_type)
4328 return Type::lookup_integer_type("int");
4329 else
4330 return t->deref()->array_type()->element_type();
4332 else if (t->is_string_type())
4334 if (get_index_type)
4335 return Type::lookup_integer_type("int");
4336 else
4337 return Type::lookup_integer_type("int32");
4339 else if (t->map_type() != NULL)
4341 if (get_index_type)
4342 return t->map_type()->key_type();
4343 else
4344 return t->map_type()->val_type();
4346 else if (t->channel_type() != NULL)
4348 if (get_index_type)
4349 return t->channel_type()->element_type();
4350 else
4352 if (report_error)
4353 error_at(this->location(),
4354 "invalid definition of value variable for channel range");
4355 return Type::make_error_type();
4358 else
4360 if (report_error)
4361 error_at(this->location(), "invalid type for range clause");
4362 return Type::make_error_type();
4366 // EXPR should be a channel. Return the channel's element type.
4368 Type*
4369 Variable::type_from_chan_element(Expression* expr, bool report_error) const
4371 Type* t = expr->type();
4372 if (t->channel_type() != NULL)
4373 return t->channel_type()->element_type();
4374 else
4376 if (report_error)
4377 error_at(this->location(), "expected channel");
4378 return Type::make_error_type();
4382 // Return the type of the Variable. This may be called before
4383 // Variable::determine_type is called, which means that we may need to
4384 // get the type from the initializer. FIXME: If we combine lowering
4385 // with type determination, then this should be unnecessary.
4387 Type*
4388 Variable::type()
4390 // A variable in a type switch with a nil case will have the wrong
4391 // type here. This gets fixed up in determine_type, below.
4392 Type* type = this->type_;
4393 Expression* init = this->init_;
4394 if (this->is_type_switch_var_
4395 && this->type_->is_nil_constant_as_type())
4397 Type_guard_expression* tge = this->init_->type_guard_expression();
4398 go_assert(tge != NULL);
4399 init = tge->expr();
4400 type = NULL;
4403 if (this->seen_)
4405 if (this->type_ == NULL || !this->type_->is_error_type())
4407 error_at(this->location_, "variable initializer refers to itself");
4408 this->type_ = Type::make_error_type();
4410 return this->type_;
4413 this->seen_ = true;
4415 if (type != NULL)
4417 else if (this->type_from_init_tuple_)
4418 type = this->type_from_tuple(init, false);
4419 else if (this->type_from_range_index_ || this->type_from_range_value_)
4420 type = this->type_from_range(init, this->type_from_range_index_, false);
4421 else if (this->type_from_chan_element_)
4422 type = this->type_from_chan_element(init, false);
4423 else
4425 go_assert(init != NULL);
4426 type = init->type();
4427 go_assert(type != NULL);
4429 // Variables should not have abstract types.
4430 if (type->is_abstract())
4431 type = type->make_non_abstract_type();
4433 if (type->is_void_type())
4434 type = Type::make_error_type();
4437 this->seen_ = false;
4439 return type;
4442 // Fetch the type from a const pointer, in which case it should have
4443 // been set already.
4445 Type*
4446 Variable::type() const
4448 go_assert(this->type_ != NULL);
4449 return this->type_;
4452 // Set the type if necessary.
4454 void
4455 Variable::determine_type()
4457 if (this->determined_type_)
4458 return;
4459 this->determined_type_ = true;
4461 if (this->preinit_ != NULL)
4462 this->preinit_->determine_types();
4464 // A variable in a type switch with a nil case will have the wrong
4465 // type here. It will have an initializer which is a type guard.
4466 // We want to initialize it to the value without the type guard, and
4467 // use the type of that value as well.
4468 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
4470 Type_guard_expression* tge = this->init_->type_guard_expression();
4471 go_assert(tge != NULL);
4472 this->type_ = NULL;
4473 this->init_ = tge->expr();
4476 if (this->init_ == NULL)
4477 go_assert(this->type_ != NULL && !this->type_->is_abstract());
4478 else if (this->type_from_init_tuple_)
4480 Expression *init = this->init_;
4481 init->determine_type_no_context();
4482 this->type_ = this->type_from_tuple(init, true);
4483 this->init_ = NULL;
4485 else if (this->type_from_range_index_ || this->type_from_range_value_)
4487 Expression* init = this->init_;
4488 init->determine_type_no_context();
4489 this->type_ = this->type_from_range(init, this->type_from_range_index_,
4490 true);
4491 this->init_ = NULL;
4493 else if (this->type_from_chan_element_)
4495 Expression* init = this->init_;
4496 init->determine_type_no_context();
4497 this->type_ = this->type_from_chan_element(init, true);
4498 this->init_ = NULL;
4500 else
4502 Type_context context(this->type_, false);
4503 this->init_->determine_type(&context);
4504 if (this->type_ == NULL)
4506 Type* type = this->init_->type();
4507 go_assert(type != NULL);
4508 if (type->is_abstract())
4509 type = type->make_non_abstract_type();
4511 if (type->is_void_type())
4513 error_at(this->location_, "variable has no type");
4514 type = Type::make_error_type();
4516 else if (type->is_nil_type())
4518 error_at(this->location_, "variable defined to nil type");
4519 type = Type::make_error_type();
4521 else if (type->is_call_multiple_result_type())
4523 error_at(this->location_,
4524 "single variable set to multiple-value function call");
4525 type = Type::make_error_type();
4528 this->type_ = type;
4533 // Export the variable
4535 void
4536 Variable::export_var(Export* exp, const std::string& name) const
4538 go_assert(this->is_global_);
4539 exp->write_c_string("var ");
4540 exp->write_string(name);
4541 exp->write_c_string(" ");
4542 exp->write_type(this->type());
4543 exp->write_c_string(";\n");
4546 // Import a variable.
4548 void
4549 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
4551 imp->require_c_string("var ");
4552 *pname = imp->read_identifier();
4553 imp->require_c_string(" ");
4554 *ptype = imp->read_type();
4555 imp->require_c_string(";\n");
4558 // Convert a variable to the backend representation.
4560 Bvariable*
4561 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
4562 const Package* package, const std::string& name)
4564 if (this->backend_ == NULL)
4566 Backend* backend = gogo->backend();
4567 Type* type = this->type_;
4568 if (type->is_error_type()
4569 || (type->is_undefined()
4570 && (!this->is_global_ || package == NULL)))
4571 this->backend_ = backend->error_variable();
4572 else
4574 bool is_parameter = this->is_parameter_;
4575 if (this->is_receiver_ && type->points_to() == NULL)
4576 is_parameter = false;
4577 if (this->is_in_heap())
4579 is_parameter = false;
4580 type = Type::make_pointer_type(type);
4583 std::string n = Gogo::unpack_hidden_name(name);
4584 Btype* btype = type->get_backend(gogo);
4586 Bvariable* bvar;
4587 if (this->is_global_)
4588 bvar = backend->global_variable((package == NULL
4589 ? gogo->package_name()
4590 : package->package_name()),
4591 (package == NULL
4592 ? gogo->pkgpath_symbol()
4593 : package->pkgpath_symbol()),
4595 btype,
4596 package != NULL,
4597 Gogo::is_hidden_name(name),
4598 this->in_unique_section_,
4599 this->location_);
4600 else if (function == NULL)
4602 go_assert(saw_errors());
4603 bvar = backend->error_variable();
4605 else
4607 tree fndecl = function->func_value()->get_decl();
4608 Bfunction* bfunction = tree_to_function(fndecl);
4609 bool is_address_taken = (this->is_non_escaping_address_taken_
4610 && !this->is_in_heap());
4611 if (is_parameter)
4612 bvar = backend->parameter_variable(bfunction, n, btype,
4613 is_address_taken,
4614 this->location_);
4615 else
4616 bvar = backend->local_variable(bfunction, n, btype,
4617 is_address_taken,
4618 this->location_);
4620 this->backend_ = bvar;
4623 return this->backend_;
4626 // Class Result_variable.
4628 // Convert a result variable to the backend representation.
4630 Bvariable*
4631 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
4632 const std::string& name)
4634 if (this->backend_ == NULL)
4636 Backend* backend = gogo->backend();
4637 Type* type = this->type_;
4638 if (type->is_error())
4639 this->backend_ = backend->error_variable();
4640 else
4642 if (this->is_in_heap())
4643 type = Type::make_pointer_type(type);
4644 Btype* btype = type->get_backend(gogo);
4645 tree fndecl = function->func_value()->get_decl();
4646 Bfunction* bfunction = tree_to_function(fndecl);
4647 std::string n = Gogo::unpack_hidden_name(name);
4648 bool is_address_taken = (this->is_non_escaping_address_taken_
4649 && !this->is_in_heap());
4650 this->backend_ = backend->local_variable(bfunction, n, btype,
4651 is_address_taken,
4652 this->location_);
4655 return this->backend_;
4658 // Class Named_constant.
4660 // Traverse the initializer expression.
4663 Named_constant::traverse_expression(Traverse* traverse)
4665 return Expression::traverse(&this->expr_, traverse);
4668 // Determine the type of the constant.
4670 void
4671 Named_constant::determine_type()
4673 if (this->type_ != NULL)
4675 Type_context context(this->type_, false);
4676 this->expr_->determine_type(&context);
4678 else
4680 // A constant may have an abstract type.
4681 Type_context context(NULL, true);
4682 this->expr_->determine_type(&context);
4683 this->type_ = this->expr_->type();
4684 go_assert(this->type_ != NULL);
4688 // Indicate that we found and reported an error for this constant.
4690 void
4691 Named_constant::set_error()
4693 this->type_ = Type::make_error_type();
4694 this->expr_ = Expression::make_error(this->location_);
4697 // Export a constant.
4699 void
4700 Named_constant::export_const(Export* exp, const std::string& name) const
4702 exp->write_c_string("const ");
4703 exp->write_string(name);
4704 exp->write_c_string(" ");
4705 if (!this->type_->is_abstract())
4707 exp->write_type(this->type_);
4708 exp->write_c_string(" ");
4710 exp->write_c_string("= ");
4711 this->expr()->export_expression(exp);
4712 exp->write_c_string(";\n");
4715 // Import a constant.
4717 void
4718 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
4719 Expression** pexpr)
4721 imp->require_c_string("const ");
4722 *pname = imp->read_identifier();
4723 imp->require_c_string(" ");
4724 if (imp->peek_char() == '=')
4725 *ptype = NULL;
4726 else
4728 *ptype = imp->read_type();
4729 imp->require_c_string(" ");
4731 imp->require_c_string("= ");
4732 *pexpr = Expression::import_expression(imp);
4733 imp->require_c_string(";\n");
4736 // Add a method.
4738 Named_object*
4739 Type_declaration::add_method(const std::string& name, Function* function)
4741 Named_object* ret = Named_object::make_function(name, NULL, function);
4742 this->methods_.push_back(ret);
4743 return ret;
4746 // Add a method declaration.
4748 Named_object*
4749 Type_declaration::add_method_declaration(const std::string& name,
4750 Package* package,
4751 Function_type* type,
4752 Location location)
4754 Named_object* ret = Named_object::make_function_declaration(name, package,
4755 type, location);
4756 this->methods_.push_back(ret);
4757 return ret;
4760 // Return whether any methods ere defined.
4762 bool
4763 Type_declaration::has_methods() const
4765 return !this->methods_.empty();
4768 // Define methods for the real type.
4770 void
4771 Type_declaration::define_methods(Named_type* nt)
4773 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
4774 p != this->methods_.end();
4775 ++p)
4776 nt->add_existing_method(*p);
4779 // We are using the type. Return true if we should issue a warning.
4781 bool
4782 Type_declaration::using_type()
4784 bool ret = !this->issued_warning_;
4785 this->issued_warning_ = true;
4786 return ret;
4789 // Class Unknown_name.
4791 // Set the real named object.
4793 void
4794 Unknown_name::set_real_named_object(Named_object* no)
4796 go_assert(this->real_named_object_ == NULL);
4797 go_assert(!no->is_unknown());
4798 this->real_named_object_ = no;
4801 // Class Named_object.
4803 Named_object::Named_object(const std::string& name,
4804 const Package* package,
4805 Classification classification)
4806 : name_(name), package_(package), classification_(classification),
4807 tree_(NULL)
4809 if (Gogo::is_sink_name(name))
4810 go_assert(classification == NAMED_OBJECT_SINK);
4813 // Make an unknown name. This is used by the parser. The name must
4814 // be resolved later. Unknown names are only added in the current
4815 // package.
4817 Named_object*
4818 Named_object::make_unknown_name(const std::string& name,
4819 Location location)
4821 Named_object* named_object = new Named_object(name, NULL,
4822 NAMED_OBJECT_UNKNOWN);
4823 Unknown_name* value = new Unknown_name(location);
4824 named_object->u_.unknown_value = value;
4825 return named_object;
4828 // Make a constant.
4830 Named_object*
4831 Named_object::make_constant(const Typed_identifier& tid,
4832 const Package* package, Expression* expr,
4833 int iota_value)
4835 Named_object* named_object = new Named_object(tid.name(), package,
4836 NAMED_OBJECT_CONST);
4837 Named_constant* named_constant = new Named_constant(tid.type(), expr,
4838 iota_value,
4839 tid.location());
4840 named_object->u_.const_value = named_constant;
4841 return named_object;
4844 // Make a named type.
4846 Named_object*
4847 Named_object::make_type(const std::string& name, const Package* package,
4848 Type* type, Location location)
4850 Named_object* named_object = new Named_object(name, package,
4851 NAMED_OBJECT_TYPE);
4852 Named_type* named_type = Type::make_named_type(named_object, type, location);
4853 named_object->u_.type_value = named_type;
4854 return named_object;
4857 // Make a type declaration.
4859 Named_object*
4860 Named_object::make_type_declaration(const std::string& name,
4861 const Package* package,
4862 Location location)
4864 Named_object* named_object = new Named_object(name, package,
4865 NAMED_OBJECT_TYPE_DECLARATION);
4866 Type_declaration* type_declaration = new Type_declaration(location);
4867 named_object->u_.type_declaration = type_declaration;
4868 return named_object;
4871 // Make a variable.
4873 Named_object*
4874 Named_object::make_variable(const std::string& name, const Package* package,
4875 Variable* variable)
4877 Named_object* named_object = new Named_object(name, package,
4878 NAMED_OBJECT_VAR);
4879 named_object->u_.var_value = variable;
4880 return named_object;
4883 // Make a result variable.
4885 Named_object*
4886 Named_object::make_result_variable(const std::string& name,
4887 Result_variable* result)
4889 Named_object* named_object = new Named_object(name, NULL,
4890 NAMED_OBJECT_RESULT_VAR);
4891 named_object->u_.result_var_value = result;
4892 return named_object;
4895 // Make a sink. This is used for the special blank identifier _.
4897 Named_object*
4898 Named_object::make_sink()
4900 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4903 // Make a named function.
4905 Named_object*
4906 Named_object::make_function(const std::string& name, const Package* package,
4907 Function* function)
4909 Named_object* named_object = new Named_object(name, package,
4910 NAMED_OBJECT_FUNC);
4911 named_object->u_.func_value = function;
4912 return named_object;
4915 // Make a function declaration.
4917 Named_object*
4918 Named_object::make_function_declaration(const std::string& name,
4919 const Package* package,
4920 Function_type* fntype,
4921 Location location)
4923 Named_object* named_object = new Named_object(name, package,
4924 NAMED_OBJECT_FUNC_DECLARATION);
4925 Function_declaration *func_decl = new Function_declaration(fntype, location);
4926 named_object->u_.func_declaration_value = func_decl;
4927 return named_object;
4930 // Make a package.
4932 Named_object*
4933 Named_object::make_package(const std::string& alias, Package* package)
4935 Named_object* named_object = new Named_object(alias, NULL,
4936 NAMED_OBJECT_PACKAGE);
4937 named_object->u_.package_value = package;
4938 return named_object;
4941 // Return the name to use in an error message.
4943 std::string
4944 Named_object::message_name() const
4946 if (this->package_ == NULL)
4947 return Gogo::message_name(this->name_);
4948 std::string ret;
4949 if (this->package_->has_package_name())
4950 ret = this->package_->package_name();
4951 else
4952 ret = this->package_->pkgpath();
4953 ret = Gogo::message_name(ret);
4954 ret += '.';
4955 ret += Gogo::message_name(this->name_);
4956 return ret;
4959 // Set the type when a declaration is defined.
4961 void
4962 Named_object::set_type_value(Named_type* named_type)
4964 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4965 Type_declaration* td = this->u_.type_declaration;
4966 td->define_methods(named_type);
4967 unsigned int index;
4968 Named_object* in_function = td->in_function(&index);
4969 if (in_function != NULL)
4970 named_type->set_in_function(in_function, index);
4971 delete td;
4972 this->classification_ = NAMED_OBJECT_TYPE;
4973 this->u_.type_value = named_type;
4976 // Define a function which was previously declared.
4978 void
4979 Named_object::set_function_value(Function* function)
4981 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4982 if (this->func_declaration_value()->has_descriptor())
4984 Expression* descriptor =
4985 this->func_declaration_value()->descriptor(NULL, NULL);
4986 function->set_descriptor(descriptor);
4988 this->classification_ = NAMED_OBJECT_FUNC;
4989 // FIXME: We should free the old value.
4990 this->u_.func_value = function;
4993 // Declare an unknown object as a type declaration.
4995 void
4996 Named_object::declare_as_type()
4998 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4999 Unknown_name* unk = this->u_.unknown_value;
5000 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
5001 this->u_.type_declaration = new Type_declaration(unk->location());
5002 delete unk;
5005 // Return the location of a named object.
5007 Location
5008 Named_object::location() const
5010 switch (this->classification_)
5012 default:
5013 case NAMED_OBJECT_UNINITIALIZED:
5014 go_unreachable();
5016 case NAMED_OBJECT_ERRONEOUS:
5017 return Linemap::unknown_location();
5019 case NAMED_OBJECT_UNKNOWN:
5020 return this->unknown_value()->location();
5022 case NAMED_OBJECT_CONST:
5023 return this->const_value()->location();
5025 case NAMED_OBJECT_TYPE:
5026 return this->type_value()->location();
5028 case NAMED_OBJECT_TYPE_DECLARATION:
5029 return this->type_declaration_value()->location();
5031 case NAMED_OBJECT_VAR:
5032 return this->var_value()->location();
5034 case NAMED_OBJECT_RESULT_VAR:
5035 return this->result_var_value()->location();
5037 case NAMED_OBJECT_SINK:
5038 go_unreachable();
5040 case NAMED_OBJECT_FUNC:
5041 return this->func_value()->location();
5043 case NAMED_OBJECT_FUNC_DECLARATION:
5044 return this->func_declaration_value()->location();
5046 case NAMED_OBJECT_PACKAGE:
5047 return this->package_value()->location();
5051 // Export a named object.
5053 void
5054 Named_object::export_named_object(Export* exp) const
5056 switch (this->classification_)
5058 default:
5059 case NAMED_OBJECT_UNINITIALIZED:
5060 case NAMED_OBJECT_UNKNOWN:
5061 go_unreachable();
5063 case NAMED_OBJECT_ERRONEOUS:
5064 break;
5066 case NAMED_OBJECT_CONST:
5067 this->const_value()->export_const(exp, this->name_);
5068 break;
5070 case NAMED_OBJECT_TYPE:
5071 this->type_value()->export_named_type(exp, this->name_);
5072 break;
5074 case NAMED_OBJECT_TYPE_DECLARATION:
5075 error_at(this->type_declaration_value()->location(),
5076 "attempt to export %<%s%> which was declared but not defined",
5077 this->message_name().c_str());
5078 break;
5080 case NAMED_OBJECT_FUNC_DECLARATION:
5081 this->func_declaration_value()->export_func(exp, this->name_);
5082 break;
5084 case NAMED_OBJECT_VAR:
5085 this->var_value()->export_var(exp, this->name_);
5086 break;
5088 case NAMED_OBJECT_RESULT_VAR:
5089 case NAMED_OBJECT_SINK:
5090 go_unreachable();
5092 case NAMED_OBJECT_FUNC:
5093 this->func_value()->export_func(exp, this->name_);
5094 break;
5098 // Convert a variable to the backend representation.
5100 Bvariable*
5101 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
5103 if (this->classification_ == NAMED_OBJECT_VAR)
5104 return this->var_value()->get_backend_variable(gogo, function,
5105 this->package_, this->name_);
5106 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
5107 return this->result_var_value()->get_backend_variable(gogo, function,
5108 this->name_);
5109 else
5110 go_unreachable();
5113 // Class Bindings.
5115 Bindings::Bindings(Bindings* enclosing)
5116 : enclosing_(enclosing), named_objects_(), bindings_()
5120 // Clear imports.
5122 void
5123 Bindings::clear_file_scope(Gogo* gogo)
5125 Contour::iterator p = this->bindings_.begin();
5126 while (p != this->bindings_.end())
5128 bool keep;
5129 if (p->second->package() != NULL)
5130 keep = false;
5131 else if (p->second->is_package())
5132 keep = false;
5133 else if (p->second->is_function()
5134 && !p->second->func_value()->type()->is_method()
5135 && Gogo::unpack_hidden_name(p->second->name()) == "init")
5136 keep = false;
5137 else
5138 keep = true;
5140 if (keep)
5141 ++p;
5142 else
5144 gogo->add_file_block_name(p->second->name(), p->second->location());
5145 p = this->bindings_.erase(p);
5150 // Look up a symbol.
5152 Named_object*
5153 Bindings::lookup(const std::string& name) const
5155 Contour::const_iterator p = this->bindings_.find(name);
5156 if (p != this->bindings_.end())
5157 return p->second->resolve();
5158 else if (this->enclosing_ != NULL)
5159 return this->enclosing_->lookup(name);
5160 else
5161 return NULL;
5164 // Look up a symbol locally.
5166 Named_object*
5167 Bindings::lookup_local(const std::string& name) const
5169 Contour::const_iterator p = this->bindings_.find(name);
5170 if (p == this->bindings_.end())
5171 return NULL;
5172 return p->second;
5175 // Remove an object from a set of bindings. This is used for a
5176 // special case in thunks for functions which call recover.
5178 void
5179 Bindings::remove_binding(Named_object* no)
5181 Contour::iterator pb = this->bindings_.find(no->name());
5182 go_assert(pb != this->bindings_.end());
5183 this->bindings_.erase(pb);
5184 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
5185 pn != this->named_objects_.end();
5186 ++pn)
5188 if (*pn == no)
5190 this->named_objects_.erase(pn);
5191 return;
5194 go_unreachable();
5197 // Add a method to the list of objects. This is not added to the
5198 // lookup table. This is so that we have a single list of objects
5199 // declared at the top level, which we walk through when it's time to
5200 // convert to trees.
5202 void
5203 Bindings::add_method(Named_object* method)
5205 this->named_objects_.push_back(method);
5208 // Add a generic Named_object to a Contour.
5210 Named_object*
5211 Bindings::add_named_object_to_contour(Contour* contour,
5212 Named_object* named_object)
5214 go_assert(named_object == named_object->resolve());
5215 const std::string& name(named_object->name());
5216 go_assert(!Gogo::is_sink_name(name));
5218 std::pair<Contour::iterator, bool> ins =
5219 contour->insert(std::make_pair(name, named_object));
5220 if (!ins.second)
5222 // The name was already there.
5223 if (named_object->package() != NULL
5224 && ins.first->second->package() == named_object->package()
5225 && (ins.first->second->classification()
5226 == named_object->classification()))
5228 // This is a second import of the same object.
5229 return ins.first->second;
5231 ins.first->second = this->new_definition(ins.first->second,
5232 named_object);
5233 return ins.first->second;
5235 else
5237 // Don't push declarations on the list. We push them on when
5238 // and if we find the definitions. That way we genericize the
5239 // functions in order.
5240 if (!named_object->is_type_declaration()
5241 && !named_object->is_function_declaration()
5242 && !named_object->is_unknown())
5243 this->named_objects_.push_back(named_object);
5244 return named_object;
5248 // We had an existing named object OLD_OBJECT, and we've seen a new
5249 // one NEW_OBJECT with the same name. FIXME: This does not free the
5250 // new object when we don't need it.
5252 Named_object*
5253 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
5255 if (new_object->is_erroneous() && !old_object->is_erroneous())
5256 return new_object;
5258 std::string reason;
5259 switch (old_object->classification())
5261 default:
5262 case Named_object::NAMED_OBJECT_UNINITIALIZED:
5263 go_unreachable();
5265 case Named_object::NAMED_OBJECT_ERRONEOUS:
5266 return old_object;
5268 case Named_object::NAMED_OBJECT_UNKNOWN:
5270 Named_object* real = old_object->unknown_value()->real_named_object();
5271 if (real != NULL)
5272 return this->new_definition(real, new_object);
5273 go_assert(!new_object->is_unknown());
5274 old_object->unknown_value()->set_real_named_object(new_object);
5275 if (!new_object->is_type_declaration()
5276 && !new_object->is_function_declaration())
5277 this->named_objects_.push_back(new_object);
5278 return new_object;
5281 case Named_object::NAMED_OBJECT_CONST:
5282 break;
5284 case Named_object::NAMED_OBJECT_TYPE:
5285 if (new_object->is_type_declaration())
5286 return old_object;
5287 break;
5289 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5290 if (new_object->is_type_declaration())
5291 return old_object;
5292 if (new_object->is_type())
5294 old_object->set_type_value(new_object->type_value());
5295 new_object->type_value()->set_named_object(old_object);
5296 this->named_objects_.push_back(old_object);
5297 return old_object;
5299 break;
5301 case Named_object::NAMED_OBJECT_VAR:
5302 case Named_object::NAMED_OBJECT_RESULT_VAR:
5303 // We have already given an error in the parser for cases where
5304 // one parameter or result variable redeclares another one.
5305 if ((new_object->is_variable()
5306 && new_object->var_value()->is_parameter())
5307 || new_object->is_result_variable())
5308 return old_object;
5309 break;
5311 case Named_object::NAMED_OBJECT_SINK:
5312 go_unreachable();
5314 case Named_object::NAMED_OBJECT_FUNC:
5315 if (new_object->is_function_declaration())
5317 if (!new_object->func_declaration_value()->asm_name().empty())
5318 sorry("__asm__ for function definitions");
5319 Function_type* old_type = old_object->func_value()->type();
5320 Function_type* new_type =
5321 new_object->func_declaration_value()->type();
5322 if (old_type->is_valid_redeclaration(new_type, &reason))
5323 return old_object;
5325 break;
5327 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5329 Function_type* old_type = old_object->func_declaration_value()->type();
5330 if (new_object->is_function_declaration())
5332 Function_type* new_type =
5333 new_object->func_declaration_value()->type();
5334 if (old_type->is_valid_redeclaration(new_type, &reason))
5335 return old_object;
5337 if (new_object->is_function())
5339 Function_type* new_type = new_object->func_value()->type();
5340 if (old_type->is_valid_redeclaration(new_type, &reason))
5342 if (!old_object->func_declaration_value()->asm_name().empty())
5343 sorry("__asm__ for function definitions");
5344 old_object->set_function_value(new_object->func_value());
5345 this->named_objects_.push_back(old_object);
5346 return old_object;
5350 break;
5352 case Named_object::NAMED_OBJECT_PACKAGE:
5353 break;
5356 std::string n = old_object->message_name();
5357 if (reason.empty())
5358 error_at(new_object->location(), "redefinition of %qs", n.c_str());
5359 else
5360 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
5361 reason.c_str());
5363 inform(old_object->location(), "previous definition of %qs was here",
5364 n.c_str());
5366 return old_object;
5369 // Add a named type.
5371 Named_object*
5372 Bindings::add_named_type(Named_type* named_type)
5374 return this->add_named_object(named_type->named_object());
5377 // Add a function.
5379 Named_object*
5380 Bindings::add_function(const std::string& name, const Package* package,
5381 Function* function)
5383 return this->add_named_object(Named_object::make_function(name, package,
5384 function));
5387 // Add a function declaration.
5389 Named_object*
5390 Bindings::add_function_declaration(const std::string& name,
5391 const Package* package,
5392 Function_type* type,
5393 Location location)
5395 Named_object* no = Named_object::make_function_declaration(name, package,
5396 type, location);
5397 return this->add_named_object(no);
5400 // Define a type which was previously declared.
5402 void
5403 Bindings::define_type(Named_object* no, Named_type* type)
5405 no->set_type_value(type);
5406 this->named_objects_.push_back(no);
5409 // Mark all local variables as used. This is used for some types of
5410 // parse error.
5412 void
5413 Bindings::mark_locals_used()
5415 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
5416 p != this->named_objects_.end();
5417 ++p)
5418 if ((*p)->is_variable())
5419 (*p)->var_value()->set_is_used();
5422 // Traverse bindings.
5425 Bindings::traverse(Traverse* traverse, bool is_global)
5427 unsigned int traverse_mask = traverse->traverse_mask();
5429 // We don't use an iterator because we permit the traversal to add
5430 // new global objects.
5431 const unsigned int e_or_t = (Traverse::traverse_expressions
5432 | Traverse::traverse_types);
5433 const unsigned int e_or_t_or_s = (e_or_t
5434 | Traverse::traverse_statements);
5435 for (size_t i = 0; i < this->named_objects_.size(); ++i)
5437 Named_object* p = this->named_objects_[i];
5438 int t = TRAVERSE_CONTINUE;
5439 switch (p->classification())
5441 case Named_object::NAMED_OBJECT_CONST:
5442 if ((traverse_mask & Traverse::traverse_constants) != 0)
5443 t = traverse->constant(p, is_global);
5444 if (t == TRAVERSE_CONTINUE
5445 && (traverse_mask & e_or_t) != 0)
5447 Type* tc = p->const_value()->type();
5448 if (tc != NULL
5449 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5450 return TRAVERSE_EXIT;
5451 t = p->const_value()->traverse_expression(traverse);
5453 break;
5455 case Named_object::NAMED_OBJECT_VAR:
5456 case Named_object::NAMED_OBJECT_RESULT_VAR:
5457 if ((traverse_mask & Traverse::traverse_variables) != 0)
5458 t = traverse->variable(p);
5459 if (t == TRAVERSE_CONTINUE
5460 && (traverse_mask & e_or_t) != 0)
5462 if (p->is_result_variable()
5463 || p->var_value()->has_type())
5465 Type* tv = (p->is_variable()
5466 ? p->var_value()->type()
5467 : p->result_var_value()->type());
5468 if (tv != NULL
5469 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5470 return TRAVERSE_EXIT;
5473 if (t == TRAVERSE_CONTINUE
5474 && (traverse_mask & e_or_t_or_s) != 0
5475 && p->is_variable())
5476 t = p->var_value()->traverse_expression(traverse, traverse_mask);
5477 break;
5479 case Named_object::NAMED_OBJECT_FUNC:
5480 if ((traverse_mask & Traverse::traverse_functions) != 0)
5481 t = traverse->function(p);
5483 if (t == TRAVERSE_CONTINUE
5484 && (traverse_mask
5485 & (Traverse::traverse_variables
5486 | Traverse::traverse_constants
5487 | Traverse::traverse_functions
5488 | Traverse::traverse_blocks
5489 | Traverse::traverse_statements
5490 | Traverse::traverse_expressions
5491 | Traverse::traverse_types)) != 0)
5492 t = p->func_value()->traverse(traverse);
5493 break;
5495 case Named_object::NAMED_OBJECT_PACKAGE:
5496 // These are traversed in Gogo::traverse.
5497 go_assert(is_global);
5498 break;
5500 case Named_object::NAMED_OBJECT_TYPE:
5501 if ((traverse_mask & e_or_t) != 0)
5502 t = Type::traverse(p->type_value(), traverse);
5503 break;
5505 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5506 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5507 case Named_object::NAMED_OBJECT_UNKNOWN:
5508 case Named_object::NAMED_OBJECT_ERRONEOUS:
5509 break;
5511 case Named_object::NAMED_OBJECT_SINK:
5512 default:
5513 go_unreachable();
5516 if (t == TRAVERSE_EXIT)
5517 return TRAVERSE_EXIT;
5520 // If we need to traverse types, check the function declarations,
5521 // which have types. Also check any methods of a type declaration.
5522 if ((traverse_mask & e_or_t) != 0)
5524 for (Bindings::const_declarations_iterator p =
5525 this->begin_declarations();
5526 p != this->end_declarations();
5527 ++p)
5529 if (p->second->is_function_declaration())
5531 if (Type::traverse(p->second->func_declaration_value()->type(),
5532 traverse)
5533 == TRAVERSE_EXIT)
5534 return TRAVERSE_EXIT;
5536 else if (p->second->is_type_declaration())
5538 const std::vector<Named_object*>* methods =
5539 p->second->type_declaration_value()->methods();
5540 for (std::vector<Named_object*>::const_iterator pm =
5541 methods->begin();
5542 pm != methods->end();
5543 pm++)
5545 Named_object* no = *pm;
5546 Type *t;
5547 if (no->is_function())
5548 t = no->func_value()->type();
5549 else if (no->is_function_declaration())
5550 t = no->func_declaration_value()->type();
5551 else
5552 continue;
5553 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
5554 return TRAVERSE_EXIT;
5560 return TRAVERSE_CONTINUE;
5563 // Class Label.
5565 // Clear any references to this label.
5567 void
5568 Label::clear_refs()
5570 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
5571 p != this->refs_.end();
5572 ++p)
5573 delete *p;
5574 this->refs_.clear();
5577 // Get the backend representation for a label.
5579 Blabel*
5580 Label::get_backend_label(Translate_context* context)
5582 if (this->blabel_ == NULL)
5584 Function* function = context->function()->func_value();
5585 tree fndecl = function->get_decl();
5586 Bfunction* bfunction = tree_to_function(fndecl);
5587 this->blabel_ = context->backend()->label(bfunction, this->name_,
5588 this->location_);
5590 return this->blabel_;
5593 // Return an expression for the address of this label.
5595 Bexpression*
5596 Label::get_addr(Translate_context* context, Location location)
5598 Blabel* label = this->get_backend_label(context);
5599 return context->backend()->label_address(label, location);
5602 // Class Unnamed_label.
5604 // Get the backend representation for an unnamed label.
5606 Blabel*
5607 Unnamed_label::get_blabel(Translate_context* context)
5609 if (this->blabel_ == NULL)
5611 Function* function = context->function()->func_value();
5612 tree fndecl = function->get_decl();
5613 Bfunction* bfunction = tree_to_function(fndecl);
5614 this->blabel_ = context->backend()->label(bfunction, "",
5615 this->location_);
5617 return this->blabel_;
5620 // Return a statement which defines this unnamed label.
5622 Bstatement*
5623 Unnamed_label::get_definition(Translate_context* context)
5625 Blabel* blabel = this->get_blabel(context);
5626 return context->backend()->label_definition_statement(blabel);
5629 // Return a goto statement to this unnamed label.
5631 Bstatement*
5632 Unnamed_label::get_goto(Translate_context* context, Location location)
5634 Blabel* blabel = this->get_blabel(context);
5635 return context->backend()->goto_statement(blabel, location);
5638 // Class Package.
5640 Package::Package(const std::string& pkgpath, Location location)
5641 : pkgpath_(pkgpath), pkgpath_symbol_(Gogo::pkgpath_for_symbol(pkgpath)),
5642 package_name_(), bindings_(new Bindings(NULL)), priority_(0),
5643 location_(location), used_(false), is_imported_(false),
5644 uses_sink_alias_(false)
5646 go_assert(!pkgpath.empty());
5650 // Set the package name.
5652 void
5653 Package::set_package_name(const std::string& package_name, Location location)
5655 go_assert(!package_name.empty());
5656 if (this->package_name_.empty())
5657 this->package_name_ = package_name;
5658 else if (this->package_name_ != package_name)
5659 error_at(location,
5660 "saw two different packages with the same package path %s: %s, %s",
5661 this->pkgpath_.c_str(), this->package_name_.c_str(),
5662 package_name.c_str());
5665 // Set the priority. We may see multiple priorities for an imported
5666 // package; we want to use the largest one.
5668 void
5669 Package::set_priority(int priority)
5671 if (priority > this->priority_)
5672 this->priority_ = priority;
5675 // Determine types of constants. Everything else in a package
5676 // (variables, function declarations) should already have a fixed
5677 // type. Constants may have abstract types.
5679 void
5680 Package::determine_types()
5682 Bindings* bindings = this->bindings_;
5683 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
5684 p != bindings->end_definitions();
5685 ++p)
5687 if ((*p)->is_const())
5688 (*p)->const_value()->determine_type();
5692 // Class Traverse.
5694 // Destructor.
5696 Traverse::~Traverse()
5698 if (this->types_seen_ != NULL)
5699 delete this->types_seen_;
5700 if (this->expressions_seen_ != NULL)
5701 delete this->expressions_seen_;
5704 // Record that we are looking at a type, and return true if we have
5705 // already seen it.
5707 bool
5708 Traverse::remember_type(const Type* type)
5710 if (type->is_error_type())
5711 return true;
5712 go_assert((this->traverse_mask() & traverse_types) != 0
5713 || (this->traverse_mask() & traverse_expressions) != 0);
5714 // We mostly only have to remember named types. But it turns out
5715 // that an interface type can refer to itself without using a name
5716 // by relying on interface inheritance, as in
5717 // type I interface { F() interface{I} }
5718 if (type->classification() != Type::TYPE_NAMED
5719 && type->classification() != Type::TYPE_INTERFACE)
5720 return false;
5721 if (this->types_seen_ == NULL)
5722 this->types_seen_ = new Types_seen();
5723 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
5724 return !ins.second;
5727 // Record that we are looking at an expression, and return true if we
5728 // have already seen it.
5730 bool
5731 Traverse::remember_expression(const Expression* expression)
5733 go_assert((this->traverse_mask() & traverse_types) != 0
5734 || (this->traverse_mask() & traverse_expressions) != 0);
5735 if (this->expressions_seen_ == NULL)
5736 this->expressions_seen_ = new Expressions_seen();
5737 std::pair<Expressions_seen::iterator, bool> ins =
5738 this->expressions_seen_->insert(expression);
5739 return !ins.second;
5742 // The default versions of these functions should never be called: the
5743 // traversal mask indicates which functions may be called.
5746 Traverse::variable(Named_object*)
5748 go_unreachable();
5752 Traverse::constant(Named_object*, bool)
5754 go_unreachable();
5758 Traverse::function(Named_object*)
5760 go_unreachable();
5764 Traverse::block(Block*)
5766 go_unreachable();
5770 Traverse::statement(Block*, size_t*, Statement*)
5772 go_unreachable();
5776 Traverse::expression(Expression**)
5778 go_unreachable();
5782 Traverse::type(Type*)
5784 go_unreachable();
5787 // Class Statement_inserter.
5789 void
5790 Statement_inserter::insert(Statement* s)
5792 if (this->block_ != NULL)
5794 go_assert(this->pindex_ != NULL);
5795 this->block_->insert_statement_before(*this->pindex_, s);
5796 ++*this->pindex_;
5798 else if (this->var_ != NULL)
5799 this->var_->add_preinit_statement(this->gogo_, s);
5800 else
5801 go_assert(saw_errors());