compiler: drop special handling of unexported func/var assembler names
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blobc986963f1b2a38dae51650b31f7237569e709048
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 <fstream>
11 #include "filenames.h"
13 #include "go-c.h"
14 #include "go-diagnostics.h"
15 #include "go-encode-id.h"
16 #include "go-dump.h"
17 #include "go-optimize.h"
18 #include "lex.h"
19 #include "types.h"
20 #include "statements.h"
21 #include "expressions.h"
22 #include "runtime.h"
23 #include "import.h"
24 #include "export.h"
25 #include "backend.h"
26 #include "gogo.h"
28 // Class Gogo.
30 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
31 : backend_(backend),
32 linemap_(linemap),
33 package_(NULL),
34 functions_(),
35 globals_(new Bindings(NULL)),
36 file_block_names_(),
37 imports_(),
38 imported_unsafe_(false),
39 current_file_imported_unsafe_(false),
40 packages_(),
41 init_functions_(),
42 var_deps_(),
43 need_init_fn_(false),
44 init_fn_name_(),
45 imported_init_fns_(),
46 pkgpath_(),
47 pkgpath_symbol_(),
48 prefix_(),
49 pkgpath_set_(false),
50 pkgpath_from_option_(false),
51 prefix_from_option_(false),
52 relative_import_path_(),
53 c_header_(),
54 check_divide_by_zero_(true),
55 check_divide_overflow_(true),
56 compiling_runtime_(false),
57 debug_escape_level_(0),
58 verify_types_(),
59 interface_types_(),
60 specific_type_functions_(),
61 specific_type_functions_are_written_(false),
62 named_types_are_converted_(false),
63 analysis_sets_(),
64 gc_roots_()
66 const Location loc = Linemap::predeclared_location();
68 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
69 RUNTIME_TYPE_KIND_UINT8);
70 this->add_named_type(uint8_type);
71 this->add_named_type(Type::make_integer_type("uint16", true, 16,
72 RUNTIME_TYPE_KIND_UINT16));
73 this->add_named_type(Type::make_integer_type("uint32", true, 32,
74 RUNTIME_TYPE_KIND_UINT32));
75 this->add_named_type(Type::make_integer_type("uint64", true, 64,
76 RUNTIME_TYPE_KIND_UINT64));
78 this->add_named_type(Type::make_integer_type("int8", false, 8,
79 RUNTIME_TYPE_KIND_INT8));
80 this->add_named_type(Type::make_integer_type("int16", false, 16,
81 RUNTIME_TYPE_KIND_INT16));
82 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
83 RUNTIME_TYPE_KIND_INT32);
84 this->add_named_type(int32_type);
85 this->add_named_type(Type::make_integer_type("int64", false, 64,
86 RUNTIME_TYPE_KIND_INT64));
88 this->add_named_type(Type::make_float_type("float32", 32,
89 RUNTIME_TYPE_KIND_FLOAT32));
90 this->add_named_type(Type::make_float_type("float64", 64,
91 RUNTIME_TYPE_KIND_FLOAT64));
93 this->add_named_type(Type::make_complex_type("complex64", 64,
94 RUNTIME_TYPE_KIND_COMPLEX64));
95 this->add_named_type(Type::make_complex_type("complex128", 128,
96 RUNTIME_TYPE_KIND_COMPLEX128));
98 int int_type_size = pointer_size;
99 if (int_type_size < 32)
100 int_type_size = 32;
101 this->add_named_type(Type::make_integer_type("uint", true,
102 int_type_size,
103 RUNTIME_TYPE_KIND_UINT));
104 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
105 RUNTIME_TYPE_KIND_INT);
106 this->add_named_type(int_type);
108 this->add_named_type(Type::make_integer_type("uintptr", true,
109 pointer_size,
110 RUNTIME_TYPE_KIND_UINTPTR));
112 // "byte" is an alias for "uint8".
113 uint8_type->integer_type()->set_is_byte();
114 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
115 loc);
116 byte_type->type_value()->set_is_alias();
117 this->add_named_type(byte_type->type_value());
119 // "rune" is an alias for "int32".
120 int32_type->integer_type()->set_is_rune();
121 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
122 loc);
123 rune_type->type_value()->set_is_alias();
124 this->add_named_type(rune_type->type_value());
126 this->add_named_type(Type::make_named_bool_type());
128 this->add_named_type(Type::make_named_string_type());
130 // "error" is interface { Error() string }.
132 Typed_identifier_list *methods = new Typed_identifier_list;
133 Typed_identifier_list *results = new Typed_identifier_list;
134 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
135 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
136 methods->push_back(Typed_identifier("Error", method_type, loc));
137 Interface_type *error_iface = Type::make_interface_type(methods, loc);
138 error_iface->finalize_methods();
139 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
140 this->add_named_type(error_type);
143 this->globals_->add_constant(Typed_identifier("true",
144 Type::make_boolean_type(),
145 loc),
146 NULL,
147 Expression::make_boolean(true, loc),
149 this->globals_->add_constant(Typed_identifier("false",
150 Type::make_boolean_type(),
151 loc),
152 NULL,
153 Expression::make_boolean(false, loc),
156 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
157 loc),
158 NULL,
159 Expression::make_nil(loc),
162 Type* abstract_int_type = Type::make_abstract_integer_type();
163 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
164 loc),
165 NULL,
166 Expression::make_iota(),
169 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
170 new_type->set_is_varargs();
171 new_type->set_is_builtin();
172 this->globals_->add_function_declaration("new", NULL, new_type, loc);
174 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
175 make_type->set_is_varargs();
176 make_type->set_is_builtin();
177 this->globals_->add_function_declaration("make", NULL, make_type, loc);
179 Typed_identifier_list* len_result = new Typed_identifier_list();
180 len_result->push_back(Typed_identifier("", int_type, loc));
181 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
182 loc);
183 len_type->set_is_builtin();
184 this->globals_->add_function_declaration("len", NULL, len_type, loc);
186 Typed_identifier_list* cap_result = new Typed_identifier_list();
187 cap_result->push_back(Typed_identifier("", int_type, loc));
188 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
189 loc);
190 cap_type->set_is_builtin();
191 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
193 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
194 print_type->set_is_varargs();
195 print_type->set_is_builtin();
196 this->globals_->add_function_declaration("print", NULL, print_type, loc);
198 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
199 print_type->set_is_varargs();
200 print_type->set_is_builtin();
201 this->globals_->add_function_declaration("println", NULL, print_type, loc);
203 Type *empty = Type::make_empty_interface_type(loc);
204 Typed_identifier_list* panic_parms = new Typed_identifier_list();
205 panic_parms->push_back(Typed_identifier("e", empty, loc));
206 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
207 NULL, loc);
208 panic_type->set_is_builtin();
209 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
211 Typed_identifier_list* recover_result = new Typed_identifier_list();
212 recover_result->push_back(Typed_identifier("", empty, loc));
213 Function_type* recover_type = Type::make_function_type(NULL, NULL,
214 recover_result,
215 loc);
216 recover_type->set_is_builtin();
217 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
219 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
220 close_type->set_is_varargs();
221 close_type->set_is_builtin();
222 this->globals_->add_function_declaration("close", NULL, close_type, loc);
224 Typed_identifier_list* copy_result = new Typed_identifier_list();
225 copy_result->push_back(Typed_identifier("", int_type, loc));
226 Function_type* copy_type = Type::make_function_type(NULL, NULL,
227 copy_result, loc);
228 copy_type->set_is_varargs();
229 copy_type->set_is_builtin();
230 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
232 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
233 append_type->set_is_varargs();
234 append_type->set_is_builtin();
235 this->globals_->add_function_declaration("append", NULL, append_type, loc);
237 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
238 complex_type->set_is_varargs();
239 complex_type->set_is_builtin();
240 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
242 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
243 real_type->set_is_varargs();
244 real_type->set_is_builtin();
245 this->globals_->add_function_declaration("real", NULL, real_type, loc);
247 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
248 imag_type->set_is_varargs();
249 imag_type->set_is_builtin();
250 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
252 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
253 delete_type->set_is_varargs();
254 delete_type->set_is_builtin();
255 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
258 // Convert a pkgpath into a string suitable for a symbol. Note that
259 // this transformation is convenient but imperfect. A -fgo-pkgpath
260 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
261 // possibly leading to link time errors.
263 std::string
264 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
266 std::string s = pkgpath;
267 for (size_t i = 0; i < s.length(); ++i)
269 char c = s[i];
270 if ((c >= 'a' && c <= 'z')
271 || (c >= 'A' && c <= 'Z')
272 || (c >= '0' && c <= '9'))
274 else
275 s[i] = '_';
277 return s;
280 // Get the package path to use for type reflection data. This should
281 // ideally be unique across the entire link.
283 const std::string&
284 Gogo::pkgpath() const
286 go_assert(this->pkgpath_set_);
287 return this->pkgpath_;
290 // Set the package path from the -fgo-pkgpath command line option.
292 void
293 Gogo::set_pkgpath(const std::string& arg)
295 go_assert(!this->pkgpath_set_);
296 this->pkgpath_ = arg;
297 this->pkgpath_set_ = true;
298 this->pkgpath_from_option_ = true;
301 // Get the package path to use for symbol names.
303 const std::string&
304 Gogo::pkgpath_symbol() const
306 go_assert(this->pkgpath_set_);
307 return this->pkgpath_symbol_;
310 // Set the unique prefix to use to determine the package path, from
311 // the -fgo-prefix command line option.
313 void
314 Gogo::set_prefix(const std::string& arg)
316 go_assert(!this->prefix_from_option_);
317 this->prefix_ = arg;
318 this->prefix_from_option_ = true;
321 // Munge name for use in an error message.
323 std::string
324 Gogo::message_name(const std::string& name)
326 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
329 // Get the package name.
331 const std::string&
332 Gogo::package_name() const
334 go_assert(this->package_ != NULL);
335 return this->package_->package_name();
338 // Set the package name.
340 void
341 Gogo::set_package_name(const std::string& package_name,
342 Location location)
344 if (this->package_ != NULL)
346 if (this->package_->package_name() != package_name)
347 go_error_at(location, "expected package %<%s%>",
348 Gogo::message_name(this->package_->package_name()).c_str());
349 return;
352 // Now that we know the name of the package we are compiling, set
353 // the package path to use for reflect.Type.PkgPath and global
354 // symbol names.
355 if (this->pkgpath_set_)
356 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
357 else
359 if (!this->prefix_from_option_ && package_name == "main")
361 this->pkgpath_ = package_name;
362 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
364 else
366 if (!this->prefix_from_option_)
367 this->prefix_ = "go";
368 this->pkgpath_ = this->prefix_ + '.' + package_name;
369 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
370 + Gogo::pkgpath_for_symbol(package_name));
372 this->pkgpath_set_ = true;
375 this->package_ = this->register_package(this->pkgpath_,
376 this->pkgpath_symbol_, location);
377 this->package_->set_package_name(package_name, location);
379 if (this->is_main_package())
381 // Declare "main" as a function which takes no parameters and
382 // returns no value.
383 Location uloc = Linemap::unknown_location();
384 this->declare_function(Gogo::pack_hidden_name("main", false),
385 Type::make_function_type (NULL, NULL, NULL, uloc),
386 uloc);
390 // Return whether this is the "main" package. This is not true if
391 // -fgo-pkgpath or -fgo-prefix was used.
393 bool
394 Gogo::is_main_package() const
396 return (this->package_name() == "main"
397 && !this->pkgpath_from_option_
398 && !this->prefix_from_option_);
401 // Import a package.
403 void
404 Gogo::import_package(const std::string& filename,
405 const std::string& local_name,
406 bool is_local_name_exported,
407 bool must_exist,
408 Location location)
410 if (filename.empty())
412 go_error_at(location, "import path is empty");
413 return;
416 const char *pf = filename.data();
417 const char *pend = pf + filename.length();
418 while (pf < pend)
420 unsigned int c;
421 int adv = Lex::fetch_char(pf, &c);
422 if (adv == 0)
424 go_error_at(location, "import path contains invalid UTF-8 sequence");
425 return;
427 if (c == '\0')
429 go_error_at(location, "import path contains NUL");
430 return;
432 if (c < 0x20 || c == 0x7f)
434 go_error_at(location, "import path contains control character");
435 return;
437 if (c == '\\')
439 go_error_at(location, "import path contains backslash; use slash");
440 return;
442 if (Lex::is_unicode_space(c))
444 go_error_at(location, "import path contains space character");
445 return;
447 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
449 go_error_at(location,
450 "import path contains invalid character '%c'", c);
451 return;
453 pf += adv;
456 if (IS_ABSOLUTE_PATH(filename.c_str()))
458 go_error_at(location, "import path cannot be absolute path");
459 return;
462 if (local_name == "init")
463 go_error_at(location, "cannot import package as init");
465 if (filename == "unsafe")
467 this->import_unsafe(local_name, is_local_name_exported, location);
468 this->current_file_imported_unsafe_ = true;
469 return;
472 Imports::const_iterator p = this->imports_.find(filename);
473 if (p != this->imports_.end())
475 Package* package = p->second;
476 package->set_location(location);
477 std::string ln = local_name;
478 bool is_ln_exported = is_local_name_exported;
479 if (ln.empty())
481 ln = package->package_name();
482 go_assert(!ln.empty());
483 is_ln_exported = Lex::is_exported_name(ln);
485 if (ln == "_")
487 else if (ln == ".")
489 Bindings* bindings = package->bindings();
490 for (Bindings::const_declarations_iterator p =
491 bindings->begin_declarations();
492 p != bindings->end_declarations();
493 ++p)
494 this->add_dot_import_object(p->second);
495 std::string dot_alias = "." + package->package_name();
496 package->add_alias(dot_alias, location);
498 else
500 package->add_alias(ln, location);
501 ln = this->pack_hidden_name(ln, is_ln_exported);
502 this->package_->bindings()->add_package(ln, package);
504 return;
507 Import::Stream* stream = Import::open_package(filename, location,
508 this->relative_import_path_);
509 if (stream == NULL)
511 if (must_exist)
512 go_error_at(location, "import file %qs not found", filename.c_str());
513 return;
516 Import imp(stream, location);
517 imp.register_builtin_types(this);
518 Package* package = imp.import(this, local_name, is_local_name_exported);
519 if (package != NULL)
521 if (package->pkgpath() == this->pkgpath())
522 go_error_at(location,
523 ("imported package uses same package path as package "
524 "being compiled (see -fgo-pkgpath option)"));
526 this->imports_.insert(std::make_pair(filename, package));
529 delete stream;
532 Import_init *
533 Gogo::lookup_init(const std::string& init_name)
535 Import_init tmp("", init_name, -1);
536 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
537 return (it != this->imported_init_fns_.end()) ? *it : NULL;
540 // Add an import control function for an imported package to the list.
542 void
543 Gogo::add_import_init_fn(const std::string& package_name,
544 const std::string& init_name, int prio)
546 for (Import_init_set::iterator p =
547 this->imported_init_fns_.begin();
548 p != this->imported_init_fns_.end();
549 ++p)
551 Import_init *ii = (*p);
552 if (ii->init_name() == init_name)
554 // If a test of package P1, built as part of package P1,
555 // imports package P2, and P2 imports P1 (perhaps
556 // indirectly), then we will see the same import name with
557 // different import priorities. That is OK, so don't give
558 // an error about it.
559 if (ii->package_name() != package_name)
561 go_error_at(Linemap::unknown_location(),
562 "duplicate package initialization name %qs",
563 Gogo::message_name(init_name).c_str());
564 go_inform(Linemap::unknown_location(), "used by package %qs",
565 Gogo::message_name(ii->package_name()).c_str());
566 go_inform(Linemap::unknown_location(), " and by package %qs",
567 Gogo::message_name(package_name).c_str());
569 ii->set_priority(prio);
570 return;
574 Import_init* nii = new Import_init(package_name, init_name, prio);
575 this->imported_init_fns_.insert(nii);
578 // Return whether we are at the global binding level.
580 bool
581 Gogo::in_global_scope() const
583 return this->functions_.empty();
586 // Return the current binding contour.
588 Bindings*
589 Gogo::current_bindings()
591 if (!this->functions_.empty())
592 return this->functions_.back().blocks.back()->bindings();
593 else if (this->package_ != NULL)
594 return this->package_->bindings();
595 else
596 return this->globals_;
599 const Bindings*
600 Gogo::current_bindings() const
602 if (!this->functions_.empty())
603 return this->functions_.back().blocks.back()->bindings();
604 else if (this->package_ != NULL)
605 return this->package_->bindings();
606 else
607 return this->globals_;
610 void
611 Gogo::update_init_priority(Import_init* ii,
612 std::set<const Import_init *>* visited)
614 visited->insert(ii);
615 int succ_prior = -1;
617 for (std::set<std::string>::const_iterator pci =
618 ii->precursors().begin();
619 pci != ii->precursors().end();
620 ++pci)
622 Import_init* succ = this->lookup_init(*pci);
623 if (visited->find(succ) == visited->end())
624 update_init_priority(succ, visited);
625 succ_prior = std::max(succ_prior, succ->priority());
627 if (ii->priority() <= succ_prior)
628 ii->set_priority(succ_prior + 1);
631 void
632 Gogo::recompute_init_priorities()
634 std::set<Import_init *> nonroots;
636 for (Import_init_set::const_iterator p =
637 this->imported_init_fns_.begin();
638 p != this->imported_init_fns_.end();
639 ++p)
641 const Import_init *ii = *p;
642 for (std::set<std::string>::const_iterator pci =
643 ii->precursors().begin();
644 pci != ii->precursors().end();
645 ++pci)
647 Import_init* ii = this->lookup_init(*pci);
648 nonroots.insert(ii);
652 // Recursively update priorities starting at roots.
653 std::set<const Import_init*> visited;
654 for (Import_init_set::iterator p =
655 this->imported_init_fns_.begin();
656 p != this->imported_init_fns_.end();
657 ++p)
659 Import_init* ii = *p;
660 if (nonroots.find(ii) != nonroots.end())
661 continue;
662 update_init_priority(ii, &visited);
666 // Add statements to INIT_STMTS which run the initialization
667 // functions for imported packages. This is only used for the "main"
668 // package.
670 void
671 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
673 go_assert(this->is_main_package());
675 if (this->imported_init_fns_.empty())
676 return;
678 Location unknown_loc = Linemap::unknown_location();
679 Function_type* func_type =
680 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
681 Btype* fntype = func_type->get_backend_fntype(this);
683 // Recompute init priorities based on a walk of the init graph.
684 recompute_init_priorities();
686 // We must call them in increasing priority order.
687 std::vector<const Import_init*> v;
688 for (Import_init_set::const_iterator p =
689 this->imported_init_fns_.begin();
690 p != this->imported_init_fns_.end();
691 ++p)
693 if ((*p)->priority() < 0)
694 go_error_at(Linemap::unknown_location(),
695 "internal error: failed to set init priority for %s",
696 (*p)->package_name().c_str());
697 v.push_back(*p);
699 std::sort(v.begin(), v.end(), priority_compare);
701 // We build calls to the init functions, which take no arguments.
702 std::vector<Bexpression*> empty_args;
703 for (std::vector<const Import_init*>::const_iterator p = v.begin();
704 p != v.end();
705 ++p)
707 const Import_init* ii = *p;
708 std::string user_name = ii->package_name() + ".init";
709 const std::string& init_name(ii->init_name());
711 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
712 true, true, true, false,
713 false, unknown_loc);
714 Bexpression* pfunc_code =
715 this->backend()->function_code_expression(pfunc, unknown_loc);
716 Bexpression* pfunc_call =
717 this->backend()->call_expression(bfunction, pfunc_code, empty_args,
718 NULL, unknown_loc);
719 init_stmts.push_back(this->backend()->expression_statement(bfunction,
720 pfunc_call));
724 // Register global variables with the garbage collector. We need to
725 // register all variables which can hold a pointer value. They become
726 // roots during the mark phase. We build a struct that is easy to
727 // hook into a list of roots.
729 // type gcRoot struct {
730 // decl unsafe.Pointer // Pointer to variable.
731 // size uintptr // Total size of variable.
732 // ptrdata uintptr // Length of variable's gcdata.
733 // gcdata *byte // Pointer mask.
734 // }
736 // type gcRootList struct {
737 // next *gcRootList
738 // count int
739 // roots [...]gcRoot
740 // }
742 // The last entry in the roots array has a NULL decl field.
744 void
745 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
746 std::vector<Bstatement*>& init_stmts,
747 Bfunction* init_bfn)
749 if (var_gc.empty() && this->gc_roots_.empty())
750 return;
752 Type* pvt = Type::make_pointer_type(Type::make_void_type());
753 Type* uintptr_type = Type::lookup_integer_type("uintptr");
754 Type* byte_type = this->lookup_global("byte")->type_value();
755 Type* pointer_byte_type = Type::make_pointer_type(byte_type);
756 Struct_type* root_type =
757 Type::make_builtin_struct_type(4,
758 "decl", pvt,
759 "size", uintptr_type,
760 "ptrdata", uintptr_type,
761 "gcdata", pointer_byte_type);
763 Location builtin_loc = Linemap::predeclared_location();
764 unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
765 Expression* length = Expression::make_integer_ul(roots_len, NULL,
766 builtin_loc);
767 Array_type* root_array_type = Type::make_array_type(root_type, length);
768 root_array_type->set_is_array_incomparable();
770 Type* int_type = Type::lookup_integer_type("int");
771 Struct_type* root_list_type =
772 Type::make_builtin_struct_type(3,
773 "next", pvt,
774 "count", int_type,
775 "roots", root_array_type);
777 // Build an initializer for the roots array.
779 Expression_list* roots_init = new Expression_list();
781 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
782 p != var_gc.end();
783 ++p)
785 Expression_list* init = new Expression_list();
787 Location no_loc = (*p)->location();
788 Expression* decl = Expression::make_var_reference(*p, no_loc);
789 Expression* decl_addr =
790 Expression::make_unary(OPERATOR_AND, decl, no_loc);
791 decl_addr->unary_expression()->set_does_not_escape();
792 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
793 init->push_back(decl_addr);
795 Expression* size =
796 Expression::make_type_info(decl->type(),
797 Expression::TYPE_INFO_SIZE);
798 init->push_back(size);
800 Expression* ptrdata =
801 Expression::make_type_info(decl->type(),
802 Expression::TYPE_INFO_BACKEND_PTRDATA);
803 init->push_back(ptrdata);
805 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
806 init->push_back(gcdata);
808 Expression* root_ctor =
809 Expression::make_struct_composite_literal(root_type, init, no_loc);
810 roots_init->push_back(root_ctor);
813 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
814 p != this->gc_roots_.end();
815 ++p)
817 Expression_list *init = new Expression_list();
819 Expression* expr = *p;
820 Location eloc = expr->location();
821 init->push_back(Expression::make_cast(pvt, expr, eloc));
823 Type* type = expr->type()->points_to();
824 go_assert(type != NULL);
826 Expression* size =
827 Expression::make_type_info(type,
828 Expression::TYPE_INFO_SIZE);
829 init->push_back(size);
831 Expression* ptrdata =
832 Expression::make_type_info(type,
833 Expression::TYPE_INFO_BACKEND_PTRDATA);
834 init->push_back(ptrdata);
836 Expression* gcdata = Expression::make_ptrmask_symbol(type);
837 init->push_back(gcdata);
839 Expression* root_ctor =
840 Expression::make_struct_composite_literal(root_type, init, eloc);
841 roots_init->push_back(root_ctor);
844 // Build a constructor for the struct.
846 Expression_list* root_list_init = new Expression_list();
847 root_list_init->push_back(Expression::make_nil(builtin_loc));
848 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
849 builtin_loc));
851 Expression* roots_ctor =
852 Expression::make_array_composite_literal(root_array_type, roots_init,
853 builtin_loc);
854 root_list_init->push_back(roots_ctor);
856 Expression* root_list_ctor =
857 Expression::make_struct_composite_literal(root_list_type, root_list_init,
858 builtin_loc);
860 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
861 builtin_loc);
862 root_addr->unary_expression()->set_is_gc_root();
863 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
864 builtin_loc, 1, root_addr);
866 Translate_context context(this, NULL, NULL, NULL);
867 Bexpression* bcall = register_roots->get_backend(&context);
868 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
871 // Build the decl for the initialization function.
873 Named_object*
874 Gogo::initialization_function_decl()
876 std::string name = this->get_init_fn_name();
877 Location loc = this->package_->location();
879 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
880 Function* initfn = new Function(fntype, NULL, NULL, loc);
881 return Named_object::make_function(name, NULL, initfn);
884 // Create the magic initialization function. CODE_STMT is the
885 // code that it needs to run.
887 Named_object*
888 Gogo::create_initialization_function(Named_object* initfn,
889 Bstatement* code_stmt)
891 // Make sure that we thought we needed an initialization function,
892 // as otherwise we will not have reported it in the export data.
893 go_assert(this->is_main_package() || this->need_init_fn_);
895 if (initfn == NULL)
896 initfn = this->initialization_function_decl();
898 // Bind the initialization function code to a block.
899 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
900 Location pkg_loc = this->package_->location();
901 std::vector<Bvariable*> vars;
902 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
904 if (!this->backend()->function_set_body(fndecl, code_stmt))
906 go_assert(saw_errors());
907 return NULL;
909 return initfn;
912 // Search for references to VAR in any statements or called functions.
914 class Find_var : public Traverse
916 public:
917 // A hash table we use to avoid looping. The index is the name of a
918 // named object. We only look through objects defined in this
919 // package.
920 typedef Unordered_set(const void*) Seen_objects;
922 Find_var(Named_object* var, Seen_objects* seen_objects)
923 : Traverse(traverse_expressions),
924 var_(var), seen_objects_(seen_objects), found_(false)
927 // Whether the variable was found.
928 bool
929 found() const
930 { return this->found_; }
933 expression(Expression**);
935 private:
936 // The variable we are looking for.
937 Named_object* var_;
938 // Names of objects we have already seen.
939 Seen_objects* seen_objects_;
940 // True if the variable was found.
941 bool found_;
944 // See if EXPR refers to VAR, looking through function calls and
945 // variable initializations.
948 Find_var::expression(Expression** pexpr)
950 Expression* e = *pexpr;
952 Var_expression* ve = e->var_expression();
953 if (ve != NULL)
955 Named_object* v = ve->named_object();
956 if (v == this->var_)
958 this->found_ = true;
959 return TRAVERSE_EXIT;
962 if (v->is_variable() && v->package() == NULL)
964 Expression* init = v->var_value()->init();
965 if (init != NULL)
967 std::pair<Seen_objects::iterator, bool> ins =
968 this->seen_objects_->insert(v);
969 if (ins.second)
971 // This is the first time we have seen this name.
972 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
973 return TRAVERSE_EXIT;
979 // We traverse the code of any function or bound method we see. Note that
980 // this means that we will traverse the code of a function or bound method
981 // whose address is taken even if it is not called.
982 Func_expression* fe = e->func_expression();
983 Bound_method_expression* bme = e->bound_method_expression();
984 if (fe != NULL || bme != NULL)
986 const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
987 if (f->is_function() && f->package() == NULL)
989 std::pair<Seen_objects::iterator, bool> ins =
990 this->seen_objects_->insert(f);
991 if (ins.second)
993 // This is the first time we have seen this name.
994 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
995 return TRAVERSE_EXIT;
1000 Temporary_reference_expression* tre = e->temporary_reference_expression();
1001 if (tre != NULL)
1003 Temporary_statement* ts = tre->statement();
1004 Expression* init = ts->init();
1005 if (init != NULL)
1007 std::pair<Seen_objects::iterator, bool> ins =
1008 this->seen_objects_->insert(ts);
1009 if (ins.second)
1011 // This is the first time we have seen this temporary
1012 // statement.
1013 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1014 return TRAVERSE_EXIT;
1019 return TRAVERSE_CONTINUE;
1022 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1024 static bool
1025 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1026 Named_object* var)
1028 Find_var::Seen_objects seen_objects;
1029 Find_var find_var(var, &seen_objects);
1030 if (expr != NULL)
1031 Expression::traverse(&expr, &find_var);
1032 if (preinit != NULL)
1033 preinit->traverse(&find_var);
1034 if (dep != NULL)
1036 Expression* init = dep->var_value()->init();
1037 if (init != NULL)
1038 Expression::traverse(&init, &find_var);
1039 if (dep->var_value()->has_pre_init())
1040 dep->var_value()->preinit()->traverse(&find_var);
1043 return find_var.found();
1046 // Sort variable initializations. If the initialization expression
1047 // for variable A refers directly or indirectly to the initialization
1048 // expression for variable B, then we must initialize B before A.
1050 class Var_init
1052 public:
1053 Var_init()
1054 : var_(NULL), init_(NULL), dep_count_(0)
1057 Var_init(Named_object* var, Bstatement* init)
1058 : var_(var), init_(init), dep_count_(0)
1061 // Return the variable.
1062 Named_object*
1063 var() const
1064 { return this->var_; }
1066 // Return the initialization expression.
1067 Bstatement*
1068 init() const
1069 { return this->init_; }
1071 // Return the number of remaining dependencies.
1072 size_t
1073 dep_count() const
1074 { return this->dep_count_; }
1076 // Increment the number of dependencies.
1077 void
1078 add_dependency()
1079 { ++this->dep_count_; }
1081 // Decrement the number of dependencies.
1082 void
1083 remove_dependency()
1084 { --this->dep_count_; }
1086 private:
1087 // The variable being initialized.
1088 Named_object* var_;
1089 // The initialization statement.
1090 Bstatement* init_;
1091 // The number of initializations this is dependent on. A variable
1092 // initialization should not be emitted if any of its dependencies
1093 // have not yet been resolved.
1094 size_t dep_count_;
1097 // For comparing Var_init keys in a map.
1099 inline bool
1100 operator<(const Var_init& v1, const Var_init& v2)
1101 { return v1.var()->name() < v2.var()->name(); }
1103 typedef std::list<Var_init> Var_inits;
1105 // Sort the variable initializations. The rule we follow is that we
1106 // emit them in the order they appear in the array, except that if the
1107 // initialization expression for a variable V1 depends upon another
1108 // variable V2 then we initialize V1 after V2.
1110 static void
1111 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1113 if (var_inits->empty())
1114 return;
1116 typedef std::pair<Named_object*, Named_object*> No_no;
1117 typedef std::map<No_no, bool> Cache;
1118 Cache cache;
1120 // A mapping from a variable initialization to a set of
1121 // variable initializations that depend on it.
1122 typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1123 Init_deps init_deps;
1124 bool init_loop = false;
1125 for (Var_inits::iterator p1 = var_inits->begin();
1126 p1 != var_inits->end();
1127 ++p1)
1129 Named_object* var = p1->var();
1130 Expression* init = var->var_value()->init();
1131 Block* preinit = var->var_value()->preinit();
1132 Named_object* dep = gogo->var_depends_on(var->var_value());
1134 // Start walking through the list to see which variables VAR
1135 // needs to wait for.
1136 for (Var_inits::iterator p2 = var_inits->begin();
1137 p2 != var_inits->end();
1138 ++p2)
1140 if (var == p2->var())
1141 continue;
1143 Named_object* p2var = p2->var();
1144 No_no key(var, p2var);
1145 std::pair<Cache::iterator, bool> ins =
1146 cache.insert(std::make_pair(key, false));
1147 if (ins.second)
1148 ins.first->second = expression_requires(init, preinit, dep, p2var);
1149 if (ins.first->second)
1151 // VAR depends on P2VAR.
1152 init_deps[*p2].insert(&(*p1));
1153 p1->add_dependency();
1155 // Check for cycles.
1156 key = std::make_pair(p2var, var);
1157 ins = cache.insert(std::make_pair(key, false));
1158 if (ins.second)
1159 ins.first->second =
1160 expression_requires(p2var->var_value()->init(),
1161 p2var->var_value()->preinit(),
1162 gogo->var_depends_on(p2var->var_value()),
1163 var);
1164 if (ins.first->second)
1166 go_error_at(var->location(),
1167 ("initialization expressions for %qs and "
1168 "%qs depend upon each other"),
1169 var->message_name().c_str(),
1170 p2var->message_name().c_str());
1171 go_inform(p2->var()->location(), "%qs defined here",
1172 p2var->message_name().c_str());
1173 init_loop = true;
1174 break;
1180 // If there are no dependencies then the declaration order is sorted.
1181 if (!init_deps.empty() && !init_loop)
1183 // Otherwise, sort variable initializations by emitting all variables with
1184 // no dependencies in declaration order. VAR_INITS is already in
1185 // declaration order.
1186 Var_inits ready;
1187 while (!var_inits->empty())
1189 Var_inits::iterator v1;;
1190 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1192 if (v1->dep_count() == 0)
1193 break;
1195 go_assert(v1 != var_inits->end());
1197 // V1 either has no dependencies or its dependencies have already
1198 // been emitted, add it to READY next. When V1 is emitted, remove
1199 // a dependency from each V that depends on V1.
1200 ready.splice(ready.end(), *var_inits, v1);
1202 Init_deps::iterator p1 = init_deps.find(*v1);
1203 if (p1 != init_deps.end())
1205 std::set<Var_init*> resolved = p1->second;
1206 for (std::set<Var_init*>::iterator pv = resolved.begin();
1207 pv != resolved.end();
1208 ++pv)
1209 (*pv)->remove_dependency();
1210 init_deps.erase(p1);
1213 var_inits->swap(ready);
1214 go_assert(init_deps.empty());
1217 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1218 // check for a loop of VAR on itself.
1219 // interpret as a loop.
1220 for (Var_inits::const_iterator p = var_inits->begin();
1221 p != var_inits->end();
1222 ++p)
1223 gogo->check_self_dep(p->var());
1226 // Give an error if the initialization expression for VAR depends on
1227 // itself. We only check if INIT is not NULL and there is no
1228 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1229 // which we will interpret as a loop.
1231 void
1232 Gogo::check_self_dep(Named_object* var)
1234 Expression* init = var->var_value()->init();
1235 Block* preinit = var->var_value()->preinit();
1236 Named_object* dep = this->var_depends_on(var->var_value());
1237 if (init != NULL
1238 && dep == NULL
1239 && expression_requires(init, preinit, NULL, var))
1240 go_error_at(var->location(),
1241 "initialization expression for %qs depends upon itself",
1242 var->message_name().c_str());
1245 // Write out the global definitions.
1247 void
1248 Gogo::write_globals()
1250 this->build_interface_method_tables();
1252 Bindings* bindings = this->current_bindings();
1254 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1255 p != bindings->end_declarations();
1256 ++p)
1258 // If any function declarations needed a descriptor, make sure
1259 // we build it.
1260 Named_object* no = p->second;
1261 if (no->is_function_declaration())
1262 no->func_declaration_value()->build_backend_descriptor(this);
1265 // Lists of globally declared types, variables, constants, and functions
1266 // that must be defined.
1267 std::vector<Btype*> type_decls;
1268 std::vector<Bvariable*> var_decls;
1269 std::vector<Bexpression*> const_decls;
1270 std::vector<Bfunction*> func_decls;
1272 // The init function declaration and associated Bfunction, if necessary.
1273 Named_object* init_fndecl = NULL;
1274 Bfunction* init_bfn = NULL;
1276 std::vector<Bstatement*> init_stmts;
1277 std::vector<Bstatement*> var_init_stmts;
1279 if (this->is_main_package())
1281 init_fndecl = this->initialization_function_decl();
1282 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1283 this->init_imports(init_stmts, init_bfn);
1286 // A list of variable initializations.
1287 Var_inits var_inits;
1289 // A list of variables which need to be registered with the garbage
1290 // collector.
1291 size_t count_definitions = bindings->size_definitions();
1292 std::vector<Named_object*> var_gc;
1293 var_gc.reserve(count_definitions);
1295 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1296 p != bindings->end_definitions();
1297 ++p)
1299 Named_object* no = *p;
1300 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1302 // There is nothing to do for a package.
1303 if (no->is_package())
1304 continue;
1306 // There is nothing to do for an object which was imported from
1307 // a different package into the global scope.
1308 if (no->package() != NULL)
1309 continue;
1311 // Skip blank named functions and constants.
1312 if ((no->is_function() && no->func_value()->is_sink())
1313 || (no->is_const() && no->const_value()->is_sink()))
1314 continue;
1316 // There is nothing useful we can output for constants which
1317 // have ideal or non-integral type.
1318 if (no->is_const())
1320 Type* type = no->const_value()->type();
1321 if (type == NULL)
1322 type = no->const_value()->expr()->type();
1323 if (type->is_abstract() || !type->is_numeric_type())
1324 continue;
1327 if (!no->is_variable())
1328 no->get_backend(this, const_decls, type_decls, func_decls);
1329 else
1331 Variable* var = no->var_value();
1332 Bvariable* bvar = no->get_backend_variable(this, NULL);
1333 var_decls.push_back(bvar);
1335 // Check for a sink variable, which may be used to run an
1336 // initializer purely for its side effects.
1337 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1339 Bstatement* var_init_stmt = NULL;
1340 if (!var->has_pre_init())
1342 // If the backend representation of the variable initializer is
1343 // constant, we can just set the initial value using
1344 // global_var_set_init instead of during the init() function.
1345 // The initializer is constant if it is the zero-value of the
1346 // variable's type or if the initial value is an immutable value
1347 // that is not copied to the heap.
1348 bool is_static_initializer = false;
1349 if (var->init() == NULL)
1350 is_static_initializer = true;
1351 else
1353 Type* var_type = var->type();
1354 Expression* init = var->init();
1355 Expression* init_cast =
1356 Expression::make_cast(var_type, init, var->location());
1357 is_static_initializer = init_cast->is_static_initializer();
1360 // Non-constant variable initializations might need to create
1361 // temporary variables, which will need the initialization
1362 // function as context.
1363 Named_object* var_init_fn;
1364 if (is_static_initializer)
1365 var_init_fn = NULL;
1366 else
1368 if (init_fndecl == NULL)
1370 init_fndecl = this->initialization_function_decl();
1371 Function* func = init_fndecl->func_value();
1372 init_bfn = func->get_or_make_decl(this, init_fndecl);
1374 var_init_fn = init_fndecl;
1376 Bexpression* var_binit = var->get_init(this, var_init_fn);
1378 if (var_binit == NULL)
1380 else if (is_static_initializer)
1382 if (expression_requires(var->init(), NULL,
1383 this->var_depends_on(var), no))
1384 go_error_at(no->location(),
1385 "initialization expression for %qs depends "
1386 "upon itself",
1387 no->message_name().c_str());
1388 this->backend()->global_variable_set_init(bvar, var_binit);
1390 else if (is_sink)
1391 var_init_stmt =
1392 this->backend()->expression_statement(init_bfn, var_binit);
1393 else
1395 Location loc = var->location();
1396 Bexpression* var_expr =
1397 this->backend()->var_expression(bvar, VE_lvalue, loc);
1398 var_init_stmt =
1399 this->backend()->assignment_statement(init_bfn, var_expr,
1400 var_binit, loc);
1403 else
1405 // We are going to create temporary variables which
1406 // means that we need an fndecl.
1407 if (init_fndecl == NULL)
1408 init_fndecl = this->initialization_function_decl();
1410 Bvariable* var_decl = is_sink ? NULL : bvar;
1411 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1414 if (var_init_stmt != NULL)
1416 if (var->init() == NULL && !var->has_pre_init())
1417 var_init_stmts.push_back(var_init_stmt);
1418 else
1419 var_inits.push_back(Var_init(no, var_init_stmt));
1421 else if (this->var_depends_on(var) != NULL)
1423 // This variable is initialized from something that is
1424 // not in its init or preinit. This variable needs to
1425 // participate in dependency analysis sorting, in case
1426 // some other variable depends on this one.
1427 Btype* btype = no->var_value()->type()->get_backend(this);
1428 Bexpression* zero = this->backend()->zero_expression(btype);
1429 Bstatement* zero_stmt =
1430 this->backend()->expression_statement(init_bfn, zero);
1431 var_inits.push_back(Var_init(no, zero_stmt));
1434 // Collect a list of all global variables with pointers,
1435 // to register them for the garbage collector.
1436 if (!is_sink && var->type()->has_pointer())
1438 // Avoid putting runtime.gcRoots itself on the list.
1439 if (this->compiling_runtime()
1440 && this->package_name() == "runtime"
1441 && Gogo::unpack_hidden_name(no->name()) == "gcRoots")
1443 else
1444 var_gc.push_back(no);
1449 // Register global variables with the garbage collector.
1450 this->register_gc_vars(var_gc, init_stmts, init_bfn);
1452 // Simple variable initializations, after all variables are
1453 // registered.
1454 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1456 // Complete variable initializations, first sorting them into a
1457 // workable order.
1458 if (!var_inits.empty())
1460 sort_var_inits(this, &var_inits);
1461 for (Var_inits::const_iterator p = var_inits.begin();
1462 p != var_inits.end();
1463 ++p)
1464 init_stmts.push_back(p->init());
1467 // After all the variables are initialized, call the init
1468 // functions if there are any. Init functions take no arguments, so
1469 // we pass in EMPTY_ARGS to call them.
1470 std::vector<Bexpression*> empty_args;
1471 for (std::vector<Named_object*>::const_iterator p =
1472 this->init_functions_.begin();
1473 p != this->init_functions_.end();
1474 ++p)
1476 Location func_loc = (*p)->location();
1477 Function* func = (*p)->func_value();
1478 Bfunction* initfn = func->get_or_make_decl(this, *p);
1479 Bexpression* func_code =
1480 this->backend()->function_code_expression(initfn, func_loc);
1481 Bexpression* call = this->backend()->call_expression(init_bfn, func_code,
1482 empty_args,
1483 NULL, func_loc);
1484 Bstatement* ist = this->backend()->expression_statement(init_bfn, call);
1485 init_stmts.push_back(ist);
1488 // Set up a magic function to do all the initialization actions.
1489 // This will be called if this package is imported.
1490 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1491 if (this->need_init_fn_ || this->is_main_package())
1493 init_fndecl =
1494 this->create_initialization_function(init_fndecl, init_fncode);
1495 if (init_fndecl != NULL)
1496 func_decls.push_back(init_fndecl->func_value()->get_decl());
1499 // We should not have seen any new bindings created during the conversion.
1500 go_assert(count_definitions == this->current_bindings()->size_definitions());
1502 // Define all globally declared values.
1503 if (!saw_errors())
1504 this->backend()->write_global_definitions(type_decls, const_decls,
1505 func_decls, var_decls);
1508 // Return the current block.
1510 Block*
1511 Gogo::current_block()
1513 if (this->functions_.empty())
1514 return NULL;
1515 else
1516 return this->functions_.back().blocks.back();
1519 // Look up a name in the current binding contour. If PFUNCTION is not
1520 // NULL, set it to the function in which the name is defined, or NULL
1521 // if the name is defined in global scope.
1523 Named_object*
1524 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1526 if (pfunction != NULL)
1527 *pfunction = NULL;
1529 if (Gogo::is_sink_name(name))
1530 return Named_object::make_sink();
1532 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1533 p != this->functions_.rend();
1534 ++p)
1536 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1537 if (ret != NULL)
1539 if (pfunction != NULL)
1540 *pfunction = p->function;
1541 return ret;
1545 if (this->package_ != NULL)
1547 Named_object* ret = this->package_->bindings()->lookup(name);
1548 if (ret != NULL)
1550 if (ret->package() != NULL)
1552 std::string dot_alias = "." + ret->package()->package_name();
1553 ret->package()->note_usage(dot_alias);
1555 return ret;
1559 // We do not look in the global namespace. If we did, the global
1560 // namespace would effectively hide names which were defined in
1561 // package scope which we have not yet seen. Instead,
1562 // define_global_names is called after parsing is over to connect
1563 // undefined names at package scope with names defined at global
1564 // scope.
1566 return NULL;
1569 // Look up a name in the current block, without searching enclosing
1570 // blocks.
1572 Named_object*
1573 Gogo::lookup_in_block(const std::string& name) const
1575 go_assert(!this->functions_.empty());
1576 go_assert(!this->functions_.back().blocks.empty());
1577 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1580 // Look up a name in the global namespace.
1582 Named_object*
1583 Gogo::lookup_global(const char* name) const
1585 return this->globals_->lookup(name);
1588 // Add an imported package.
1590 Package*
1591 Gogo::add_imported_package(const std::string& real_name,
1592 const std::string& alias_arg,
1593 bool is_alias_exported,
1594 const std::string& pkgpath,
1595 const std::string& pkgpath_symbol,
1596 Location location,
1597 bool* padd_to_globals)
1599 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1600 ret->set_package_name(real_name, location);
1602 *padd_to_globals = false;
1604 if (alias_arg == "_")
1606 else if (alias_arg == ".")
1608 *padd_to_globals = true;
1609 std::string dot_alias = "." + real_name;
1610 ret->add_alias(dot_alias, location);
1612 else
1614 std::string alias = alias_arg;
1615 if (alias.empty())
1617 alias = real_name;
1618 is_alias_exported = Lex::is_exported_name(alias);
1620 ret->add_alias(alias, location);
1621 alias = this->pack_hidden_name(alias, is_alias_exported);
1622 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1623 if (!no->is_package())
1624 return NULL;
1627 return ret;
1630 // Register a package. This package may or may not be imported. This
1631 // returns the Package structure for the package, creating if it
1632 // necessary. LOCATION is the location of the import statement that
1633 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1634 // for names in the package; it may be the empty string, in which case
1635 // we either get it later or make a guess when we need it.
1637 Package*
1638 Gogo::register_package(const std::string& pkgpath,
1639 const std::string& pkgpath_symbol, Location location)
1641 Package* package = NULL;
1642 std::pair<Packages::iterator, bool> ins =
1643 this->packages_.insert(std::make_pair(pkgpath, package));
1644 if (!ins.second)
1646 // We have seen this package name before.
1647 package = ins.first->second;
1648 go_assert(package != NULL && package->pkgpath() == pkgpath);
1649 if (!pkgpath_symbol.empty())
1650 package->set_pkgpath_symbol(pkgpath_symbol);
1651 if (Linemap::is_unknown_location(package->location()))
1652 package->set_location(location);
1654 else
1656 // First time we have seen this package name.
1657 package = new Package(pkgpath, pkgpath_symbol, location);
1658 go_assert(ins.first->second == NULL);
1659 ins.first->second = package;
1662 return package;
1665 // Return the pkgpath symbol for a package, given the pkgpath.
1667 std::string
1668 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath)
1670 Packages::iterator p = this->packages_.find(pkgpath);
1671 go_assert(p != this->packages_.end());
1672 return p->second->pkgpath_symbol();
1675 // Start compiling a function.
1677 Named_object*
1678 Gogo::start_function(const std::string& name, Function_type* type,
1679 bool add_method_to_type, Location location)
1681 bool at_top_level = this->functions_.empty();
1683 Block* block = new Block(NULL, location);
1685 Named_object* enclosing = (at_top_level
1686 ? NULL
1687 : this->functions_.back().function);
1689 Function* function = new Function(type, enclosing, block, location);
1691 if (type->is_method())
1693 const Typed_identifier* receiver = type->receiver();
1694 Variable* this_param = new Variable(receiver->type(), NULL, false,
1695 true, true, location);
1696 std::string rname = receiver->name();
1697 if (rname.empty() || Gogo::is_sink_name(rname))
1699 // We need to give receivers a name since they wind up in
1700 // DECL_ARGUMENTS. FIXME.
1701 static unsigned int count;
1702 char buf[50];
1703 snprintf(buf, sizeof buf, "r.%u", count);
1704 ++count;
1705 rname = buf;
1707 block->bindings()->add_variable(rname, NULL, this_param);
1710 const Typed_identifier_list* parameters = type->parameters();
1711 bool is_varargs = type->is_varargs();
1712 if (parameters != NULL)
1714 for (Typed_identifier_list::const_iterator p = parameters->begin();
1715 p != parameters->end();
1716 ++p)
1718 Variable* param = new Variable(p->type(), NULL, false, true, false,
1719 p->location());
1720 if (is_varargs && p + 1 == parameters->end())
1721 param->set_is_varargs_parameter();
1723 std::string pname = p->name();
1724 if (pname.empty() || Gogo::is_sink_name(pname))
1726 // We need to give parameters a name since they wind up
1727 // in DECL_ARGUMENTS. FIXME.
1728 static unsigned int count;
1729 char buf[50];
1730 snprintf(buf, sizeof buf, "p.%u", count);
1731 ++count;
1732 pname = buf;
1734 block->bindings()->add_variable(pname, NULL, param);
1738 function->create_result_variables(this);
1740 const std::string* pname;
1741 std::string nested_name;
1742 bool is_init = false;
1743 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1745 if ((type->parameters() != NULL && !type->parameters()->empty())
1746 || (type->results() != NULL && !type->results()->empty()))
1747 go_error_at(location,
1748 "func init must have no arguments and no return values");
1749 // There can be multiple "init" functions, so give them each a
1750 // different name.
1751 nested_name = this->init_function_name();
1752 pname = &nested_name;
1753 is_init = true;
1755 else if (!name.empty())
1756 pname = &name;
1757 else
1759 // Invent a name for a nested function.
1760 nested_name = this->nested_function_name();
1761 pname = &nested_name;
1764 Named_object* ret;
1765 if (Gogo::is_sink_name(*pname))
1767 std::string sname(this->sink_function_name());
1768 ret = Named_object::make_function(sname, NULL, function);
1769 ret->func_value()->set_is_sink();
1771 if (!type->is_method())
1772 ret = this->package_->bindings()->add_named_object(ret);
1773 else if (add_method_to_type)
1775 // We should report errors even for sink methods.
1776 Type* rtype = type->receiver()->type();
1777 // Avoid points_to and deref to avoid getting an error if
1778 // the type is not yet defined.
1779 if (rtype->classification() == Type::TYPE_POINTER)
1780 rtype = rtype->points_to();
1781 while (rtype->named_type() != NULL
1782 && rtype->named_type()->is_alias())
1783 rtype = rtype->named_type()->real_type()->forwarded();
1784 if (rtype->is_error_type())
1786 else if (rtype->named_type() != NULL)
1788 if (rtype->named_type()->named_object()->package() != NULL)
1789 go_error_at(type->receiver()->location(),
1790 "may not define methods on non-local type");
1792 else if (rtype->forward_declaration_type() != NULL)
1794 // Go ahead and add the method in case we need to report
1795 // an error when we see the definition.
1796 rtype->forward_declaration_type()->add_existing_method(ret);
1798 else
1799 go_error_at(type->receiver()->location(),
1800 ("invalid receiver type "
1801 "(receiver must be a named type)"));
1804 else if (!type->is_method())
1806 ret = this->package_->bindings()->add_function(*pname, NULL, function);
1807 if (!ret->is_function() || ret->func_value() != function)
1809 // Redefinition error. Invent a name to avoid knockon
1810 // errors.
1811 std::string rname(this->redefined_function_name());
1812 ret = this->package_->bindings()->add_function(rname, NULL, function);
1815 else
1817 if (!add_method_to_type)
1818 ret = Named_object::make_function(name, NULL, function);
1819 else
1821 go_assert(at_top_level);
1822 Type* rtype = type->receiver()->type();
1824 // We want to look through the pointer created by the
1825 // parser, without getting an error if the type is not yet
1826 // defined.
1827 if (rtype->classification() == Type::TYPE_POINTER)
1828 rtype = rtype->points_to();
1830 while (rtype->named_type() != NULL
1831 && rtype->named_type()->is_alias())
1832 rtype = rtype->named_type()->real_type()->forwarded();
1834 if (rtype->is_error_type())
1835 ret = Named_object::make_function(name, NULL, function);
1836 else if (rtype->named_type() != NULL)
1838 if (rtype->named_type()->named_object()->package() != NULL)
1840 go_error_at(type->receiver()->location(),
1841 "may not define methods on non-local type");
1842 ret = Named_object::make_function(name, NULL, function);
1844 else
1846 ret = rtype->named_type()->add_method(name, function);
1847 if (!ret->is_function())
1849 // Redefinition error.
1850 ret = Named_object::make_function(name, NULL, function);
1854 else if (rtype->forward_declaration_type() != NULL)
1856 Named_object* type_no =
1857 rtype->forward_declaration_type()->named_object();
1858 if (type_no->is_unknown())
1860 // If we are seeing methods it really must be a
1861 // type. Declare it as such. An alternative would
1862 // be to support lists of methods for unknown
1863 // expressions. Either way the error messages if
1864 // this is not a type are going to get confusing.
1865 Named_object* declared =
1866 this->declare_package_type(type_no->name(),
1867 type_no->location());
1868 go_assert(declared
1869 == type_no->unknown_value()->real_named_object());
1871 ret = rtype->forward_declaration_type()->add_method(name,
1872 function);
1874 else
1876 go_error_at(type->receiver()->location(),
1877 ("invalid receiver type (receiver must "
1878 "be a named type)"));
1879 ret = Named_object::make_function(name, NULL, function);
1882 this->package_->bindings()->add_method(ret);
1885 this->functions_.resize(this->functions_.size() + 1);
1886 Open_function& of(this->functions_.back());
1887 of.function = ret;
1888 of.blocks.push_back(block);
1890 if (is_init)
1892 this->init_functions_.push_back(ret);
1893 this->need_init_fn_ = true;
1896 return ret;
1899 // Finish compiling a function.
1901 void
1902 Gogo::finish_function(Location location)
1904 this->finish_block(location);
1905 go_assert(this->functions_.back().blocks.empty());
1906 this->functions_.pop_back();
1909 // Return the current function.
1911 Named_object*
1912 Gogo::current_function() const
1914 go_assert(!this->functions_.empty());
1915 return this->functions_.back().function;
1918 // Start a new block.
1920 void
1921 Gogo::start_block(Location location)
1923 go_assert(!this->functions_.empty());
1924 Block* block = new Block(this->current_block(), location);
1925 this->functions_.back().blocks.push_back(block);
1928 // Finish a block.
1930 Block*
1931 Gogo::finish_block(Location location)
1933 go_assert(!this->functions_.empty());
1934 go_assert(!this->functions_.back().blocks.empty());
1935 Block* block = this->functions_.back().blocks.back();
1936 this->functions_.back().blocks.pop_back();
1937 block->set_end_location(location);
1938 return block;
1941 // Add an erroneous name.
1943 Named_object*
1944 Gogo::add_erroneous_name(const std::string& name)
1946 return this->package_->bindings()->add_erroneous_name(name);
1949 // Add an unknown name.
1951 Named_object*
1952 Gogo::add_unknown_name(const std::string& name, Location location)
1954 return this->package_->bindings()->add_unknown_name(name, location);
1957 // Declare a function.
1959 Named_object*
1960 Gogo::declare_function(const std::string& name, Function_type* type,
1961 Location location)
1963 if (!type->is_method())
1964 return this->current_bindings()->add_function_declaration(name, NULL, type,
1965 location);
1966 else
1968 // We don't bother to add this to the list of global
1969 // declarations.
1970 Type* rtype = type->receiver()->type();
1972 // We want to look through the pointer created by the
1973 // parser, without getting an error if the type is not yet
1974 // defined.
1975 if (rtype->classification() == Type::TYPE_POINTER)
1976 rtype = rtype->points_to();
1978 if (rtype->is_error_type())
1979 return NULL;
1980 else if (rtype->named_type() != NULL)
1981 return rtype->named_type()->add_method_declaration(name, NULL, type,
1982 location);
1983 else if (rtype->forward_declaration_type() != NULL)
1985 Forward_declaration_type* ftype = rtype->forward_declaration_type();
1986 return ftype->add_method_declaration(name, NULL, type, location);
1988 else
1990 go_error_at(type->receiver()->location(),
1991 "invalid receiver type (receiver must be a named type)");
1992 return Named_object::make_erroneous_name(name);
1997 // Add a label definition.
1999 Label*
2000 Gogo::add_label_definition(const std::string& label_name,
2001 Location location)
2003 go_assert(!this->functions_.empty());
2004 Function* func = this->functions_.back().function->func_value();
2005 Label* label = func->add_label_definition(this, label_name, location);
2006 this->add_statement(Statement::make_label_statement(label, location));
2007 return label;
2010 // Add a label reference.
2012 Label*
2013 Gogo::add_label_reference(const std::string& label_name,
2014 Location location, bool issue_goto_errors)
2016 go_assert(!this->functions_.empty());
2017 Function* func = this->functions_.back().function->func_value();
2018 return func->add_label_reference(this, label_name, location,
2019 issue_goto_errors);
2022 // Return the current binding state.
2024 Bindings_snapshot*
2025 Gogo::bindings_snapshot(Location location)
2027 return new Bindings_snapshot(this->current_block(), location);
2030 // Add a statement.
2032 void
2033 Gogo::add_statement(Statement* statement)
2035 go_assert(!this->functions_.empty()
2036 && !this->functions_.back().blocks.empty());
2037 this->functions_.back().blocks.back()->add_statement(statement);
2040 // Add a block.
2042 void
2043 Gogo::add_block(Block* block, Location location)
2045 go_assert(!this->functions_.empty()
2046 && !this->functions_.back().blocks.empty());
2047 Statement* statement = Statement::make_block_statement(block, location);
2048 this->functions_.back().blocks.back()->add_statement(statement);
2051 // Add a constant.
2053 Named_object*
2054 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2055 int iota_value)
2057 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2060 // Add a type.
2062 void
2063 Gogo::add_type(const std::string& name, Type* type, Location location)
2065 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2066 location);
2067 if (!this->in_global_scope() && no->is_type())
2069 Named_object* f = this->functions_.back().function;
2070 unsigned int index;
2071 if (f->is_function())
2072 index = f->func_value()->new_local_type_index();
2073 else
2074 index = 0;
2075 no->type_value()->set_in_function(f, index);
2079 // Add a named type.
2081 void
2082 Gogo::add_named_type(Named_type* type)
2084 go_assert(this->in_global_scope());
2085 this->current_bindings()->add_named_type(type);
2088 // Declare a type.
2090 Named_object*
2091 Gogo::declare_type(const std::string& name, Location location)
2093 Bindings* bindings = this->current_bindings();
2094 Named_object* no = bindings->add_type_declaration(name, NULL, location);
2095 if (!this->in_global_scope() && no->is_type_declaration())
2097 Named_object* f = this->functions_.back().function;
2098 unsigned int index;
2099 if (f->is_function())
2100 index = f->func_value()->new_local_type_index();
2101 else
2102 index = 0;
2103 no->type_declaration_value()->set_in_function(f, index);
2105 return no;
2108 // Declare a type at the package level.
2110 Named_object*
2111 Gogo::declare_package_type(const std::string& name, Location location)
2113 return this->package_->bindings()->add_type_declaration(name, NULL, location);
2116 // Declare a function at the package level.
2118 Named_object*
2119 Gogo::declare_package_function(const std::string& name, Function_type* type,
2120 Location location)
2122 return this->package_->bindings()->add_function_declaration(name, NULL, type,
2123 location);
2126 // Define a type which was already declared.
2128 void
2129 Gogo::define_type(Named_object* no, Named_type* type)
2131 this->current_bindings()->define_type(no, type);
2134 // Add a variable.
2136 Named_object*
2137 Gogo::add_variable(const std::string& name, Variable* variable)
2139 Named_object* no = this->current_bindings()->add_variable(name, NULL,
2140 variable);
2142 // In a function the middle-end wants to see a DECL_EXPR node.
2143 if (no != NULL
2144 && no->is_variable()
2145 && !no->var_value()->is_parameter()
2146 && !this->functions_.empty())
2147 this->add_statement(Statement::make_variable_declaration(no));
2149 return no;
2152 // Add a sink--a reference to the blank identifier _.
2154 Named_object*
2155 Gogo::add_sink()
2157 return Named_object::make_sink();
2160 // Add a named object for a dot import.
2162 void
2163 Gogo::add_dot_import_object(Named_object* no)
2165 // If the name already exists, then it was defined in some file seen
2166 // earlier. If the earlier name is just a declaration, don't add
2167 // this name, because that will cause the previous declaration to
2168 // merge to this imported name, which should not happen. Just add
2169 // this name to the list of file block names to get appropriate
2170 // errors if we see a later definition.
2171 Named_object* e = this->package_->bindings()->lookup(no->name());
2172 if (e != NULL && e->package() == NULL)
2174 if (e->is_unknown())
2175 e = e->resolve();
2176 if (e->package() == NULL
2177 && (e->is_type_declaration()
2178 || e->is_function_declaration()
2179 || e->is_unknown()))
2181 this->add_file_block_name(no->name(), no->location());
2182 return;
2186 this->current_bindings()->add_named_object(no);
2189 // Add a linkname. This implements the go:linkname compiler directive.
2190 // We only support this for functions and function declarations.
2192 void
2193 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2194 const std::string& ext_name, Location loc)
2196 Named_object* no =
2197 this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2198 is_exported));
2199 if (no == NULL)
2200 go_error_at(loc, "%s is not defined", go_name.c_str());
2201 else if (no->is_function())
2202 no->func_value()->set_asm_name(ext_name);
2203 else if (no->is_function_declaration())
2204 no->func_declaration_value()->set_asm_name(ext_name);
2205 else
2206 go_error_at(loc,
2207 ("%s is not a function; "
2208 "//go:linkname is only supported for functions"),
2209 go_name.c_str());
2212 // Mark all local variables used. This is used when some types of
2213 // parse error occur.
2215 void
2216 Gogo::mark_locals_used()
2218 for (Open_functions::iterator pf = this->functions_.begin();
2219 pf != this->functions_.end();
2220 ++pf)
2222 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2223 pb != pf->blocks.end();
2224 ++pb)
2225 (*pb)->bindings()->mark_locals_used();
2229 // Record that we've seen an interface type.
2231 void
2232 Gogo::record_interface_type(Interface_type* itype)
2234 this->interface_types_.push_back(itype);
2237 // Define the global names. We do this only after parsing all the
2238 // input files, because the program might define the global names
2239 // itself.
2241 void
2242 Gogo::define_global_names()
2244 if (this->is_main_package())
2246 // Every Go program has to import the runtime package, so that
2247 // it is properly initialized.
2248 this->import_package("runtime", "_", false, false,
2249 Linemap::predeclared_location());
2252 for (Bindings::const_declarations_iterator p =
2253 this->globals_->begin_declarations();
2254 p != this->globals_->end_declarations();
2255 ++p)
2257 Named_object* global_no = p->second;
2258 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2259 Named_object* no = this->package_->bindings()->lookup(name);
2260 if (no == NULL)
2261 continue;
2262 no = no->resolve();
2263 if (no->is_type_declaration())
2265 if (global_no->is_type())
2267 if (no->type_declaration_value()->has_methods())
2269 for (std::vector<Named_object*>::const_iterator p =
2270 no->type_declaration_value()->methods()->begin();
2271 p != no->type_declaration_value()->methods()->end();
2272 p++)
2273 go_error_at((*p)->location(),
2274 "may not define methods on non-local type");
2276 no->set_type_value(global_no->type_value());
2278 else
2280 go_error_at(no->location(), "expected type");
2281 Type* errtype = Type::make_error_type();
2282 Named_object* err =
2283 Named_object::make_type("erroneous_type", NULL, errtype,
2284 Linemap::predeclared_location());
2285 no->set_type_value(err->type_value());
2288 else if (no->is_unknown())
2289 no->unknown_value()->set_real_named_object(global_no);
2292 // Give an error if any name is defined in both the package block
2293 // and the file block. For example, this can happen if one file
2294 // imports "fmt" and another file defines a global variable fmt.
2295 for (Bindings::const_declarations_iterator p =
2296 this->package_->bindings()->begin_declarations();
2297 p != this->package_->bindings()->end_declarations();
2298 ++p)
2300 if (p->second->is_unknown()
2301 && p->second->unknown_value()->real_named_object() == NULL)
2303 // No point in warning about an undefined name, as we will
2304 // get other errors later anyhow.
2305 continue;
2307 File_block_names::const_iterator pf =
2308 this->file_block_names_.find(p->second->name());
2309 if (pf != this->file_block_names_.end())
2311 std::string n = p->second->message_name();
2312 go_error_at(p->second->location(),
2313 "%qs defined as both imported name and global name",
2314 n.c_str());
2315 go_inform(pf->second, "%qs imported here", n.c_str());
2318 // No package scope identifier may be named "init".
2319 if (!p->second->is_function()
2320 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2322 go_error_at(p->second->location(),
2323 "cannot declare init - must be func");
2328 // Clear out names in file scope.
2330 void
2331 Gogo::clear_file_scope()
2333 this->package_->bindings()->clear_file_scope(this);
2335 // Warn about packages which were imported but not used.
2336 bool quiet = saw_errors();
2337 for (Packages::iterator p = this->packages_.begin();
2338 p != this->packages_.end();
2339 ++p)
2341 Package* package = p->second;
2342 if (package != this->package_ && !quiet)
2344 for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2345 p1 != package->aliases().end();
2346 ++p1)
2348 if (!p1->second->used())
2350 // Give a more refined error message if the alias name is known.
2351 std::string pkg_name = package->package_name();
2352 if (p1->first != pkg_name && p1->first[0] != '.')
2354 go_error_at(p1->second->location(),
2355 "imported and not used: %s as %s",
2356 Gogo::message_name(pkg_name).c_str(),
2357 Gogo::message_name(p1->first).c_str());
2359 else
2360 go_error_at(p1->second->location(),
2361 "imported and not used: %s",
2362 Gogo::message_name(pkg_name).c_str());
2366 package->clear_used();
2369 this->current_file_imported_unsafe_ = false;
2372 // Queue up a type specific function for later writing. These are
2373 // written out in write_specific_type_functions, called after the
2374 // parse tree is lowered.
2376 void
2377 Gogo::queue_specific_type_function(Type* type, Named_type* name, int64_t size,
2378 const std::string& hash_name,
2379 Function_type* hash_fntype,
2380 const std::string& equal_name,
2381 Function_type* equal_fntype)
2383 go_assert(!this->specific_type_functions_are_written_);
2384 go_assert(!this->in_global_scope());
2385 Specific_type_function* tsf = new Specific_type_function(type, name, size,
2386 hash_name,
2387 hash_fntype,
2388 equal_name,
2389 equal_fntype);
2390 this->specific_type_functions_.push_back(tsf);
2393 // Look for types which need specific hash or equality functions.
2395 class Specific_type_functions : public Traverse
2397 public:
2398 Specific_type_functions(Gogo* gogo)
2399 : Traverse(traverse_types),
2400 gogo_(gogo)
2404 type(Type*);
2406 private:
2407 Gogo* gogo_;
2411 Specific_type_functions::type(Type* t)
2413 Named_object* hash_fn;
2414 Named_object* equal_fn;
2415 switch (t->classification())
2417 case Type::TYPE_NAMED:
2419 Named_type* nt = t->named_type();
2420 if (nt->is_alias())
2421 return TRAVERSE_CONTINUE;
2422 if (t->needs_specific_type_functions(this->gogo_))
2423 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2425 // If this is a struct type, we don't want to make functions
2426 // for the unnamed struct.
2427 Type* rt = nt->real_type();
2428 if (rt->struct_type() == NULL)
2430 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2431 return TRAVERSE_EXIT;
2433 else
2435 // If this type is defined in another package, then we don't
2436 // need to worry about the unexported fields.
2437 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2438 const Struct_field_list* fields = rt->struct_type()->fields();
2439 for (Struct_field_list::const_iterator p = fields->begin();
2440 p != fields->end();
2441 ++p)
2443 if (is_defined_elsewhere
2444 && Gogo::is_hidden_name(p->field_name()))
2445 continue;
2446 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2447 return TRAVERSE_EXIT;
2451 return TRAVERSE_SKIP_COMPONENTS;
2454 case Type::TYPE_STRUCT:
2455 case Type::TYPE_ARRAY:
2456 if (t->needs_specific_type_functions(this->gogo_))
2457 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2458 break;
2460 default:
2461 break;
2464 return TRAVERSE_CONTINUE;
2467 // Write out type specific functions.
2469 void
2470 Gogo::write_specific_type_functions()
2472 Specific_type_functions stf(this);
2473 this->traverse(&stf);
2475 while (!this->specific_type_functions_.empty())
2477 Specific_type_function* tsf = this->specific_type_functions_.back();
2478 this->specific_type_functions_.pop_back();
2479 tsf->type->write_specific_type_functions(this, tsf->name, tsf->size,
2480 tsf->hash_name,
2481 tsf->hash_fntype,
2482 tsf->equal_name,
2483 tsf->equal_fntype);
2484 delete tsf;
2486 this->specific_type_functions_are_written_ = true;
2489 // Traverse the tree.
2491 void
2492 Gogo::traverse(Traverse* traverse)
2494 // Traverse the current package first for consistency. The other
2495 // packages will only contain imported types, constants, and
2496 // declarations.
2497 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2498 return;
2499 for (Packages::const_iterator p = this->packages_.begin();
2500 p != this->packages_.end();
2501 ++p)
2503 if (p->second != this->package_)
2505 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2506 break;
2511 // Add a type to verify. This is used for types of sink variables, in
2512 // order to give appropriate error messages.
2514 void
2515 Gogo::add_type_to_verify(Type* type)
2517 this->verify_types_.push_back(type);
2520 // Traversal class used to verify types.
2522 class Verify_types : public Traverse
2524 public:
2525 Verify_types()
2526 : Traverse(traverse_types)
2530 type(Type*);
2533 // Verify that a type is correct.
2536 Verify_types::type(Type* t)
2538 if (!t->verify())
2539 return TRAVERSE_SKIP_COMPONENTS;
2540 return TRAVERSE_CONTINUE;
2543 // Verify that all types are correct.
2545 void
2546 Gogo::verify_types()
2548 Verify_types traverse;
2549 this->traverse(&traverse);
2551 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2552 p != this->verify_types_.end();
2553 ++p)
2554 (*p)->verify();
2555 this->verify_types_.clear();
2558 // Traversal class used to lower parse tree.
2560 class Lower_parse_tree : public Traverse
2562 public:
2563 Lower_parse_tree(Gogo* gogo, Named_object* function)
2564 : Traverse(traverse_variables
2565 | traverse_constants
2566 | traverse_functions
2567 | traverse_statements
2568 | traverse_expressions),
2569 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2572 void
2573 set_inserter(const Statement_inserter* inserter)
2574 { this->inserter_ = *inserter; }
2577 variable(Named_object*);
2580 constant(Named_object*, bool);
2583 function(Named_object*);
2586 statement(Block*, size_t* pindex, Statement*);
2589 expression(Expression**);
2591 private:
2592 // General IR.
2593 Gogo* gogo_;
2594 // The function we are traversing.
2595 Named_object* function_;
2596 // Value to use for the predeclared constant iota.
2597 int iota_value_;
2598 // Current statement inserter for use by expressions.
2599 Statement_inserter inserter_;
2602 // Lower variables.
2605 Lower_parse_tree::variable(Named_object* no)
2607 if (!no->is_variable())
2608 return TRAVERSE_CONTINUE;
2610 if (no->is_variable() && no->var_value()->is_global())
2612 // Global variables can have loops in their initialization
2613 // expressions. This is handled in lower_init_expression.
2614 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2615 &this->inserter_);
2616 return TRAVERSE_CONTINUE;
2619 // This is a local variable. We are going to return
2620 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2621 // initialization expression when we reach the variable declaration
2622 // statement. However, that means that we need to traverse the type
2623 // ourselves.
2624 if (no->var_value()->has_type())
2626 Type* type = no->var_value()->type();
2627 if (type != NULL)
2629 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2630 return TRAVERSE_EXIT;
2633 go_assert(!no->var_value()->has_pre_init());
2635 return TRAVERSE_SKIP_COMPONENTS;
2638 // Lower constants. We handle constants specially so that we can set
2639 // the right value for the predeclared constant iota. This works in
2640 // conjunction with the way we lower Const_expression objects.
2643 Lower_parse_tree::constant(Named_object* no, bool)
2645 Named_constant* nc = no->const_value();
2647 // Don't get into trouble if the constant's initializer expression
2648 // refers to the constant itself.
2649 if (nc->lowering())
2650 return TRAVERSE_CONTINUE;
2651 nc->set_lowering();
2653 go_assert(this->iota_value_ == -1);
2654 this->iota_value_ = nc->iota_value();
2655 nc->traverse_expression(this);
2656 this->iota_value_ = -1;
2658 nc->clear_lowering();
2660 // We will traverse the expression a second time, but that will be
2661 // fast.
2663 return TRAVERSE_CONTINUE;
2666 // Lower the body of a function, and set the closure type. Record the
2667 // function while lowering it, so that we can pass it down when
2668 // lowering an expression.
2671 Lower_parse_tree::function(Named_object* no)
2673 no->func_value()->set_closure_type();
2675 go_assert(this->function_ == NULL);
2676 this->function_ = no;
2677 int t = no->func_value()->traverse(this);
2678 this->function_ = NULL;
2680 if (t == TRAVERSE_EXIT)
2681 return t;
2682 return TRAVERSE_SKIP_COMPONENTS;
2685 // Lower statement parse trees.
2688 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2690 // Because we explicitly traverse the statement's contents
2691 // ourselves, we want to skip block statements here. There is
2692 // nothing to lower in a block statement.
2693 if (sorig->is_block_statement())
2694 return TRAVERSE_CONTINUE;
2696 Statement_inserter hold_inserter(this->inserter_);
2697 this->inserter_ = Statement_inserter(block, pindex);
2699 // Lower the expressions first.
2700 int t = sorig->traverse_contents(this);
2701 if (t == TRAVERSE_EXIT)
2703 this->inserter_ = hold_inserter;
2704 return t;
2707 // Keep lowering until nothing changes.
2708 Statement* s = sorig;
2709 while (true)
2711 Statement* snew = s->lower(this->gogo_, this->function_, block,
2712 &this->inserter_);
2713 if (snew == s)
2714 break;
2715 s = snew;
2716 t = s->traverse_contents(this);
2717 if (t == TRAVERSE_EXIT)
2719 this->inserter_ = hold_inserter;
2720 return t;
2724 if (s != sorig)
2725 block->replace_statement(*pindex, s);
2727 this->inserter_ = hold_inserter;
2728 return TRAVERSE_SKIP_COMPONENTS;
2731 // Lower expression parse trees.
2734 Lower_parse_tree::expression(Expression** pexpr)
2736 // We have to lower all subexpressions first, so that we can get
2737 // their type if necessary. This is awkward, because we don't have
2738 // a postorder traversal pass.
2739 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2740 return TRAVERSE_EXIT;
2741 // Keep lowering until nothing changes.
2742 while (true)
2744 Expression* e = *pexpr;
2745 Expression* enew = e->lower(this->gogo_, this->function_,
2746 &this->inserter_, this->iota_value_);
2747 if (enew == e)
2748 break;
2749 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2750 return TRAVERSE_EXIT;
2751 *pexpr = enew;
2753 return TRAVERSE_SKIP_COMPONENTS;
2756 // Lower the parse tree. This is called after the parse is complete,
2757 // when all names should be resolved.
2759 void
2760 Gogo::lower_parse_tree()
2762 Lower_parse_tree lower_parse_tree(this, NULL);
2763 this->traverse(&lower_parse_tree);
2765 // There might be type definitions that involve expressions such as the
2766 // array length. Make sure to lower these expressions as well. Otherwise,
2767 // errors hidden within a type can introduce unexpected errors into later
2768 // passes.
2769 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2770 p != this->verify_types_.end();
2771 ++p)
2772 Type::traverse(*p, &lower_parse_tree);
2775 // Lower a block.
2777 void
2778 Gogo::lower_block(Named_object* function, Block* block)
2780 Lower_parse_tree lower_parse_tree(this, function);
2781 block->traverse(&lower_parse_tree);
2784 // Lower an expression. INSERTER may be NULL, in which case the
2785 // expression had better not need to create any temporaries.
2787 void
2788 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2789 Expression** pexpr)
2791 Lower_parse_tree lower_parse_tree(this, function);
2792 if (inserter != NULL)
2793 lower_parse_tree.set_inserter(inserter);
2794 lower_parse_tree.expression(pexpr);
2797 // Lower a constant. This is called when lowering a reference to a
2798 // constant. We have to make sure that the constant has already been
2799 // lowered.
2801 void
2802 Gogo::lower_constant(Named_object* no)
2804 go_assert(no->is_const());
2805 Lower_parse_tree lower(this, NULL);
2806 lower.constant(no, false);
2809 // Traverse the tree to create function descriptors as needed.
2811 class Create_function_descriptors : public Traverse
2813 public:
2814 Create_function_descriptors(Gogo* gogo)
2815 : Traverse(traverse_functions | traverse_expressions),
2816 gogo_(gogo)
2820 function(Named_object*);
2823 expression(Expression**);
2825 private:
2826 Gogo* gogo_;
2829 // Create a descriptor for every top-level exported function.
2832 Create_function_descriptors::function(Named_object* no)
2834 if (no->is_function()
2835 && no->func_value()->enclosing() == NULL
2836 && !no->func_value()->is_method()
2837 && !Gogo::is_hidden_name(no->name())
2838 && !Gogo::is_thunk(no))
2839 no->func_value()->descriptor(this->gogo_, no);
2841 return TRAVERSE_CONTINUE;
2844 // If we see a function referenced in any way other than calling it,
2845 // create a descriptor for it.
2848 Create_function_descriptors::expression(Expression** pexpr)
2850 Expression* expr = *pexpr;
2852 Func_expression* fe = expr->func_expression();
2853 if (fe != NULL)
2855 // We would not get here for a call to this function, so this is
2856 // a reference to a function other than calling it. We need a
2857 // descriptor.
2858 if (fe->closure() != NULL)
2859 return TRAVERSE_CONTINUE;
2860 Named_object* no = fe->named_object();
2861 if (no->is_function() && !no->func_value()->is_method())
2862 no->func_value()->descriptor(this->gogo_, no);
2863 else if (no->is_function_declaration()
2864 && !no->func_declaration_value()->type()->is_method()
2865 && !Linemap::is_predeclared_location(no->location()))
2866 no->func_declaration_value()->descriptor(this->gogo_, no);
2867 return TRAVERSE_CONTINUE;
2870 Bound_method_expression* bme = expr->bound_method_expression();
2871 if (bme != NULL)
2873 // We would not get here for a call to this method, so this is a
2874 // method value. We need to create a thunk.
2875 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
2876 bme->function());
2877 return TRAVERSE_CONTINUE;
2880 Interface_field_reference_expression* ifre =
2881 expr->interface_field_reference_expression();
2882 if (ifre != NULL)
2884 // We would not get here for a call to this interface method, so
2885 // this is a method value. We need to create a thunk.
2886 Interface_type* type = ifre->expr()->type()->interface_type();
2887 if (type != NULL)
2888 Interface_field_reference_expression::create_thunk(this->gogo_, type,
2889 ifre->name());
2890 return TRAVERSE_CONTINUE;
2893 Call_expression* ce = expr->call_expression();
2894 if (ce != NULL)
2896 Expression* fn = ce->fn();
2897 if (fn->func_expression() != NULL
2898 || fn->bound_method_expression() != NULL
2899 || fn->interface_field_reference_expression() != NULL)
2901 // Traverse the arguments but not the function.
2902 Expression_list* args = ce->args();
2903 if (args != NULL)
2905 if (args->traverse(this) == TRAVERSE_EXIT)
2906 return TRAVERSE_EXIT;
2908 return TRAVERSE_SKIP_COMPONENTS;
2912 return TRAVERSE_CONTINUE;
2915 // Create function descriptors as needed. We need a function
2916 // descriptor for all exported functions and for all functions that
2917 // are referenced without being called.
2919 void
2920 Gogo::create_function_descriptors()
2922 // Create a function descriptor for any exported function that is
2923 // declared in this package. This is so that we have a descriptor
2924 // for functions written in assembly. Gather the descriptors first
2925 // so that we don't add declarations while looping over them.
2926 std::vector<Named_object*> fndecls;
2927 Bindings* b = this->package_->bindings();
2928 for (Bindings::const_declarations_iterator p = b->begin_declarations();
2929 p != b->end_declarations();
2930 ++p)
2932 Named_object* no = p->second;
2933 if (no->is_function_declaration()
2934 && !no->func_declaration_value()->type()->is_method()
2935 && !Linemap::is_predeclared_location(no->location())
2936 && !Gogo::is_hidden_name(no->name()))
2937 fndecls.push_back(no);
2939 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
2940 p != fndecls.end();
2941 ++p)
2942 (*p)->func_declaration_value()->descriptor(this, *p);
2943 fndecls.clear();
2945 Create_function_descriptors cfd(this);
2946 this->traverse(&cfd);
2949 // Look for interface types to finalize methods of inherited
2950 // interfaces.
2952 class Finalize_methods : public Traverse
2954 public:
2955 Finalize_methods(Gogo* gogo)
2956 : Traverse(traverse_types),
2957 gogo_(gogo)
2961 type(Type*);
2963 private:
2964 Gogo* gogo_;
2967 // Finalize the methods of an interface type.
2970 Finalize_methods::type(Type* t)
2972 // Check the classification so that we don't finalize the methods
2973 // twice for a named interface type.
2974 switch (t->classification())
2976 case Type::TYPE_INTERFACE:
2977 t->interface_type()->finalize_methods();
2978 break;
2980 case Type::TYPE_NAMED:
2982 Named_type* nt = t->named_type();
2983 Type* rt = nt->real_type();
2984 if (rt->classification() != Type::TYPE_STRUCT)
2986 // Finalize the methods of the real type first.
2987 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2988 return TRAVERSE_EXIT;
2990 // Finalize the methods of this type.
2991 nt->finalize_methods(this->gogo_);
2993 else
2995 // We don't want to finalize the methods of a named struct
2996 // type, as the methods should be attached to the named
2997 // type, not the struct type. We just want to finalize
2998 // the field types.
3000 // It is possible that a field type refers indirectly to
3001 // this type, such as via a field with function type with
3002 // an argument or result whose type is this type. To
3003 // avoid the cycle, first finalize the methods of any
3004 // embedded types, which are the only types we need to
3005 // know to finalize the methods of this type.
3006 const Struct_field_list* fields = rt->struct_type()->fields();
3007 if (fields != NULL)
3009 for (Struct_field_list::const_iterator pf = fields->begin();
3010 pf != fields->end();
3011 ++pf)
3013 if (pf->is_anonymous())
3015 if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3016 return TRAVERSE_EXIT;
3021 // Finalize the methods of this type.
3022 nt->finalize_methods(this->gogo_);
3024 // Finalize all the struct fields.
3025 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3026 return TRAVERSE_EXIT;
3029 // If this type is defined in a different package, then finalize the
3030 // types of all the methods, since we won't see them otherwise.
3031 if (nt->named_object()->package() != NULL && nt->has_any_methods())
3033 const Methods* methods = nt->methods();
3034 for (Methods::const_iterator p = methods->begin();
3035 p != methods->end();
3036 ++p)
3038 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3039 return TRAVERSE_EXIT;
3043 // Finalize the types of all methods that are declared but not
3044 // defined, since we won't see the declarations otherwise.
3045 if (nt->named_object()->package() == NULL
3046 && nt->local_methods() != NULL)
3048 const Bindings* methods = nt->local_methods();
3049 for (Bindings::const_declarations_iterator p =
3050 methods->begin_declarations();
3051 p != methods->end_declarations();
3052 p++)
3054 if (p->second->is_function_declaration())
3056 Type* mt = p->second->func_declaration_value()->type();
3057 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3058 return TRAVERSE_EXIT;
3063 return TRAVERSE_SKIP_COMPONENTS;
3066 case Type::TYPE_STRUCT:
3067 // Traverse the field types first in case there is an embedded
3068 // field with methods that the struct should inherit.
3069 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3070 return TRAVERSE_EXIT;
3071 t->struct_type()->finalize_methods(this->gogo_);
3072 return TRAVERSE_SKIP_COMPONENTS;
3074 default:
3075 break;
3078 return TRAVERSE_CONTINUE;
3081 // Finalize method lists and build stub methods for types.
3083 void
3084 Gogo::finalize_methods()
3086 Finalize_methods finalize(this);
3087 this->traverse(&finalize);
3090 // Set types for unspecified variables and constants.
3092 void
3093 Gogo::determine_types()
3095 Bindings* bindings = this->current_bindings();
3096 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3097 p != bindings->end_definitions();
3098 ++p)
3100 if ((*p)->is_function())
3101 (*p)->func_value()->determine_types();
3102 else if ((*p)->is_variable())
3103 (*p)->var_value()->determine_type();
3104 else if ((*p)->is_const())
3105 (*p)->const_value()->determine_type();
3107 // See if a variable requires us to build an initialization
3108 // function. We know that we will see all global variables
3109 // here.
3110 if (!this->need_init_fn_ && (*p)->is_variable())
3112 Variable* variable = (*p)->var_value();
3114 // If this is a global variable which requires runtime
3115 // initialization, we need an initialization function.
3116 if (!variable->is_global())
3118 else if (variable->init() == NULL)
3120 else if (variable->type()->interface_type() != NULL)
3121 this->need_init_fn_ = true;
3122 else if (variable->init()->is_constant())
3124 else if (!variable->init()->is_composite_literal())
3125 this->need_init_fn_ = true;
3126 else if (variable->init()->is_nonconstant_composite_literal())
3127 this->need_init_fn_ = true;
3129 // If this is a global variable which holds a pointer value,
3130 // then we need an initialization function to register it as a
3131 // GC root.
3132 if (variable->is_global() && variable->type()->has_pointer())
3133 this->need_init_fn_ = true;
3137 // Determine the types of constants in packages.
3138 for (Packages::const_iterator p = this->packages_.begin();
3139 p != this->packages_.end();
3140 ++p)
3141 p->second->determine_types();
3144 // Traversal class used for type checking.
3146 class Check_types_traverse : public Traverse
3148 public:
3149 Check_types_traverse(Gogo* gogo)
3150 : Traverse(traverse_variables
3151 | traverse_constants
3152 | traverse_functions
3153 | traverse_statements
3154 | traverse_expressions),
3155 gogo_(gogo)
3159 variable(Named_object*);
3162 constant(Named_object*, bool);
3165 function(Named_object*);
3168 statement(Block*, size_t* pindex, Statement*);
3171 expression(Expression**);
3173 private:
3174 // General IR.
3175 Gogo* gogo_;
3178 // Check that a variable initializer has the right type.
3181 Check_types_traverse::variable(Named_object* named_object)
3183 if (named_object->is_variable())
3185 Variable* var = named_object->var_value();
3187 // Give error if variable type is not defined.
3188 var->type()->base();
3190 Expression* init = var->init();
3191 std::string reason;
3192 if (init != NULL
3193 && !Type::are_assignable(var->type(), init->type(), &reason))
3195 if (reason.empty())
3196 go_error_at(var->location(), "incompatible type in initialization");
3197 else
3198 go_error_at(var->location(),
3199 "incompatible type in initialization (%s)",
3200 reason.c_str());
3201 init = Expression::make_error(named_object->location());
3202 var->clear_init();
3204 else if (init != NULL
3205 && init->func_expression() != NULL)
3207 Named_object* no = init->func_expression()->named_object();
3208 Function_type* fntype;
3209 if (no->is_function())
3210 fntype = no->func_value()->type();
3211 else if (no->is_function_declaration())
3212 fntype = no->func_declaration_value()->type();
3213 else
3214 go_unreachable();
3216 // Builtin functions cannot be used as function values for variable
3217 // initialization.
3218 if (fntype->is_builtin())
3220 go_error_at(init->location(),
3221 "invalid use of special builtin function %qs; "
3222 "must be called",
3223 no->message_name().c_str());
3226 if (!var->is_used()
3227 && !var->is_global()
3228 && !var->is_parameter()
3229 && !var->is_receiver()
3230 && !var->type()->is_error()
3231 && (init == NULL || !init->is_error_expression())
3232 && !Lex::is_invalid_identifier(named_object->name()))
3233 go_error_at(var->location(), "%qs declared and not used",
3234 named_object->message_name().c_str());
3236 return TRAVERSE_CONTINUE;
3239 // Check that a constant initializer has the right type.
3242 Check_types_traverse::constant(Named_object* named_object, bool)
3244 Named_constant* constant = named_object->const_value();
3245 Type* ctype = constant->type();
3246 if (ctype->integer_type() == NULL
3247 && ctype->float_type() == NULL
3248 && ctype->complex_type() == NULL
3249 && !ctype->is_boolean_type()
3250 && !ctype->is_string_type())
3252 if (ctype->is_nil_type())
3253 go_error_at(constant->location(), "const initializer cannot be nil");
3254 else if (!ctype->is_error())
3255 go_error_at(constant->location(), "invalid constant type");
3256 constant->set_error();
3258 else if (!constant->expr()->is_constant())
3260 go_error_at(constant->expr()->location(), "expression is not constant");
3261 constant->set_error();
3263 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3264 NULL))
3266 go_error_at(constant->location(),
3267 "initialization expression has wrong type");
3268 constant->set_error();
3270 return TRAVERSE_CONTINUE;
3273 // There are no types to check in a function, but this is where we
3274 // issue warnings about labels which are defined but not referenced.
3277 Check_types_traverse::function(Named_object* no)
3279 no->func_value()->check_labels();
3280 return TRAVERSE_CONTINUE;
3283 // Check that types are valid in a statement.
3286 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3288 s->check_types(this->gogo_);
3289 return TRAVERSE_CONTINUE;
3292 // Check that types are valid in an expression.
3295 Check_types_traverse::expression(Expression** expr)
3297 (*expr)->check_types(this->gogo_);
3298 return TRAVERSE_CONTINUE;
3301 // Check that types are valid.
3303 void
3304 Gogo::check_types()
3306 Check_types_traverse traverse(this);
3307 this->traverse(&traverse);
3309 Bindings* bindings = this->current_bindings();
3310 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3311 p != bindings->end_declarations();
3312 ++p)
3314 // Also check the types in a function declaration's signature.
3315 Named_object* no = p->second;
3316 if (no->is_function_declaration())
3317 no->func_declaration_value()->check_types();
3321 // Check the types in a single block.
3323 void
3324 Gogo::check_types_in_block(Block* block)
3326 Check_types_traverse traverse(this);
3327 block->traverse(&traverse);
3330 // A traversal class used to find a single shortcut operator within an
3331 // expression.
3333 class Find_shortcut : public Traverse
3335 public:
3336 Find_shortcut()
3337 : Traverse(traverse_blocks
3338 | traverse_statements
3339 | traverse_expressions),
3340 found_(NULL)
3343 // A pointer to the expression which was found, or NULL if none was
3344 // found.
3345 Expression**
3346 found() const
3347 { return this->found_; }
3349 protected:
3351 block(Block*)
3352 { return TRAVERSE_SKIP_COMPONENTS; }
3355 statement(Block*, size_t*, Statement*)
3356 { return TRAVERSE_SKIP_COMPONENTS; }
3359 expression(Expression**);
3361 private:
3362 Expression** found_;
3365 // Find a shortcut expression.
3368 Find_shortcut::expression(Expression** pexpr)
3370 Expression* expr = *pexpr;
3371 Binary_expression* be = expr->binary_expression();
3372 if (be == NULL)
3373 return TRAVERSE_CONTINUE;
3374 Operator op = be->op();
3375 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3376 return TRAVERSE_CONTINUE;
3377 go_assert(this->found_ == NULL);
3378 this->found_ = pexpr;
3379 return TRAVERSE_EXIT;
3382 // A traversal class used to turn shortcut operators into explicit if
3383 // statements.
3385 class Shortcuts : public Traverse
3387 public:
3388 Shortcuts(Gogo* gogo)
3389 : Traverse(traverse_variables
3390 | traverse_statements),
3391 gogo_(gogo)
3394 protected:
3396 variable(Named_object*);
3399 statement(Block*, size_t*, Statement*);
3401 private:
3402 // Convert a shortcut operator.
3403 Statement*
3404 convert_shortcut(Block* enclosing, Expression** pshortcut);
3406 // The IR.
3407 Gogo* gogo_;
3410 // Remove shortcut operators in a single statement.
3413 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3415 // FIXME: This approach doesn't work for switch statements, because
3416 // we add the new statements before the whole switch when we need to
3417 // instead add them just before the switch expression. The right
3418 // fix is probably to lower switch statements with nonconstant cases
3419 // to a series of conditionals.
3420 if (s->switch_statement() != NULL)
3421 return TRAVERSE_CONTINUE;
3423 while (true)
3425 Find_shortcut find_shortcut;
3427 // If S is a variable declaration, then ordinary traversal won't
3428 // do anything. We want to explicitly traverse the
3429 // initialization expression if there is one.
3430 Variable_declaration_statement* vds = s->variable_declaration_statement();
3431 Expression* init = NULL;
3432 if (vds == NULL)
3433 s->traverse_contents(&find_shortcut);
3434 else
3436 init = vds->var()->var_value()->init();
3437 if (init == NULL)
3438 return TRAVERSE_CONTINUE;
3439 init->traverse(&init, &find_shortcut);
3441 Expression** pshortcut = find_shortcut.found();
3442 if (pshortcut == NULL)
3443 return TRAVERSE_CONTINUE;
3445 Statement* snew = this->convert_shortcut(block, pshortcut);
3446 block->insert_statement_before(*pindex, snew);
3447 ++*pindex;
3449 if (pshortcut == &init)
3450 vds->var()->var_value()->set_init(init);
3454 // Remove shortcut operators in the initializer of a global variable.
3457 Shortcuts::variable(Named_object* no)
3459 if (no->is_result_variable())
3460 return TRAVERSE_CONTINUE;
3461 Variable* var = no->var_value();
3462 Expression* init = var->init();
3463 if (!var->is_global() || init == NULL)
3464 return TRAVERSE_CONTINUE;
3466 while (true)
3468 Find_shortcut find_shortcut;
3469 init->traverse(&init, &find_shortcut);
3470 Expression** pshortcut = find_shortcut.found();
3471 if (pshortcut == NULL)
3472 return TRAVERSE_CONTINUE;
3474 Statement* snew = this->convert_shortcut(NULL, pshortcut);
3475 var->add_preinit_statement(this->gogo_, snew);
3476 if (pshortcut == &init)
3477 var->set_init(init);
3481 // Given an expression which uses a shortcut operator, return a
3482 // statement which implements it, and update *PSHORTCUT accordingly.
3484 Statement*
3485 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3487 Binary_expression* shortcut = (*pshortcut)->binary_expression();
3488 Expression* left = shortcut->left();
3489 Expression* right = shortcut->right();
3490 Location loc = shortcut->location();
3492 Block* retblock = new Block(enclosing, loc);
3493 retblock->set_end_location(loc);
3495 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3496 left, loc);
3497 retblock->add_statement(ts);
3499 Block* block = new Block(retblock, loc);
3500 block->set_end_location(loc);
3501 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
3502 Statement* assign = Statement::make_assignment(tmpref, right, loc);
3503 block->add_statement(assign);
3505 Expression* cond = Expression::make_temporary_reference(ts, loc);
3506 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
3507 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3509 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
3510 loc);
3511 retblock->add_statement(if_statement);
3513 *pshortcut = Expression::make_temporary_reference(ts, loc);
3515 delete shortcut;
3517 // Now convert any shortcut operators in LEFT and RIGHT.
3518 Shortcuts shortcuts(this->gogo_);
3519 retblock->traverse(&shortcuts);
3521 return Statement::make_block_statement(retblock, loc);
3524 // Turn shortcut operators into explicit if statements. Doing this
3525 // considerably simplifies the order of evaluation rules.
3527 void
3528 Gogo::remove_shortcuts()
3530 Shortcuts shortcuts(this);
3531 this->traverse(&shortcuts);
3534 // A traversal class which finds all the expressions which must be
3535 // evaluated in order within a statement or larger expression. This
3536 // is used to implement the rules about order of evaluation.
3538 class Find_eval_ordering : public Traverse
3540 private:
3541 typedef std::vector<Expression**> Expression_pointers;
3543 public:
3544 Find_eval_ordering()
3545 : Traverse(traverse_blocks
3546 | traverse_statements
3547 | traverse_expressions),
3548 exprs_()
3551 size_t
3552 size() const
3553 { return this->exprs_.size(); }
3555 typedef Expression_pointers::const_iterator const_iterator;
3557 const_iterator
3558 begin() const
3559 { return this->exprs_.begin(); }
3561 const_iterator
3562 end() const
3563 { return this->exprs_.end(); }
3565 protected:
3567 block(Block*)
3568 { return TRAVERSE_SKIP_COMPONENTS; }
3571 statement(Block*, size_t*, Statement*)
3572 { return TRAVERSE_SKIP_COMPONENTS; }
3575 expression(Expression**);
3577 private:
3578 // A list of pointers to expressions with side-effects.
3579 Expression_pointers exprs_;
3582 // If an expression must be evaluated in order, put it on the list.
3585 Find_eval_ordering::expression(Expression** expression_pointer)
3587 // We have to look at subexpressions before this one.
3588 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3589 return TRAVERSE_EXIT;
3590 if ((*expression_pointer)->must_eval_in_order())
3591 this->exprs_.push_back(expression_pointer);
3592 return TRAVERSE_SKIP_COMPONENTS;
3595 // A traversal class for ordering evaluations.
3597 class Order_eval : public Traverse
3599 public:
3600 Order_eval(Gogo* gogo)
3601 : Traverse(traverse_variables
3602 | traverse_statements),
3603 gogo_(gogo)
3607 variable(Named_object*);
3610 statement(Block*, size_t*, Statement*);
3612 private:
3613 // The IR.
3614 Gogo* gogo_;
3617 // Implement the order of evaluation rules for a statement.
3620 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3622 // FIXME: This approach doesn't work for switch statements, because
3623 // we add the new statements before the whole switch when we need to
3624 // instead add them just before the switch expression. The right
3625 // fix is probably to lower switch statements with nonconstant cases
3626 // to a series of conditionals.
3627 if (stmt->switch_statement() != NULL)
3628 return TRAVERSE_CONTINUE;
3630 Find_eval_ordering find_eval_ordering;
3632 // If S is a variable declaration, then ordinary traversal won't do
3633 // anything. We want to explicitly traverse the initialization
3634 // expression if there is one.
3635 Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3636 Expression* init = NULL;
3637 Expression* orig_init = NULL;
3638 if (vds == NULL)
3639 stmt->traverse_contents(&find_eval_ordering);
3640 else
3642 init = vds->var()->var_value()->init();
3643 if (init == NULL)
3644 return TRAVERSE_CONTINUE;
3645 orig_init = init;
3647 // It might seem that this could be
3648 // init->traverse_subexpressions. Unfortunately that can fail
3649 // in a case like
3650 // var err os.Error
3651 // newvar, err := call(arg())
3652 // Here newvar will have an init of call result 0 of
3653 // call(arg()). If we only traverse subexpressions, we will
3654 // only find arg(), and we won't bother to move anything out.
3655 // Then we get to the assignment to err, we will traverse the
3656 // whole statement, and this time we will find both call() and
3657 // arg(), and so we will move them out. This will cause them to
3658 // be put into temporary variables before the assignment to err
3659 // but after the declaration of newvar. To avoid that problem,
3660 // we traverse the entire expression here.
3661 Expression::traverse(&init, &find_eval_ordering);
3664 size_t c = find_eval_ordering.size();
3665 if (c == 0)
3666 return TRAVERSE_CONTINUE;
3668 // If there is only one expression with a side-effect, we can
3669 // usually leave it in place.
3670 if (c == 1)
3672 switch (stmt->classification())
3674 case Statement::STATEMENT_ASSIGNMENT:
3675 // For an assignment statement, we need to evaluate an
3676 // expression on the right hand side before we evaluate any
3677 // index expression on the left hand side, so for that case
3678 // we always move the expression. Otherwise we mishandle
3679 // m[0] = len(m) where m is a map.
3680 break;
3682 case Statement::STATEMENT_EXPRESSION:
3684 // If this is a call statement that doesn't return any
3685 // values, it will not have been counted as a value to
3686 // move. We need to move any subexpressions in case they
3687 // are themselves call statements that require passing a
3688 // closure.
3689 Expression* expr = stmt->expression_statement()->expr();
3690 if (expr->call_expression() != NULL
3691 && expr->call_expression()->result_count() == 0)
3692 break;
3693 return TRAVERSE_CONTINUE;
3696 default:
3697 // We can leave the expression in place.
3698 return TRAVERSE_CONTINUE;
3702 bool is_thunk = stmt->thunk_statement() != NULL;
3703 Expression_statement* es = stmt->expression_statement();
3704 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3705 p != find_eval_ordering.end();
3706 ++p)
3708 Expression** pexpr = *p;
3710 // The last expression in a thunk will be the call passed to go
3711 // or defer, which we must not evaluate early.
3712 if (is_thunk && p + 1 == find_eval_ordering.end())
3713 break;
3715 Location loc = (*pexpr)->location();
3716 Statement* s;
3717 if ((*pexpr)->call_expression() == NULL
3718 || (*pexpr)->call_expression()->result_count() < 2)
3720 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3721 loc);
3722 s = ts;
3723 *pexpr = Expression::make_temporary_reference(ts, loc);
3725 else
3727 // A call expression which returns multiple results needs to
3728 // be handled specially. We can't create a temporary
3729 // because there is no type to give it. Any actual uses of
3730 // the values will be done via Call_result_expressions.
3732 // Since a given call expression can be shared by multiple
3733 // Call_result_expressions, avoid hoisting the call the
3734 // second time we see it here. In addition, don't try to
3735 // hoist the top-level multi-return call in the statement,
3736 // since doing this would result a tree with more than one copy
3737 // of the call.
3738 if (this->remember_expression(*pexpr))
3739 s = NULL;
3740 else if (es != NULL && *pexpr == es->expr())
3741 s = NULL;
3742 else
3743 s = Statement::make_statement(*pexpr, true);
3746 if (s != NULL)
3748 block->insert_statement_before(*pindex, s);
3749 ++*pindex;
3753 if (init != orig_init)
3754 vds->var()->var_value()->set_init(init);
3756 return TRAVERSE_CONTINUE;
3759 // Implement the order of evaluation rules for the initializer of a
3760 // global variable.
3763 Order_eval::variable(Named_object* no)
3765 if (no->is_result_variable())
3766 return TRAVERSE_CONTINUE;
3767 Variable* var = no->var_value();
3768 Expression* init = var->init();
3769 if (!var->is_global() || init == NULL)
3770 return TRAVERSE_CONTINUE;
3772 Find_eval_ordering find_eval_ordering;
3773 Expression::traverse(&init, &find_eval_ordering);
3775 if (find_eval_ordering.size() <= 1)
3777 // If there is only one expression with a side-effect, we can
3778 // leave it in place.
3779 return TRAVERSE_SKIP_COMPONENTS;
3782 Expression* orig_init = init;
3784 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3785 p != find_eval_ordering.end();
3786 ++p)
3788 Expression** pexpr = *p;
3789 Location loc = (*pexpr)->location();
3790 Statement* s;
3791 if ((*pexpr)->call_expression() == NULL
3792 || (*pexpr)->call_expression()->result_count() < 2)
3794 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3795 loc);
3796 s = ts;
3797 *pexpr = Expression::make_temporary_reference(ts, loc);
3799 else
3801 // A call expression which returns multiple results needs to
3802 // be handled specially.
3803 s = Statement::make_statement(*pexpr, true);
3805 var->add_preinit_statement(this->gogo_, s);
3808 if (init != orig_init)
3809 var->set_init(init);
3811 return TRAVERSE_SKIP_COMPONENTS;
3814 // Use temporary variables to implement the order of evaluation rules.
3816 void
3817 Gogo::order_evaluations()
3819 Order_eval order_eval(this);
3820 this->traverse(&order_eval);
3823 // Traversal to flatten parse tree after order of evaluation rules are applied.
3825 class Flatten : public Traverse
3827 public:
3828 Flatten(Gogo* gogo, Named_object* function)
3829 : Traverse(traverse_variables
3830 | traverse_functions
3831 | traverse_statements
3832 | traverse_expressions),
3833 gogo_(gogo), function_(function), inserter_()
3836 void
3837 set_inserter(const Statement_inserter* inserter)
3838 { this->inserter_ = *inserter; }
3841 variable(Named_object*);
3844 function(Named_object*);
3847 statement(Block*, size_t* pindex, Statement*);
3850 expression(Expression**);
3852 private:
3853 // General IR.
3854 Gogo* gogo_;
3855 // The function we are traversing.
3856 Named_object* function_;
3857 // Current statement inserter for use by expressions.
3858 Statement_inserter inserter_;
3861 // Flatten variables.
3864 Flatten::variable(Named_object* no)
3866 if (!no->is_variable())
3867 return TRAVERSE_CONTINUE;
3869 if (no->is_variable() && no->var_value()->is_global())
3871 // Global variables can have loops in their initialization
3872 // expressions. This is handled in flatten_init_expression.
3873 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
3874 &this->inserter_);
3875 return TRAVERSE_CONTINUE;
3878 go_assert(!no->var_value()->has_pre_init());
3880 return TRAVERSE_SKIP_COMPONENTS;
3883 // Flatten the body of a function. Record the function while flattening it,
3884 // so that we can pass it down when flattening an expression.
3887 Flatten::function(Named_object* no)
3889 go_assert(this->function_ == NULL);
3890 this->function_ = no;
3891 int t = no->func_value()->traverse(this);
3892 this->function_ = NULL;
3894 if (t == TRAVERSE_EXIT)
3895 return t;
3896 return TRAVERSE_SKIP_COMPONENTS;
3899 // Flatten statement parse trees.
3902 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
3904 // Because we explicitly traverse the statement's contents
3905 // ourselves, we want to skip block statements here. There is
3906 // nothing to flatten in a block statement.
3907 if (sorig->is_block_statement())
3908 return TRAVERSE_CONTINUE;
3910 Statement_inserter hold_inserter(this->inserter_);
3911 this->inserter_ = Statement_inserter(block, pindex);
3913 // Flatten the expressions first.
3914 int t = sorig->traverse_contents(this);
3915 if (t == TRAVERSE_EXIT)
3917 this->inserter_ = hold_inserter;
3918 return t;
3921 // Keep flattening until nothing changes.
3922 Statement* s = sorig;
3923 while (true)
3925 Statement* snew = s->flatten(this->gogo_, this->function_, block,
3926 &this->inserter_);
3927 if (snew == s)
3928 break;
3929 s = snew;
3930 t = s->traverse_contents(this);
3931 if (t == TRAVERSE_EXIT)
3933 this->inserter_ = hold_inserter;
3934 return t;
3938 if (s != sorig)
3939 block->replace_statement(*pindex, s);
3941 this->inserter_ = hold_inserter;
3942 return TRAVERSE_SKIP_COMPONENTS;
3945 // Flatten expression parse trees.
3948 Flatten::expression(Expression** pexpr)
3950 // Keep flattening until nothing changes.
3951 while (true)
3953 Expression* e = *pexpr;
3954 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
3955 return TRAVERSE_EXIT;
3957 Expression* enew = e->flatten(this->gogo_, this->function_,
3958 &this->inserter_);
3959 if (enew == e)
3960 break;
3961 *pexpr = enew;
3963 return TRAVERSE_SKIP_COMPONENTS;
3966 // Flatten a block.
3968 void
3969 Gogo::flatten_block(Named_object* function, Block* block)
3971 Flatten flatten(this, function);
3972 block->traverse(&flatten);
3975 // Flatten an expression. INSERTER may be NULL, in which case the
3976 // expression had better not need to create any temporaries.
3978 void
3979 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
3980 Expression** pexpr)
3982 Flatten flatten(this, function);
3983 if (inserter != NULL)
3984 flatten.set_inserter(inserter);
3985 flatten.expression(pexpr);
3988 void
3989 Gogo::flatten()
3991 Flatten flatten(this, NULL);
3992 this->traverse(&flatten);
3995 // Traversal to convert calls to the predeclared recover function to
3996 // pass in an argument indicating whether it can recover from a panic
3997 // or not.
3999 class Convert_recover : public Traverse
4001 public:
4002 Convert_recover(Named_object* arg)
4003 : Traverse(traverse_expressions),
4004 arg_(arg)
4007 protected:
4009 expression(Expression**);
4011 private:
4012 // The argument to pass to the function.
4013 Named_object* arg_;
4016 // Convert calls to recover.
4019 Convert_recover::expression(Expression** pp)
4021 Call_expression* ce = (*pp)->call_expression();
4022 if (ce != NULL && ce->is_recover_call())
4023 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4024 ce->location()));
4025 return TRAVERSE_CONTINUE;
4028 // Traversal for build_recover_thunks.
4030 class Build_recover_thunks : public Traverse
4032 public:
4033 Build_recover_thunks(Gogo* gogo)
4034 : Traverse(traverse_functions),
4035 gogo_(gogo)
4039 function(Named_object*);
4041 private:
4042 Expression*
4043 can_recover_arg(Location);
4045 // General IR.
4046 Gogo* gogo_;
4049 // If this function calls recover, turn it into a thunk.
4052 Build_recover_thunks::function(Named_object* orig_no)
4054 Function* orig_func = orig_no->func_value();
4055 if (!orig_func->calls_recover()
4056 || orig_func->is_recover_thunk()
4057 || orig_func->has_recover_thunk())
4058 return TRAVERSE_CONTINUE;
4060 Gogo* gogo = this->gogo_;
4061 Location location = orig_func->location();
4063 static int count;
4064 char buf[50];
4066 Function_type* orig_fntype = orig_func->type();
4067 Typed_identifier_list* new_params = new Typed_identifier_list();
4068 std::string receiver_name;
4069 if (orig_fntype->is_method())
4071 const Typed_identifier* receiver = orig_fntype->receiver();
4072 snprintf(buf, sizeof buf, "rt.%u", count);
4073 ++count;
4074 receiver_name = buf;
4075 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4076 receiver->location()));
4078 const Typed_identifier_list* orig_params = orig_fntype->parameters();
4079 if (orig_params != NULL && !orig_params->empty())
4081 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4082 p != orig_params->end();
4083 ++p)
4085 snprintf(buf, sizeof buf, "pt.%u", count);
4086 ++count;
4087 new_params->push_back(Typed_identifier(buf, p->type(),
4088 p->location()));
4091 snprintf(buf, sizeof buf, "pr.%u", count);
4092 ++count;
4093 std::string can_recover_name = buf;
4094 new_params->push_back(Typed_identifier(can_recover_name,
4095 Type::lookup_bool_type(),
4096 orig_fntype->location()));
4098 const Typed_identifier_list* orig_results = orig_fntype->results();
4099 Typed_identifier_list* new_results;
4100 if (orig_results == NULL || orig_results->empty())
4101 new_results = NULL;
4102 else
4104 new_results = new Typed_identifier_list();
4105 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4106 p != orig_results->end();
4107 ++p)
4108 new_results->push_back(Typed_identifier("", p->type(), p->location()));
4111 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4112 new_results,
4113 orig_fntype->location());
4114 if (orig_fntype->is_varargs())
4115 new_fntype->set_is_varargs();
4117 Type* rtype = NULL;
4118 if (orig_fntype->is_method())
4119 rtype = orig_fntype->receiver()->type();
4120 std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4121 Named_object *new_no = gogo->start_function(name, new_fntype, false,
4122 location);
4123 Function *new_func = new_no->func_value();
4124 if (orig_func->enclosing() != NULL)
4125 new_func->set_enclosing(orig_func->enclosing());
4127 // We build the code for the original function attached to the new
4128 // function, and then swap the original and new function bodies.
4129 // This means that existing references to the original function will
4130 // then refer to the new function. That makes this code a little
4131 // confusing, in that the reference to NEW_NO really refers to the
4132 // other function, not the one we are building.
4134 Expression* closure = NULL;
4135 if (orig_func->needs_closure())
4137 // For the new function we are creating, declare a new parameter
4138 // variable NEW_CLOSURE_NO and set it to be the closure variable
4139 // of the function. This will be set to the closure value
4140 // passed in by the caller. Then pass a reference to this
4141 // variable as the closure value when calling the original
4142 // function. In other words, simply pass the closure value
4143 // through the thunk we are creating.
4144 Named_object* orig_closure_no = orig_func->closure_var();
4145 Variable* orig_closure_var = orig_closure_no->var_value();
4146 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4147 false, false, location);
4148 new_var->set_is_closure();
4149 snprintf(buf, sizeof buf, "closure.%u", count);
4150 ++count;
4151 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4152 new_var);
4153 new_func->set_closure_var(new_closure_no);
4154 closure = Expression::make_var_reference(new_closure_no, location);
4157 Expression* fn = Expression::make_func_reference(new_no, closure, location);
4159 Expression_list* args = new Expression_list();
4160 if (new_params != NULL)
4162 // Note that we skip the last parameter, which is the boolean
4163 // indicating whether recover can succed.
4164 for (Typed_identifier_list::const_iterator p = new_params->begin();
4165 p + 1 != new_params->end();
4166 ++p)
4168 Named_object* p_no = gogo->lookup(p->name(), NULL);
4169 go_assert(p_no != NULL
4170 && p_no->is_variable()
4171 && p_no->var_value()->is_parameter());
4172 args->push_back(Expression::make_var_reference(p_no, location));
4175 args->push_back(this->can_recover_arg(location));
4177 gogo->start_block(location);
4179 Call_expression* call = Expression::make_call(fn, args, false, location);
4181 // Any varargs call has already been lowered.
4182 call->set_varargs_are_lowered();
4184 Statement* s = Statement::make_return_from_call(call, location);
4185 s->determine_types();
4186 gogo->add_statement(s);
4188 Block* b = gogo->finish_block(location);
4190 gogo->add_block(b, location);
4192 // Lower the call in case it returns multiple results.
4193 gogo->lower_block(new_no, b);
4195 gogo->finish_function(location);
4197 // Swap the function bodies and types.
4198 new_func->swap_for_recover(orig_func);
4199 orig_func->set_is_recover_thunk();
4200 new_func->set_calls_recover();
4201 new_func->set_has_recover_thunk();
4203 Bindings* orig_bindings = orig_func->block()->bindings();
4204 Bindings* new_bindings = new_func->block()->bindings();
4205 if (orig_fntype->is_method())
4207 // We changed the receiver to be a regular parameter. We have
4208 // to update the binding accordingly in both functions.
4209 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4210 go_assert(orig_rec_no != NULL
4211 && orig_rec_no->is_variable()
4212 && !orig_rec_no->var_value()->is_receiver());
4213 orig_rec_no->var_value()->set_is_receiver();
4215 std::string new_receiver_name(orig_fntype->receiver()->name());
4216 if (new_receiver_name.empty())
4218 // Find the receiver. It was named "r.NNN" in
4219 // Gogo::start_function.
4220 for (Bindings::const_definitions_iterator p =
4221 new_bindings->begin_definitions();
4222 p != new_bindings->end_definitions();
4223 ++p)
4225 const std::string& pname((*p)->name());
4226 if (pname[0] == 'r' && pname[1] == '.')
4228 new_receiver_name = pname;
4229 break;
4232 go_assert(!new_receiver_name.empty());
4234 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4235 if (new_rec_no == NULL)
4236 go_assert(saw_errors());
4237 else
4239 go_assert(new_rec_no->is_variable()
4240 && new_rec_no->var_value()->is_receiver());
4241 new_rec_no->var_value()->set_is_not_receiver();
4245 // Because we flipped blocks but not types, the can_recover
4246 // parameter appears in the (now) old bindings as a parameter.
4247 // Change it to a local variable, whereupon it will be discarded.
4248 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4249 go_assert(can_recover_no != NULL
4250 && can_recover_no->is_variable()
4251 && can_recover_no->var_value()->is_parameter());
4252 orig_bindings->remove_binding(can_recover_no);
4254 // Add the can_recover argument to the (now) new bindings, and
4255 // attach it to any recover statements.
4256 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4257 false, true, false, location);
4258 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4259 can_recover_var);
4260 Convert_recover convert_recover(can_recover_no);
4261 new_func->traverse(&convert_recover);
4263 // Update the function pointers in any named results.
4264 new_func->update_result_variables();
4265 orig_func->update_result_variables();
4267 return TRAVERSE_CONTINUE;
4270 // Return the expression to pass for the .can_recover parameter to the
4271 // new function. This indicates whether a call to recover may return
4272 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4274 Expression*
4275 Build_recover_thunks::can_recover_arg(Location location)
4277 static Named_object* builtin_return_address;
4278 if (builtin_return_address == NULL)
4279 builtin_return_address =
4280 Gogo::declare_builtin_rf_address("__builtin_return_address");
4282 static Named_object* can_recover;
4283 if (can_recover == NULL)
4285 const Location bloc = Linemap::predeclared_location();
4286 Typed_identifier_list* param_types = new Typed_identifier_list();
4287 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4288 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
4289 Type* boolean_type = Type::lookup_bool_type();
4290 Typed_identifier_list* results = new Typed_identifier_list();
4291 results->push_back(Typed_identifier("", boolean_type, bloc));
4292 Function_type* fntype = Type::make_function_type(NULL, param_types,
4293 results, bloc);
4294 can_recover =
4295 Named_object::make_function_declaration("runtime_canrecover",
4296 NULL, fntype, bloc);
4297 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4300 Expression* fn = Expression::make_func_reference(builtin_return_address,
4301 NULL, location);
4303 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4304 Expression_list *args = new Expression_list();
4305 args->push_back(zexpr);
4307 Expression* call = Expression::make_call(fn, args, false, location);
4309 args = new Expression_list();
4310 args->push_back(call);
4312 fn = Expression::make_func_reference(can_recover, NULL, location);
4313 return Expression::make_call(fn, args, false, location);
4316 // Build thunks for functions which call recover. We build a new
4317 // function with an extra parameter, which is whether a call to
4318 // recover can succeed. We then move the body of this function to
4319 // that one. We then turn this function into a thunk which calls the
4320 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4321 // The function will be marked as not splitting the stack. This will
4322 // cooperate with the implementation of defer to make recover do the
4323 // right thing.
4325 void
4326 Gogo::build_recover_thunks()
4328 Build_recover_thunks build_recover_thunks(this);
4329 this->traverse(&build_recover_thunks);
4332 // Return a declaration for __builtin_return_address or
4333 // __builtin_frame_address.
4335 Named_object*
4336 Gogo::declare_builtin_rf_address(const char* name)
4338 const Location bloc = Linemap::predeclared_location();
4340 Typed_identifier_list* param_types = new Typed_identifier_list();
4341 Type* uint32_type = Type::lookup_integer_type("uint32");
4342 param_types->push_back(Typed_identifier("l", uint32_type, bloc));
4344 Typed_identifier_list* return_types = new Typed_identifier_list();
4345 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4346 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4348 Function_type* fntype = Type::make_function_type(NULL, param_types,
4349 return_types, bloc);
4350 Named_object* ret = Named_object::make_function_declaration(name, NULL,
4351 fntype, bloc);
4352 ret->func_declaration_value()->set_asm_name(name);
4353 return ret;
4356 // Build a call to the runtime error function.
4358 Expression*
4359 Gogo::runtime_error(int code, Location location)
4361 Type* int32_type = Type::lookup_integer_type("int32");
4362 Expression* code_expr = Expression::make_integer_ul(code, int32_type,
4363 location);
4364 return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4367 // Look for named types to see whether we need to create an interface
4368 // method table.
4370 class Build_method_tables : public Traverse
4372 public:
4373 Build_method_tables(Gogo* gogo,
4374 const std::vector<Interface_type*>& interfaces)
4375 : Traverse(traverse_types),
4376 gogo_(gogo), interfaces_(interfaces)
4380 type(Type*);
4382 private:
4383 // The IR.
4384 Gogo* gogo_;
4385 // A list of locally defined interfaces which have hidden methods.
4386 const std::vector<Interface_type*>& interfaces_;
4389 // Build all required interface method tables for types. We need to
4390 // ensure that we have an interface method table for every interface
4391 // which has a hidden method, for every named type which implements
4392 // that interface. Normally we can just build interface method tables
4393 // as we need them. However, in some cases we can require an
4394 // interface method table for an interface defined in a different
4395 // package for a type defined in that package. If that interface and
4396 // type both use a hidden method, that is OK. However, we will not be
4397 // able to build that interface method table when we need it, because
4398 // the type's hidden method will be static. So we have to build it
4399 // here, and just refer it from other packages as needed.
4401 void
4402 Gogo::build_interface_method_tables()
4404 if (saw_errors())
4405 return;
4407 std::vector<Interface_type*> hidden_interfaces;
4408 hidden_interfaces.reserve(this->interface_types_.size());
4409 for (std::vector<Interface_type*>::const_iterator pi =
4410 this->interface_types_.begin();
4411 pi != this->interface_types_.end();
4412 ++pi)
4414 const Typed_identifier_list* methods = (*pi)->methods();
4415 if (methods == NULL)
4416 continue;
4417 for (Typed_identifier_list::const_iterator pm = methods->begin();
4418 pm != methods->end();
4419 ++pm)
4421 if (Gogo::is_hidden_name(pm->name()))
4423 hidden_interfaces.push_back(*pi);
4424 break;
4429 if (!hidden_interfaces.empty())
4431 // Now traverse the tree looking for all named types.
4432 Build_method_tables bmt(this, hidden_interfaces);
4433 this->traverse(&bmt);
4436 // We no longer need the list of interfaces.
4438 this->interface_types_.clear();
4441 // This is called for each type. For a named type, for each of the
4442 // interfaces with hidden methods that it implements, create the
4443 // method table.
4446 Build_method_tables::type(Type* type)
4448 Named_type* nt = type->named_type();
4449 Struct_type* st = type->struct_type();
4450 if (nt != NULL || st != NULL)
4452 Translate_context context(this->gogo_, NULL, NULL, NULL);
4453 for (std::vector<Interface_type*>::const_iterator p =
4454 this->interfaces_.begin();
4455 p != this->interfaces_.end();
4456 ++p)
4458 // We ask whether a pointer to the named type implements the
4459 // interface, because a pointer can implement more methods
4460 // than a value.
4461 if (nt != NULL)
4463 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4464 NULL))
4466 nt->interface_method_table(*p, false)->get_backend(&context);
4467 nt->interface_method_table(*p, true)->get_backend(&context);
4470 else
4472 if ((*p)->implements_interface(Type::make_pointer_type(st),
4473 NULL))
4475 st->interface_method_table(*p, false)->get_backend(&context);
4476 st->interface_method_table(*p, true)->get_backend(&context);
4481 return TRAVERSE_CONTINUE;
4484 // Return an expression which allocates memory to hold values of type TYPE.
4486 Expression*
4487 Gogo::allocate_memory(Type* type, Location location)
4489 Expression* td = Expression::make_type_descriptor(type, location);
4490 return Runtime::make_call(Runtime::NEW, location, 1, td);
4493 // Traversal class used to check for return statements.
4495 class Check_return_statements_traverse : public Traverse
4497 public:
4498 Check_return_statements_traverse()
4499 : Traverse(traverse_functions)
4503 function(Named_object*);
4506 // Check that a function has a return statement if it needs one.
4509 Check_return_statements_traverse::function(Named_object* no)
4511 Function* func = no->func_value();
4512 const Function_type* fntype = func->type();
4513 const Typed_identifier_list* results = fntype->results();
4515 // We only need a return statement if there is a return value.
4516 if (results == NULL || results->empty())
4517 return TRAVERSE_CONTINUE;
4519 if (func->block()->may_fall_through())
4520 go_error_at(func->block()->end_location(),
4521 "missing return at end of function");
4523 return TRAVERSE_CONTINUE;
4526 // Check return statements.
4528 void
4529 Gogo::check_return_statements()
4531 Check_return_statements_traverse traverse;
4532 this->traverse(&traverse);
4535 // Export identifiers as requested.
4537 void
4538 Gogo::do_exports()
4540 // For now we always stream to a section. Later we may want to
4541 // support streaming to a separate file.
4542 Stream_to_section stream(this->backend());
4544 // Write out either the prefix or pkgpath depending on how we were
4545 // invoked.
4546 std::string prefix;
4547 std::string pkgpath;
4548 if (this->pkgpath_from_option_)
4549 pkgpath = this->pkgpath_;
4550 else if (this->prefix_from_option_)
4551 prefix = this->prefix_;
4552 else if (this->is_main_package())
4553 pkgpath = "main";
4554 else
4555 prefix = "go";
4557 Export exp(&stream);
4558 exp.register_builtin_types(this);
4559 exp.export_globals(this->package_name(),
4560 prefix,
4561 pkgpath,
4562 this->packages_,
4563 this->imports_,
4564 (this->need_init_fn_ && !this->is_main_package()
4565 ? this->get_init_fn_name()
4566 : ""),
4567 this->imported_init_fns_,
4568 this->package_->bindings());
4570 if (!this->c_header_.empty() && !saw_errors())
4571 this->write_c_header();
4574 // Write the top level named struct types in C format to a C header
4575 // file. This is used when building the runtime package, to share
4576 // struct definitions between C and Go.
4578 void
4579 Gogo::write_c_header()
4581 std::ofstream out;
4582 out.open(this->c_header_.c_str());
4583 if (out.fail())
4585 go_error_at(Linemap::unknown_location(),
4586 "cannot open %s: %m", this->c_header_.c_str());
4587 return;
4590 std::list<Named_object*> types;
4591 Bindings* top = this->package_->bindings();
4592 for (Bindings::const_definitions_iterator p = top->begin_definitions();
4593 p != top->end_definitions();
4594 ++p)
4596 Named_object* no = *p;
4598 // Skip names that start with underscore followed by something
4599 // other than an uppercase letter, as when compiling the runtime
4600 // package they are mostly types defined by mkrsysinfo.sh based
4601 // on the C system header files. We don't need to translate
4602 // types to C and back to Go. But do accept the special cases
4603 // _defer and _panic.
4604 std::string name = Gogo::unpack_hidden_name(no->name());
4605 if (name[0] == '_'
4606 && (name[1] < 'A' || name[1] > 'Z')
4607 && (name != "_defer" && name != "_panic"))
4608 continue;
4610 if (no->is_type() && no->type_value()->struct_type() != NULL)
4611 types.push_back(no);
4612 if (no->is_const() && no->const_value()->type()->integer_type() != NULL)
4614 Numeric_constant nc;
4615 unsigned long val;
4616 if (no->const_value()->expr()->numeric_constant_value(&nc)
4617 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
4619 out << "#define " << no->message_name() << ' ' << val
4620 << std::endl;
4625 std::vector<const Named_object*> written;
4626 int loop = 0;
4627 while (!types.empty())
4629 Named_object* no = types.front();
4630 types.pop_front();
4632 std::vector<const Named_object*> requires;
4633 std::vector<const Named_object*> declare;
4634 if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
4635 &declare))
4636 continue;
4638 bool ok = true;
4639 for (std::vector<const Named_object*>::const_iterator pr
4640 = requires.begin();
4641 pr != requires.end() && ok;
4642 ++pr)
4644 for (std::list<Named_object*>::const_iterator pt = types.begin();
4645 pt != types.end() && ok;
4646 ++pt)
4647 if (*pr == *pt)
4648 ok = false;
4650 if (!ok)
4652 ++loop;
4653 if (loop > 10000)
4655 // This should be impossible since the code parsed and
4656 // type checked.
4657 go_unreachable();
4660 types.push_back(no);
4661 continue;
4664 for (std::vector<const Named_object*>::const_iterator pd
4665 = declare.begin();
4666 pd != declare.end();
4667 ++pd)
4669 if (*pd == no)
4670 continue;
4672 std::vector<const Named_object*> drequires;
4673 std::vector<const Named_object*> ddeclare;
4674 if (!(*pd)->type_value()->struct_type()->
4675 can_write_to_c_header(&drequires, &ddeclare))
4676 continue;
4678 bool done = false;
4679 for (std::vector<const Named_object*>::const_iterator pw
4680 = written.begin();
4681 pw != written.end();
4682 ++pw)
4684 if (*pw == *pd)
4686 done = true;
4687 break;
4690 if (!done)
4692 out << std::endl;
4693 out << "struct " << (*pd)->message_name() << ";" << std::endl;
4694 written.push_back(*pd);
4698 out << std::endl;
4699 out << "struct " << no->message_name() << " {" << std::endl;
4700 no->type_value()->struct_type()->write_to_c_header(out);
4701 out << "};" << std::endl;
4702 written.push_back(no);
4705 out.close();
4706 if (out.fail())
4707 go_error_at(Linemap::unknown_location(),
4708 "error writing to %s: %m", this->c_header_.c_str());
4711 // Find the blocks in order to convert named types defined in blocks.
4713 class Convert_named_types : public Traverse
4715 public:
4716 Convert_named_types(Gogo* gogo)
4717 : Traverse(traverse_blocks),
4718 gogo_(gogo)
4721 protected:
4723 block(Block* block);
4725 private:
4726 Gogo* gogo_;
4730 Convert_named_types::block(Block* block)
4732 this->gogo_->convert_named_types_in_bindings(block->bindings());
4733 return TRAVERSE_CONTINUE;
4736 // Convert all named types to the backend representation. Since named
4737 // types can refer to other types, this needs to be done in the right
4738 // sequence, which is handled by Named_type::convert. Here we arrange
4739 // to call that for each named type.
4741 void
4742 Gogo::convert_named_types()
4744 this->convert_named_types_in_bindings(this->globals_);
4745 for (Packages::iterator p = this->packages_.begin();
4746 p != this->packages_.end();
4747 ++p)
4749 Package* package = p->second;
4750 this->convert_named_types_in_bindings(package->bindings());
4753 Convert_named_types cnt(this);
4754 this->traverse(&cnt);
4756 // Make all the builtin named types used for type descriptors, and
4757 // then convert them. They will only be written out if they are
4758 // needed.
4759 Type::make_type_descriptor_type();
4760 Type::make_type_descriptor_ptr_type();
4761 Function_type::make_function_type_descriptor_type();
4762 Pointer_type::make_pointer_type_descriptor_type();
4763 Struct_type::make_struct_type_descriptor_type();
4764 Array_type::make_array_type_descriptor_type();
4765 Array_type::make_slice_type_descriptor_type();
4766 Map_type::make_map_type_descriptor_type();
4767 Channel_type::make_chan_type_descriptor_type();
4768 Interface_type::make_interface_type_descriptor_type();
4769 Expression::make_func_descriptor_type();
4770 Type::convert_builtin_named_types(this);
4772 Runtime::convert_types(this);
4774 this->named_types_are_converted_ = true;
4776 Type::finish_pointer_types(this);
4779 // Convert all names types in a set of bindings.
4781 void
4782 Gogo::convert_named_types_in_bindings(Bindings* bindings)
4784 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4785 p != bindings->end_definitions();
4786 ++p)
4788 if ((*p)->is_type())
4789 (*p)->type_value()->convert(this);
4793 // Class Function.
4795 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
4796 Location location)
4797 : type_(type), enclosing_(enclosing), results_(NULL),
4798 closure_var_(NULL), block_(block), location_(location), labels_(),
4799 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
4800 pragmas_(0), is_sink_(false), results_are_named_(false),
4801 is_unnamed_type_stub_method_(false), calls_recover_(false),
4802 is_recover_thunk_(false), has_recover_thunk_(false),
4803 calls_defer_retaddr_(false), is_type_specific_function_(false),
4804 in_unique_section_(false)
4808 // Create the named result variables.
4810 void
4811 Function::create_result_variables(Gogo* gogo)
4813 const Typed_identifier_list* results = this->type_->results();
4814 if (results == NULL || results->empty())
4815 return;
4817 if (!results->front().name().empty())
4818 this->results_are_named_ = true;
4820 this->results_ = new Results();
4821 this->results_->reserve(results->size());
4823 Block* block = this->block_;
4824 int index = 0;
4825 for (Typed_identifier_list::const_iterator p = results->begin();
4826 p != results->end();
4827 ++p, ++index)
4829 std::string name = p->name();
4830 if (name.empty() || Gogo::is_sink_name(name))
4832 static int result_counter;
4833 char buf[100];
4834 snprintf(buf, sizeof buf, "$ret%d", result_counter);
4835 ++result_counter;
4836 name = gogo->pack_hidden_name(buf, false);
4838 Result_variable* result = new Result_variable(p->type(), this, index,
4839 p->location());
4840 Named_object* no = block->bindings()->add_result_variable(name, result);
4841 if (no->is_result_variable())
4842 this->results_->push_back(no);
4843 else
4845 static int dummy_result_count;
4846 char buf[100];
4847 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
4848 ++dummy_result_count;
4849 name = gogo->pack_hidden_name(buf, false);
4850 no = block->bindings()->add_result_variable(name, result);
4851 go_assert(no->is_result_variable());
4852 this->results_->push_back(no);
4857 // Update the named result variables when cloning a function which
4858 // calls recover.
4860 void
4861 Function::update_result_variables()
4863 if (this->results_ == NULL)
4864 return;
4866 for (Results::iterator p = this->results_->begin();
4867 p != this->results_->end();
4868 ++p)
4869 (*p)->result_var_value()->set_function(this);
4872 // Whether this method should not be included in the type descriptor.
4874 bool
4875 Function::nointerface() const
4877 go_assert(this->is_method());
4878 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
4881 // Record that this method should not be included in the type
4882 // descriptor.
4884 void
4885 Function::set_nointerface()
4887 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
4890 // Return the closure variable, creating it if necessary.
4892 Named_object*
4893 Function::closure_var()
4895 if (this->closure_var_ == NULL)
4897 go_assert(this->descriptor_ == NULL);
4898 // We don't know the type of the variable yet. We add fields as
4899 // we find them.
4900 Location loc = this->type_->location();
4901 Struct_field_list* sfl = new Struct_field_list;
4902 Struct_type* struct_type = Type::make_struct_type(sfl, loc);
4903 struct_type->set_is_struct_incomparable();
4904 Variable* var = new Variable(Type::make_pointer_type(struct_type),
4905 NULL, false, false, false, loc);
4906 var->set_is_used();
4907 var->set_is_closure();
4908 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
4909 // Note that the new variable is not in any binding contour.
4911 return this->closure_var_;
4914 // Set the type of the closure variable.
4916 void
4917 Function::set_closure_type()
4919 if (this->closure_var_ == NULL)
4920 return;
4921 Named_object* closure = this->closure_var_;
4922 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
4924 // The first field of a closure is always a pointer to the function
4925 // code.
4926 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4927 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
4928 this->location_)));
4930 unsigned int index = 1;
4931 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
4932 p != this->closure_fields_.end();
4933 ++p, ++index)
4935 Named_object* no = p->first;
4936 char buf[20];
4937 snprintf(buf, sizeof buf, "%u", index);
4938 std::string n = no->name() + buf;
4939 Type* var_type;
4940 if (no->is_variable())
4941 var_type = no->var_value()->type();
4942 else
4943 var_type = no->result_var_value()->type();
4944 Type* field_type = Type::make_pointer_type(var_type);
4945 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
4949 // Return whether this function is a method.
4951 bool
4952 Function::is_method() const
4954 return this->type_->is_method();
4957 // Add a label definition.
4959 Label*
4960 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
4961 Location location)
4963 Label* lnull = NULL;
4964 std::pair<Labels::iterator, bool> ins =
4965 this->labels_.insert(std::make_pair(label_name, lnull));
4966 Label* label;
4967 if (label_name == "_")
4969 label = Label::create_dummy_label();
4970 if (ins.second)
4971 ins.first->second = label;
4973 else if (ins.second)
4975 // This is a new label.
4976 label = new Label(label_name);
4977 ins.first->second = label;
4979 else
4981 // The label was already in the hash table.
4982 label = ins.first->second;
4983 if (label->is_defined())
4985 go_error_at(location, "label %qs already defined",
4986 Gogo::message_name(label_name).c_str());
4987 go_inform(label->location(), "previous definition of %qs was here",
4988 Gogo::message_name(label_name).c_str());
4989 return new Label(label_name);
4993 label->define(location, gogo->bindings_snapshot(location));
4995 // Issue any errors appropriate for any previous goto's to this
4996 // label.
4997 const std::vector<Bindings_snapshot*>& refs(label->refs());
4998 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
4999 p != refs.end();
5000 ++p)
5001 (*p)->check_goto_to(gogo->current_block());
5002 label->clear_refs();
5004 return label;
5007 // Add a reference to a label.
5009 Label*
5010 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5011 Location location, bool issue_goto_errors)
5013 Label* lnull = NULL;
5014 std::pair<Labels::iterator, bool> ins =
5015 this->labels_.insert(std::make_pair(label_name, lnull));
5016 Label* label;
5017 if (!ins.second)
5019 // The label was already in the hash table.
5020 label = ins.first->second;
5022 else
5024 go_assert(ins.first->second == NULL);
5025 label = new Label(label_name);
5026 ins.first->second = label;
5029 label->set_is_used();
5031 if (issue_goto_errors)
5033 Bindings_snapshot* snapshot = label->snapshot();
5034 if (snapshot != NULL)
5035 snapshot->check_goto_from(gogo->current_block(), location);
5036 else
5037 label->add_snapshot_ref(gogo->bindings_snapshot(location));
5040 return label;
5043 // Warn about labels that are defined but not used.
5045 void
5046 Function::check_labels() const
5048 for (Labels::const_iterator p = this->labels_.begin();
5049 p != this->labels_.end();
5050 p++)
5052 Label* label = p->second;
5053 if (!label->is_used())
5054 go_error_at(label->location(), "label %qs defined and not used",
5055 Gogo::message_name(label->name()).c_str());
5059 // Swap one function with another. This is used when building the
5060 // thunk we use to call a function which calls recover. It may not
5061 // work for any other case.
5063 void
5064 Function::swap_for_recover(Function *x)
5066 go_assert(this->enclosing_ == x->enclosing_);
5067 std::swap(this->results_, x->results_);
5068 std::swap(this->closure_var_, x->closure_var_);
5069 std::swap(this->block_, x->block_);
5070 go_assert(this->location_ == x->location_);
5071 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5072 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5075 // Traverse the tree.
5078 Function::traverse(Traverse* traverse)
5080 unsigned int traverse_mask = traverse->traverse_mask();
5082 if ((traverse_mask
5083 & (Traverse::traverse_types | Traverse::traverse_expressions))
5084 != 0)
5086 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5087 return TRAVERSE_EXIT;
5090 // FIXME: We should check traverse_functions here if nested
5091 // functions are stored in block bindings.
5092 if (this->block_ != NULL
5093 && (traverse_mask
5094 & (Traverse::traverse_variables
5095 | Traverse::traverse_constants
5096 | Traverse::traverse_blocks
5097 | Traverse::traverse_statements
5098 | Traverse::traverse_expressions
5099 | Traverse::traverse_types)) != 0)
5101 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5102 return TRAVERSE_EXIT;
5105 return TRAVERSE_CONTINUE;
5108 // Work out types for unspecified variables and constants.
5110 void
5111 Function::determine_types()
5113 if (this->block_ != NULL)
5114 this->block_->determine_types();
5117 // Return the function descriptor, the value you get when you refer to
5118 // the function in Go code without calling it.
5120 Expression*
5121 Function::descriptor(Gogo*, Named_object* no)
5123 go_assert(!this->is_method());
5124 go_assert(this->closure_var_ == NULL);
5125 if (this->descriptor_ == NULL)
5126 this->descriptor_ = Expression::make_func_descriptor(no);
5127 return this->descriptor_;
5130 // Get a pointer to the variable representing the defer stack for this
5131 // function, making it if necessary. The value of the variable is set
5132 // by the runtime routines to true if the function is returning,
5133 // rather than panicing through. A pointer to this variable is used
5134 // as a marker for the functions on the defer stack associated with
5135 // this function. A function-specific variable permits inlining a
5136 // function which uses defer.
5138 Expression*
5139 Function::defer_stack(Location location)
5141 if (this->defer_stack_ == NULL)
5143 Type* t = Type::lookup_bool_type();
5144 Expression* n = Expression::make_boolean(false, location);
5145 this->defer_stack_ = Statement::make_temporary(t, n, location);
5146 this->defer_stack_->set_is_address_taken();
5148 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5149 location);
5150 return Expression::make_unary(OPERATOR_AND, ref, location);
5153 // Export the function.
5155 void
5156 Function::export_func(Export* exp, const std::string& name) const
5158 Function::export_func_with_type(exp, name, this->type_);
5161 // Export a function with a type.
5163 void
5164 Function::export_func_with_type(Export* exp, const std::string& name,
5165 const Function_type* fntype)
5167 exp->write_c_string("func ");
5169 if (fntype->is_method())
5171 exp->write_c_string("(");
5172 const Typed_identifier* receiver = fntype->receiver();
5173 exp->write_name(receiver->name());
5174 exp->write_escape(receiver->note());
5175 exp->write_c_string(" ");
5176 exp->write_type(receiver->type());
5177 exp->write_c_string(") ");
5180 exp->write_string(name);
5182 exp->write_c_string(" (");
5183 const Typed_identifier_list* parameters = fntype->parameters();
5184 if (parameters != NULL)
5186 size_t i = 0;
5187 bool is_varargs = fntype->is_varargs();
5188 bool first = true;
5189 for (Typed_identifier_list::const_iterator p = parameters->begin();
5190 p != parameters->end();
5191 ++p, ++i)
5193 if (first)
5194 first = false;
5195 else
5196 exp->write_c_string(", ");
5197 exp->write_name(p->name());
5198 exp->write_escape(p->note());
5199 exp->write_c_string(" ");
5200 if (!is_varargs || p + 1 != parameters->end())
5201 exp->write_type(p->type());
5202 else
5204 exp->write_c_string("...");
5205 exp->write_type(p->type()->array_type()->element_type());
5209 exp->write_c_string(")");
5211 const Typed_identifier_list* results = fntype->results();
5212 if (results != NULL)
5214 if (results->size() == 1 && results->begin()->name().empty())
5216 exp->write_c_string(" ");
5217 exp->write_type(results->begin()->type());
5219 else
5221 exp->write_c_string(" (");
5222 bool first = true;
5223 for (Typed_identifier_list::const_iterator p = results->begin();
5224 p != results->end();
5225 ++p)
5227 if (first)
5228 first = false;
5229 else
5230 exp->write_c_string(", ");
5231 exp->write_name(p->name());
5232 exp->write_escape(p->note());
5233 exp->write_c_string(" ");
5234 exp->write_type(p->type());
5236 exp->write_c_string(")");
5239 exp->write_c_string(";\n");
5242 // Import a function.
5244 void
5245 Function::import_func(Import* imp, std::string* pname,
5246 Typed_identifier** preceiver,
5247 Typed_identifier_list** pparameters,
5248 Typed_identifier_list** presults,
5249 bool* is_varargs)
5251 imp->require_c_string("func ");
5253 *preceiver = NULL;
5254 if (imp->peek_char() == '(')
5256 imp->require_c_string("(");
5257 std::string name = imp->read_name();
5258 std::string escape_note = imp->read_escape();
5259 imp->require_c_string(" ");
5260 Type* rtype = imp->read_type();
5261 *preceiver = new Typed_identifier(name, rtype, imp->location());
5262 (*preceiver)->set_note(escape_note);
5263 imp->require_c_string(") ");
5266 *pname = imp->read_identifier();
5268 Typed_identifier_list* parameters;
5269 *is_varargs = false;
5270 imp->require_c_string(" (");
5271 if (imp->peek_char() == ')')
5272 parameters = NULL;
5273 else
5275 parameters = new Typed_identifier_list();
5276 while (true)
5278 std::string name = imp->read_name();
5279 std::string escape_note = imp->read_escape();
5280 imp->require_c_string(" ");
5282 if (imp->match_c_string("..."))
5284 imp->advance(3);
5285 *is_varargs = true;
5288 Type* ptype = imp->read_type();
5289 if (*is_varargs)
5290 ptype = Type::make_array_type(ptype, NULL);
5291 Typed_identifier t = Typed_identifier(name, ptype, imp->location());
5292 t.set_note(escape_note);
5293 parameters->push_back(t);
5294 if (imp->peek_char() != ',')
5295 break;
5296 go_assert(!*is_varargs);
5297 imp->require_c_string(", ");
5300 imp->require_c_string(")");
5301 *pparameters = parameters;
5303 Typed_identifier_list* results;
5304 if (imp->peek_char() != ' ')
5305 results = NULL;
5306 else
5308 results = new Typed_identifier_list();
5309 imp->require_c_string(" ");
5310 if (imp->peek_char() != '(')
5312 Type* rtype = imp->read_type();
5313 results->push_back(Typed_identifier("", rtype, imp->location()));
5315 else
5317 imp->require_c_string("(");
5318 while (true)
5320 std::string name = imp->read_name();
5321 std::string note = imp->read_escape();
5322 imp->require_c_string(" ");
5323 Type* rtype = imp->read_type();
5324 Typed_identifier t = Typed_identifier(name, rtype,
5325 imp->location());
5326 t.set_note(note);
5327 results->push_back(t);
5328 if (imp->peek_char() != ',')
5329 break;
5330 imp->require_c_string(", ");
5332 imp->require_c_string(")");
5335 imp->require_c_string(";\n");
5336 *presults = results;
5339 // Get the backend representation.
5341 Bfunction*
5342 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
5344 if (this->fndecl_ == NULL)
5346 bool is_visible = false;
5347 bool is_init_fn = false;
5348 Type* rtype = NULL;
5349 if (no->package() != NULL)
5351 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
5353 else if (Gogo::unpack_hidden_name(no->name()) == "init"
5354 && !this->type_->is_method())
5356 else if (no->name() == gogo->get_init_fn_name())
5358 is_visible = true;
5359 is_init_fn = true;
5361 else if (Gogo::unpack_hidden_name(no->name()) == "main"
5362 && gogo->is_main_package())
5363 is_visible = true;
5364 // Methods have to be public even if they are hidden because
5365 // they can be pulled into type descriptors when using
5366 // anonymous fields.
5367 else if (!Gogo::is_hidden_name(no->name())
5368 || this->type_->is_method())
5370 if (!this->is_unnamed_type_stub_method_)
5371 is_visible = true;
5372 if (this->type_->is_method())
5373 rtype = this->type_->receiver()->type();
5376 std::string asm_name;
5377 if (!this->asm_name_.empty())
5379 asm_name = this->asm_name_;
5381 // If an assembler name is explicitly specified, there must
5382 // be some reason to refer to the symbol from a different
5383 // object file.
5384 is_visible = true;
5386 else if (is_init_fn)
5388 // These names appear in the export data and are used
5389 // directly in the assembler code. If we change this here
5390 // we need to change Gogo::init_imports.
5391 asm_name = no->name();
5393 else
5394 asm_name = gogo->function_asm_name(no->name(), NULL, rtype);
5396 // If a function calls the predeclared recover function, we
5397 // can't inline it, because recover behaves differently in a
5398 // function passed directly to defer. If this is a recover
5399 // thunk that we built to test whether a function can be
5400 // recovered, we can't inline it, because that will mess up
5401 // our return address comparison.
5402 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
5404 // If a function calls __go_set_defer_retaddr, then mark it as
5405 // uninlinable. This prevents the GCC backend from splitting
5406 // the function; splitting the function is a bad idea because we
5407 // want the return address label to be in the same function as
5408 // the call.
5409 if (this->calls_defer_retaddr_)
5410 is_inlinable = false;
5412 // Check the //go:noinline compiler directive.
5413 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
5414 is_inlinable = false;
5416 // If this is a thunk created to call a function which calls
5417 // the predeclared recover function, we need to disable
5418 // stack splitting for the thunk.
5419 bool disable_split_stack = this->is_recover_thunk_;
5421 // Check the //go:nosplit compiler directive.
5422 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
5423 disable_split_stack = true;
5425 // This should go into a unique section if that has been
5426 // requested elsewhere, or if this is a nointerface function.
5427 // We want to put a nointerface function into a unique section
5428 // because there is a good chance that the linker garbage
5429 // collection can discard it.
5430 bool in_unique_section = (this->in_unique_section_
5431 || (this->is_method() && this->nointerface()));
5433 Btype* functype = this->type_->get_backend_fntype(gogo);
5434 this->fndecl_ =
5435 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5436 is_visible, false, is_inlinable,
5437 disable_split_stack, in_unique_section,
5438 this->location());
5440 return this->fndecl_;
5443 // Get the backend representation.
5445 Bfunction*
5446 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
5448 if (this->fndecl_ == NULL)
5450 // Let Go code use an asm declaration to pick up a builtin
5451 // function.
5452 if (!this->asm_name_.empty())
5454 Bfunction* builtin_decl =
5455 gogo->backend()->lookup_builtin(this->asm_name_);
5456 if (builtin_decl != NULL)
5458 this->fndecl_ = builtin_decl;
5459 return this->fndecl_;
5463 std::string asm_name;
5464 if (this->asm_name_.empty())
5466 Type* rtype = NULL;
5467 if (this->fntype_->is_method())
5468 rtype = this->fntype_->receiver()->type();
5469 asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
5471 else if (go_id_needs_encoding(no->get_id(gogo)))
5472 asm_name = go_encode_id(no->get_id(gogo));
5474 Btype* functype = this->fntype_->get_backend_fntype(gogo);
5475 this->fndecl_ =
5476 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5477 true, true, true, false, false,
5478 this->location());
5481 return this->fndecl_;
5484 // Build the descriptor for a function declaration. This won't
5485 // necessarily happen if the package has just a declaration for the
5486 // function and no other reference to it, but we may still need the
5487 // descriptor for references from other packages.
5488 void
5489 Function_declaration::build_backend_descriptor(Gogo* gogo)
5491 if (this->descriptor_ != NULL)
5493 Translate_context context(gogo, NULL, NULL, NULL);
5494 this->descriptor_->get_backend(&context);
5498 // Check that the types used in this declaration's signature are defined.
5499 // Reports errors for any undefined type.
5501 void
5502 Function_declaration::check_types() const
5504 // Calling Type::base will give errors for any undefined types.
5505 Function_type* fntype = this->type();
5506 if (fntype->receiver() != NULL)
5507 fntype->receiver()->type()->base();
5508 if (fntype->parameters() != NULL)
5510 const Typed_identifier_list* params = fntype->parameters();
5511 for (Typed_identifier_list::const_iterator p = params->begin();
5512 p != params->end();
5513 ++p)
5514 p->type()->base();
5518 // Return the function's decl after it has been built.
5520 Bfunction*
5521 Function::get_decl() const
5523 go_assert(this->fndecl_ != NULL);
5524 return this->fndecl_;
5527 // Build the backend representation for the function code.
5529 void
5530 Function::build(Gogo* gogo, Named_object* named_function)
5532 Translate_context context(gogo, named_function, NULL, NULL);
5534 // A list of parameter variables for this function.
5535 std::vector<Bvariable*> param_vars;
5537 // Variables that need to be declared for this function and their
5538 // initial values.
5539 std::vector<Bvariable*> vars;
5540 std::vector<Bexpression*> var_inits;
5541 for (Bindings::const_definitions_iterator p =
5542 this->block_->bindings()->begin_definitions();
5543 p != this->block_->bindings()->end_definitions();
5544 ++p)
5546 Location loc = (*p)->location();
5547 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
5549 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5550 Bvariable* parm_bvar = bvar;
5552 // We always pass the receiver to a method as a pointer. If
5553 // the receiver is declared as a non-pointer type, then we
5554 // copy the value into a local variable.
5555 if ((*p)->var_value()->is_receiver()
5556 && (*p)->var_value()->type()->points_to() == NULL)
5558 std::string name = (*p)->name() + ".pointer";
5559 Type* var_type = (*p)->var_value()->type();
5560 Variable* parm_var =
5561 new Variable(Type::make_pointer_type(var_type), NULL, false,
5562 true, false, loc);
5563 Named_object* parm_no =
5564 Named_object::make_variable(name, NULL, parm_var);
5565 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5567 vars.push_back(bvar);
5568 Expression* parm_ref =
5569 Expression::make_var_reference(parm_no, loc);
5570 parm_ref = Expression::make_unary(OPERATOR_MULT, parm_ref, loc);
5571 if ((*p)->var_value()->is_in_heap())
5572 parm_ref = Expression::make_heap_expression(parm_ref, loc);
5573 var_inits.push_back(parm_ref->get_backend(&context));
5575 else if ((*p)->var_value()->is_in_heap())
5577 // If we take the address of a parameter, then we need
5578 // to copy it into the heap.
5579 std::string parm_name = (*p)->name() + ".param";
5580 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
5581 false, true, false, loc);
5582 Named_object* parm_no =
5583 Named_object::make_variable(parm_name, NULL, parm_var);
5584 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5586 vars.push_back(bvar);
5587 Expression* var_ref =
5588 Expression::make_var_reference(parm_no, loc);
5589 var_ref = Expression::make_heap_expression(var_ref, loc);
5590 var_inits.push_back(var_ref->get_backend(&context));
5592 param_vars.push_back(parm_bvar);
5594 else if ((*p)->is_result_variable())
5596 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5598 Type* type = (*p)->result_var_value()->type();
5599 Bexpression* init;
5600 if (!(*p)->result_var_value()->is_in_heap())
5602 Btype* btype = type->get_backend(gogo);
5603 init = gogo->backend()->zero_expression(btype);
5605 else
5606 init = Expression::make_allocation(type,
5607 loc)->get_backend(&context);
5609 vars.push_back(bvar);
5610 var_inits.push_back(init);
5613 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
5615 go_assert(saw_errors());
5616 return;
5619 // If we need a closure variable, make sure to create it.
5620 // It gets installed in the function as a side effect of creation.
5621 if (this->closure_var_ != NULL)
5623 go_assert(this->closure_var_->var_value()->is_closure());
5624 this->closure_var_->get_backend_variable(gogo, named_function);
5627 if (this->block_ != NULL)
5629 // Declare variables if necessary.
5630 Bblock* var_decls = NULL;
5632 Bstatement* defer_init = NULL;
5633 if (!vars.empty() || this->defer_stack_ != NULL)
5635 var_decls =
5636 gogo->backend()->block(this->fndecl_, NULL, vars,
5637 this->block_->start_location(),
5638 this->block_->end_location());
5640 if (this->defer_stack_ != NULL)
5642 Translate_context dcontext(gogo, named_function, this->block_,
5643 var_decls);
5644 defer_init = this->defer_stack_->get_backend(&dcontext);
5648 // Build the backend representation for all the statements in the
5649 // function.
5650 Translate_context context(gogo, named_function, NULL, NULL);
5651 Bblock* code_block = this->block_->get_backend(&context);
5653 // Initialize variables if necessary.
5654 std::vector<Bstatement*> init;
5655 go_assert(vars.size() == var_inits.size());
5656 for (size_t i = 0; i < vars.size(); ++i)
5658 Bstatement* init_stmt =
5659 gogo->backend()->init_statement(this->fndecl_, vars[i],
5660 var_inits[i]);
5661 init.push_back(init_stmt);
5663 if (defer_init != NULL)
5664 init.push_back(defer_init);
5665 Bstatement* var_init = gogo->backend()->statement_list(init);
5667 // Initialize all variables before executing this code block.
5668 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
5669 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
5671 // If we have a defer stack, initialize it at the start of a
5672 // function.
5673 Bstatement* except = NULL;
5674 Bstatement* fini = NULL;
5675 if (defer_init != NULL)
5677 // Clean up the defer stack when we leave the function.
5678 this->build_defer_wrapper(gogo, named_function, &except, &fini);
5680 // Wrap the code for this function in an exception handler to handle
5681 // defer calls.
5682 code_stmt =
5683 gogo->backend()->exception_handler_statement(code_stmt,
5684 except, fini,
5685 this->location_);
5688 // Stick the code into the block we built for the receiver, if
5689 // we built one.
5690 if (var_decls != NULL)
5692 std::vector<Bstatement*> code_stmt_list(1, code_stmt);
5693 gogo->backend()->block_add_statements(var_decls, code_stmt_list);
5694 code_stmt = gogo->backend()->block_statement(var_decls);
5697 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
5699 go_assert(saw_errors());
5700 return;
5704 // If we created a descriptor for the function, make sure we emit it.
5705 if (this->descriptor_ != NULL)
5707 Translate_context context(gogo, NULL, NULL, NULL);
5708 this->descriptor_->get_backend(&context);
5712 // Build the wrappers around function code needed if the function has
5713 // any defer statements. This sets *EXCEPT to an exception handler
5714 // and *FINI to a finally handler.
5716 void
5717 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
5718 Bstatement** except, Bstatement** fini)
5720 Location end_loc = this->block_->end_location();
5722 // Add an exception handler. This is used if a panic occurs. Its
5723 // purpose is to stop the stack unwinding if a deferred function
5724 // calls recover. There are more details in
5725 // libgo/runtime/go-unwind.c.
5727 std::vector<Bstatement*> stmts;
5728 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5729 this->defer_stack(end_loc));
5730 Translate_context context(gogo, named_function, NULL, NULL);
5731 Bexpression* defer = call->get_backend(&context);
5732 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
5734 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
5735 if (ret_bstmt != NULL)
5736 stmts.push_back(ret_bstmt);
5738 go_assert(*except == NULL);
5739 *except = gogo->backend()->statement_list(stmts);
5741 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5742 this->defer_stack(end_loc));
5743 defer = call->get_backend(&context);
5745 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
5746 this->defer_stack(end_loc));
5747 Bexpression* undefer = call->get_backend(&context);
5748 Bstatement* function_defer =
5749 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
5750 end_loc);
5751 stmts = std::vector<Bstatement*>(1, function_defer);
5752 if (this->type_->results() != NULL
5753 && !this->type_->results()->empty()
5754 && !this->type_->results()->front().name().empty())
5756 // If the result variables are named, and we are returning from
5757 // this function rather than panicing through it, we need to
5758 // return them again, because they might have been changed by a
5759 // defer function. The runtime routines set the defer_stack
5760 // variable to true if we are returning from this function.
5762 ret_bstmt = this->return_value(gogo, named_function, end_loc);
5763 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
5764 Bexpression* ret =
5765 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
5766 Expression* ref =
5767 Expression::make_temporary_reference(this->defer_stack_, end_loc);
5768 Bexpression* bref = ref->get_backend(&context);
5769 ret = gogo->backend()->conditional_expression(this->fndecl_,
5770 NULL, bref, ret, NULL,
5771 end_loc);
5772 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
5775 go_assert(*fini == NULL);
5776 *fini = gogo->backend()->statement_list(stmts);
5779 // Return the statement that assigns values to this function's result struct.
5781 Bstatement*
5782 Function::return_value(Gogo* gogo, Named_object* named_function,
5783 Location location) const
5785 const Typed_identifier_list* results = this->type_->results();
5786 if (results == NULL || results->empty())
5787 return NULL;
5789 go_assert(this->results_ != NULL);
5790 if (this->results_->size() != results->size())
5792 go_assert(saw_errors());
5793 return gogo->backend()->error_statement();
5796 std::vector<Bexpression*> vals(results->size());
5797 for (size_t i = 0; i < vals.size(); ++i)
5799 Named_object* no = (*this->results_)[i];
5800 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
5801 Bexpression* val = gogo->backend()->var_expression(bvar, VE_rvalue,
5802 location);
5803 if (no->result_var_value()->is_in_heap())
5805 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
5806 val = gogo->backend()->indirect_expression(bt, val, true, location);
5808 vals[i] = val;
5810 return gogo->backend()->return_statement(this->fndecl_, vals, location);
5813 // Class Block.
5815 Block::Block(Block* enclosing, Location location)
5816 : enclosing_(enclosing), statements_(),
5817 bindings_(new Bindings(enclosing == NULL
5818 ? NULL
5819 : enclosing->bindings())),
5820 start_location_(location),
5821 end_location_(Linemap::unknown_location())
5825 // Add a statement to a block.
5827 void
5828 Block::add_statement(Statement* statement)
5830 this->statements_.push_back(statement);
5833 // Add a statement to the front of a block. This is slow but is only
5834 // used for reference counts of parameters.
5836 void
5837 Block::add_statement_at_front(Statement* statement)
5839 this->statements_.insert(this->statements_.begin(), statement);
5842 // Replace a statement in a block.
5844 void
5845 Block::replace_statement(size_t index, Statement* s)
5847 go_assert(index < this->statements_.size());
5848 this->statements_[index] = s;
5851 // Add a statement before another statement.
5853 void
5854 Block::insert_statement_before(size_t index, Statement* s)
5856 go_assert(index < this->statements_.size());
5857 this->statements_.insert(this->statements_.begin() + index, s);
5860 // Add a statement after another statement.
5862 void
5863 Block::insert_statement_after(size_t index, Statement* s)
5865 go_assert(index < this->statements_.size());
5866 this->statements_.insert(this->statements_.begin() + index + 1, s);
5869 // Traverse the tree.
5872 Block::traverse(Traverse* traverse)
5874 unsigned int traverse_mask = traverse->traverse_mask();
5876 if ((traverse_mask & Traverse::traverse_blocks) != 0)
5878 int t = traverse->block(this);
5879 if (t == TRAVERSE_EXIT)
5880 return TRAVERSE_EXIT;
5881 else if (t == TRAVERSE_SKIP_COMPONENTS)
5882 return TRAVERSE_CONTINUE;
5885 if ((traverse_mask
5886 & (Traverse::traverse_variables
5887 | Traverse::traverse_constants
5888 | Traverse::traverse_expressions
5889 | Traverse::traverse_types)) != 0)
5891 const unsigned int e_or_t = (Traverse::traverse_expressions
5892 | Traverse::traverse_types);
5893 const unsigned int e_or_t_or_s = (e_or_t
5894 | Traverse::traverse_statements);
5895 for (Bindings::const_definitions_iterator pb =
5896 this->bindings_->begin_definitions();
5897 pb != this->bindings_->end_definitions();
5898 ++pb)
5900 int t = TRAVERSE_CONTINUE;
5901 switch ((*pb)->classification())
5903 case Named_object::NAMED_OBJECT_CONST:
5904 if ((traverse_mask & Traverse::traverse_constants) != 0)
5905 t = traverse->constant(*pb, false);
5906 if (t == TRAVERSE_CONTINUE
5907 && (traverse_mask & e_or_t) != 0)
5909 Type* tc = (*pb)->const_value()->type();
5910 if (tc != NULL
5911 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5912 return TRAVERSE_EXIT;
5913 t = (*pb)->const_value()->traverse_expression(traverse);
5915 break;
5917 case Named_object::NAMED_OBJECT_VAR:
5918 case Named_object::NAMED_OBJECT_RESULT_VAR:
5919 if ((traverse_mask & Traverse::traverse_variables) != 0)
5920 t = traverse->variable(*pb);
5921 if (t == TRAVERSE_CONTINUE
5922 && (traverse_mask & e_or_t) != 0)
5924 if ((*pb)->is_result_variable()
5925 || (*pb)->var_value()->has_type())
5927 Type* tv = ((*pb)->is_variable()
5928 ? (*pb)->var_value()->type()
5929 : (*pb)->result_var_value()->type());
5930 if (tv != NULL
5931 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5932 return TRAVERSE_EXIT;
5935 if (t == TRAVERSE_CONTINUE
5936 && (traverse_mask & e_or_t_or_s) != 0
5937 && (*pb)->is_variable())
5938 t = (*pb)->var_value()->traverse_expression(traverse,
5939 traverse_mask);
5940 break;
5942 case Named_object::NAMED_OBJECT_FUNC:
5943 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5944 go_unreachable();
5946 case Named_object::NAMED_OBJECT_TYPE:
5947 if ((traverse_mask & e_or_t) != 0)
5948 t = Type::traverse((*pb)->type_value(), traverse);
5949 break;
5951 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5952 case Named_object::NAMED_OBJECT_UNKNOWN:
5953 case Named_object::NAMED_OBJECT_ERRONEOUS:
5954 break;
5956 case Named_object::NAMED_OBJECT_PACKAGE:
5957 case Named_object::NAMED_OBJECT_SINK:
5958 go_unreachable();
5960 default:
5961 go_unreachable();
5964 if (t == TRAVERSE_EXIT)
5965 return TRAVERSE_EXIT;
5969 // No point in checking traverse_mask here--if we got here we always
5970 // want to walk the statements. The traversal can insert new
5971 // statements before or after the current statement. Inserting
5972 // statements before the current statement requires updating I via
5973 // the pointer; those statements will not be traversed. Any new
5974 // statements inserted after the current statement will be traversed
5975 // in their turn.
5976 for (size_t i = 0; i < this->statements_.size(); ++i)
5978 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
5979 return TRAVERSE_EXIT;
5982 return TRAVERSE_CONTINUE;
5985 // Work out types for unspecified variables and constants.
5987 void
5988 Block::determine_types()
5990 for (Bindings::const_definitions_iterator pb =
5991 this->bindings_->begin_definitions();
5992 pb != this->bindings_->end_definitions();
5993 ++pb)
5995 if ((*pb)->is_variable())
5996 (*pb)->var_value()->determine_type();
5997 else if ((*pb)->is_const())
5998 (*pb)->const_value()->determine_type();
6001 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6002 ps != this->statements_.end();
6003 ++ps)
6004 (*ps)->determine_types();
6007 // Return true if the statements in this block may fall through.
6009 bool
6010 Block::may_fall_through() const
6012 if (this->statements_.empty())
6013 return true;
6014 return this->statements_.back()->may_fall_through();
6017 // Convert a block to the backend representation.
6019 Bblock*
6020 Block::get_backend(Translate_context* context)
6022 Gogo* gogo = context->gogo();
6023 Named_object* function = context->function();
6024 std::vector<Bvariable*> vars;
6025 vars.reserve(this->bindings_->size_definitions());
6026 for (Bindings::const_definitions_iterator pv =
6027 this->bindings_->begin_definitions();
6028 pv != this->bindings_->end_definitions();
6029 ++pv)
6031 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
6032 vars.push_back((*pv)->get_backend_variable(gogo, function));
6035 go_assert(function != NULL);
6036 Bfunction* bfunction =
6037 function->func_value()->get_or_make_decl(gogo, function);
6038 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
6039 vars, this->start_location_,
6040 this->end_location_);
6042 Translate_context subcontext(gogo, function, this, ret);
6043 std::vector<Bstatement*> bstatements;
6044 bstatements.reserve(this->statements_.size());
6045 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
6046 p != this->statements_.end();
6047 ++p)
6048 bstatements.push_back((*p)->get_backend(&subcontext));
6050 context->backend()->block_add_statements(ret, bstatements);
6052 return ret;
6055 // Class Bindings_snapshot.
6057 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
6058 : block_(b), counts_(), location_(location)
6060 while (b != NULL)
6062 this->counts_.push_back(b->bindings()->size_definitions());
6063 b = b->enclosing();
6067 // Report errors appropriate for a goto from B to this.
6069 void
6070 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
6072 size_t dummy;
6073 if (!this->check_goto_block(loc, b, this->block_, &dummy))
6074 return;
6075 this->check_goto_defs(loc, this->block_,
6076 this->block_->bindings()->size_definitions(),
6077 this->counts_[0]);
6080 // Report errors appropriate for a goto from this to B.
6082 void
6083 Bindings_snapshot::check_goto_to(const Block* b)
6085 size_t index;
6086 if (!this->check_goto_block(this->location_, this->block_, b, &index))
6087 return;
6088 this->check_goto_defs(this->location_, b, this->counts_[index],
6089 b->bindings()->size_definitions());
6092 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6093 // Return true if all is well, false if we reported an error. If this
6094 // returns true, it sets *PINDEX to the number of blocks BTO is above
6095 // BFROM.
6097 bool
6098 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
6099 const Block* bto, size_t* pindex)
6101 // It is an error if BTO is not either BFROM or above BFROM.
6102 size_t index = 0;
6103 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
6105 if (pb == NULL)
6107 go_error_at(loc, "goto jumps into block");
6108 go_inform(bto->start_location(), "goto target block starts here");
6109 return false;
6112 *pindex = index;
6113 return true;
6116 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6117 // CFROM is the number of names defined at the point of the goto and
6118 // CTO is the number of names defined at the point of the label.
6120 void
6121 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
6122 size_t cfrom, size_t cto)
6124 if (cfrom < cto)
6126 Bindings::const_definitions_iterator p =
6127 block->bindings()->begin_definitions();
6128 for (size_t i = 0; i < cfrom; ++i)
6130 go_assert(p != block->bindings()->end_definitions());
6131 ++p;
6133 go_assert(p != block->bindings()->end_definitions());
6135 std::string n = (*p)->message_name();
6136 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
6137 go_inform((*p)->location(), "%qs defined here", n.c_str());
6141 // Class Function_declaration.
6143 // Return the function descriptor.
6145 Expression*
6146 Function_declaration::descriptor(Gogo*, Named_object* no)
6148 go_assert(!this->fntype_->is_method());
6149 if (this->descriptor_ == NULL)
6150 this->descriptor_ = Expression::make_func_descriptor(no);
6151 return this->descriptor_;
6154 // Class Variable.
6156 Variable::Variable(Type* type, Expression* init, bool is_global,
6157 bool is_parameter, bool is_receiver,
6158 Location location)
6159 : type_(type), init_(init), preinit_(NULL), location_(location),
6160 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
6161 is_closure_(false), is_receiver_(is_receiver),
6162 is_varargs_parameter_(false), is_used_(false),
6163 is_address_taken_(false), is_non_escaping_address_taken_(false),
6164 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6165 type_from_init_tuple_(false), type_from_range_index_(false),
6166 type_from_range_value_(false), type_from_chan_element_(false),
6167 is_type_switch_var_(false), determined_type_(false),
6168 in_unique_section_(false), escapes_(true)
6170 go_assert(type != NULL || init != NULL);
6171 go_assert(!is_parameter || init == NULL);
6174 // Traverse the initializer expression.
6177 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
6179 if (this->preinit_ != NULL)
6181 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
6182 return TRAVERSE_EXIT;
6184 if (this->init_ != NULL
6185 && ((traverse_mask
6186 & (Traverse::traverse_expressions | Traverse::traverse_types))
6187 != 0))
6189 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
6190 return TRAVERSE_EXIT;
6192 return TRAVERSE_CONTINUE;
6195 // Lower the initialization expression after parsing is complete.
6197 void
6198 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
6199 Statement_inserter* inserter)
6201 Named_object* dep = gogo->var_depends_on(this);
6202 if (dep != NULL && dep->is_variable())
6203 dep->var_value()->lower_init_expression(gogo, function, inserter);
6205 if (this->init_ != NULL && !this->init_is_lowered_)
6207 if (this->seen_)
6209 // We will give an error elsewhere, this is just to prevent
6210 // an infinite loop.
6211 return;
6213 this->seen_ = true;
6215 Statement_inserter global_inserter;
6216 if (this->is_global_)
6218 global_inserter = Statement_inserter(gogo, this);
6219 inserter = &global_inserter;
6222 gogo->lower_expression(function, inserter, &this->init_);
6224 this->seen_ = false;
6226 this->init_is_lowered_ = true;
6230 // Flatten the initialization expression after ordering evaluations.
6232 void
6233 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
6234 Statement_inserter* inserter)
6236 Named_object* dep = gogo->var_depends_on(this);
6237 if (dep != NULL && dep->is_variable())
6238 dep->var_value()->flatten_init_expression(gogo, function, inserter);
6240 if (this->init_ != NULL && !this->init_is_flattened_)
6242 if (this->seen_)
6244 // We will give an error elsewhere, this is just to prevent
6245 // an infinite loop.
6246 return;
6248 this->seen_ = true;
6250 Statement_inserter global_inserter;
6251 if (this->is_global_)
6253 global_inserter = Statement_inserter(gogo, this);
6254 inserter = &global_inserter;
6257 gogo->flatten_expression(function, inserter, &this->init_);
6259 // If an interface conversion is needed, we need a temporary
6260 // variable.
6261 if (this->type_ != NULL
6262 && !Type::are_identical(this->type_, this->init_->type(), false,
6263 NULL)
6264 && this->init_->type()->interface_type() != NULL
6265 && !this->init_->is_variable())
6267 Temporary_statement* temp =
6268 Statement::make_temporary(NULL, this->init_, this->location_);
6269 inserter->insert(temp);
6270 this->init_ = Expression::make_temporary_reference(temp,
6271 this->location_);
6274 this->seen_ = false;
6275 this->init_is_flattened_ = true;
6279 // Get the preinit block.
6281 Block*
6282 Variable::preinit_block(Gogo* gogo)
6284 go_assert(this->is_global_);
6285 if (this->preinit_ == NULL)
6286 this->preinit_ = new Block(NULL, this->location());
6288 // If a global variable has a preinitialization statement, then we
6289 // need to have an initialization function.
6290 gogo->set_need_init_fn();
6292 return this->preinit_;
6295 // Add a statement to be run before the initialization expression.
6297 void
6298 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
6300 Block* b = this->preinit_block(gogo);
6301 b->add_statement(s);
6302 b->set_end_location(s->location());
6305 // Whether this variable has a type.
6307 bool
6308 Variable::has_type() const
6310 if (this->type_ == NULL)
6311 return false;
6313 // A variable created in a type switch case nil does not actually
6314 // have a type yet. It will be changed to use the initializer's
6315 // type in determine_type.
6316 if (this->is_type_switch_var_
6317 && this->type_->is_nil_constant_as_type())
6318 return false;
6320 return true;
6323 // In an assignment which sets a variable to a tuple of EXPR, return
6324 // the type of the first element of the tuple.
6326 Type*
6327 Variable::type_from_tuple(Expression* expr, bool report_error) const
6329 if (expr->map_index_expression() != NULL)
6331 Map_type* mt = expr->map_index_expression()->get_map_type();
6332 if (mt == NULL)
6333 return Type::make_error_type();
6334 return mt->val_type();
6336 else if (expr->receive_expression() != NULL)
6338 Expression* channel = expr->receive_expression()->channel();
6339 Type* channel_type = channel->type();
6340 if (channel_type->channel_type() == NULL)
6341 return Type::make_error_type();
6342 return channel_type->channel_type()->element_type();
6344 else
6346 if (report_error)
6347 go_error_at(this->location(), "invalid tuple definition");
6348 return Type::make_error_type();
6352 // Given EXPR used in a range clause, return either the index type or
6353 // the value type of the range, depending upon GET_INDEX_TYPE.
6355 Type*
6356 Variable::type_from_range(Expression* expr, bool get_index_type,
6357 bool report_error) const
6359 Type* t = expr->type();
6360 if (t->array_type() != NULL
6361 || (t->points_to() != NULL
6362 && t->points_to()->array_type() != NULL
6363 && !t->points_to()->is_slice_type()))
6365 if (get_index_type)
6366 return Type::lookup_integer_type("int");
6367 else
6368 return t->deref()->array_type()->element_type();
6370 else if (t->is_string_type())
6372 if (get_index_type)
6373 return Type::lookup_integer_type("int");
6374 else
6375 return Type::lookup_integer_type("int32");
6377 else if (t->map_type() != NULL)
6379 if (get_index_type)
6380 return t->map_type()->key_type();
6381 else
6382 return t->map_type()->val_type();
6384 else if (t->channel_type() != NULL)
6386 if (get_index_type)
6387 return t->channel_type()->element_type();
6388 else
6390 if (report_error)
6391 go_error_at(this->location(),
6392 ("invalid definition of value variable "
6393 "for channel range"));
6394 return Type::make_error_type();
6397 else
6399 if (report_error)
6400 go_error_at(this->location(), "invalid type for range clause");
6401 return Type::make_error_type();
6405 // EXPR should be a channel. Return the channel's element type.
6407 Type*
6408 Variable::type_from_chan_element(Expression* expr, bool report_error) const
6410 Type* t = expr->type();
6411 if (t->channel_type() != NULL)
6412 return t->channel_type()->element_type();
6413 else
6415 if (report_error)
6416 go_error_at(this->location(), "expected channel");
6417 return Type::make_error_type();
6421 // Return the type of the Variable. This may be called before
6422 // Variable::determine_type is called, which means that we may need to
6423 // get the type from the initializer. FIXME: If we combine lowering
6424 // with type determination, then this should be unnecessary.
6426 Type*
6427 Variable::type()
6429 // A variable in a type switch with a nil case will have the wrong
6430 // type here. This gets fixed up in determine_type, below.
6431 Type* type = this->type_;
6432 Expression* init = this->init_;
6433 if (this->is_type_switch_var_
6434 && type != NULL
6435 && this->type_->is_nil_constant_as_type())
6437 Type_guard_expression* tge = this->init_->type_guard_expression();
6438 go_assert(tge != NULL);
6439 init = tge->expr();
6440 type = NULL;
6443 if (this->seen_)
6445 if (this->type_ == NULL || !this->type_->is_error_type())
6447 go_error_at(this->location_, "variable initializer refers to itself");
6448 this->type_ = Type::make_error_type();
6450 return this->type_;
6453 this->seen_ = true;
6455 if (type != NULL)
6457 else if (this->type_from_init_tuple_)
6458 type = this->type_from_tuple(init, false);
6459 else if (this->type_from_range_index_ || this->type_from_range_value_)
6460 type = this->type_from_range(init, this->type_from_range_index_, false);
6461 else if (this->type_from_chan_element_)
6462 type = this->type_from_chan_element(init, false);
6463 else
6465 go_assert(init != NULL);
6466 type = init->type();
6467 go_assert(type != NULL);
6469 // Variables should not have abstract types.
6470 if (type->is_abstract())
6471 type = type->make_non_abstract_type();
6473 if (type->is_void_type())
6474 type = Type::make_error_type();
6477 this->seen_ = false;
6479 return type;
6482 // Fetch the type from a const pointer, in which case it should have
6483 // been set already.
6485 Type*
6486 Variable::type() const
6488 go_assert(this->type_ != NULL);
6489 return this->type_;
6492 // Set the type if necessary.
6494 void
6495 Variable::determine_type()
6497 if (this->determined_type_)
6498 return;
6499 this->determined_type_ = true;
6501 if (this->preinit_ != NULL)
6502 this->preinit_->determine_types();
6504 // A variable in a type switch with a nil case will have the wrong
6505 // type here. It will have an initializer which is a type guard.
6506 // We want to initialize it to the value without the type guard, and
6507 // use the type of that value as well.
6508 if (this->is_type_switch_var_
6509 && this->type_ != NULL
6510 && this->type_->is_nil_constant_as_type())
6512 Type_guard_expression* tge = this->init_->type_guard_expression();
6513 go_assert(tge != NULL);
6514 this->type_ = NULL;
6515 this->init_ = tge->expr();
6518 if (this->init_ == NULL)
6519 go_assert(this->type_ != NULL && !this->type_->is_abstract());
6520 else if (this->type_from_init_tuple_)
6522 Expression *init = this->init_;
6523 init->determine_type_no_context();
6524 this->type_ = this->type_from_tuple(init, true);
6525 this->init_ = NULL;
6527 else if (this->type_from_range_index_ || this->type_from_range_value_)
6529 Expression* init = this->init_;
6530 init->determine_type_no_context();
6531 this->type_ = this->type_from_range(init, this->type_from_range_index_,
6532 true);
6533 this->init_ = NULL;
6535 else if (this->type_from_chan_element_)
6537 Expression* init = this->init_;
6538 init->determine_type_no_context();
6539 this->type_ = this->type_from_chan_element(init, true);
6540 this->init_ = NULL;
6542 else
6544 Type_context context(this->type_, false);
6545 this->init_->determine_type(&context);
6546 if (this->type_ == NULL)
6548 Type* type = this->init_->type();
6549 go_assert(type != NULL);
6550 if (type->is_abstract())
6551 type = type->make_non_abstract_type();
6553 if (type->is_void_type())
6555 go_error_at(this->location_, "variable has no type");
6556 type = Type::make_error_type();
6558 else if (type->is_nil_type())
6560 go_error_at(this->location_, "variable defined to nil type");
6561 type = Type::make_error_type();
6563 else if (type->is_call_multiple_result_type())
6565 go_error_at(this->location_,
6566 "single variable set to multiple-value function call");
6567 type = Type::make_error_type();
6570 this->type_ = type;
6575 // Get the initial value of a variable. This does not
6576 // consider whether the variable is in the heap--it returns the
6577 // initial value as though it were always stored in the stack.
6579 Bexpression*
6580 Variable::get_init(Gogo* gogo, Named_object* function)
6582 go_assert(this->preinit_ == NULL);
6583 Location loc = this->location();
6584 if (this->init_ == NULL)
6586 go_assert(!this->is_parameter_);
6587 if (this->is_global_ || this->is_in_heap())
6588 return NULL;
6589 Btype* btype = this->type()->get_backend(gogo);
6590 return gogo->backend()->zero_expression(btype);
6592 else
6594 Translate_context context(gogo, function, NULL, NULL);
6595 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
6596 return init->get_backend(&context);
6600 // Get the initial value of a variable when a block is required.
6601 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6603 Bstatement*
6604 Variable::get_init_block(Gogo* gogo, Named_object* function,
6605 Bvariable* var_decl)
6607 go_assert(this->preinit_ != NULL);
6609 // We want to add the variable assignment to the end of the preinit
6610 // block.
6612 Translate_context context(gogo, function, NULL, NULL);
6613 Bblock* bblock = this->preinit_->get_backend(&context);
6614 Bfunction* bfunction =
6615 function->func_value()->get_or_make_decl(gogo, function);
6617 // It's possible to have pre-init statements without an initializer
6618 // if the pre-init statements set the variable.
6619 Bstatement* decl_init = NULL;
6620 if (this->init_ != NULL)
6622 if (var_decl == NULL)
6624 Bexpression* init_bexpr = this->init_->get_backend(&context);
6625 decl_init = gogo->backend()->expression_statement(bfunction,
6626 init_bexpr);
6628 else
6630 Location loc = this->location();
6631 Expression* val_expr =
6632 Expression::make_cast(this->type(), this->init_, loc);
6633 Bexpression* val = val_expr->get_backend(&context);
6634 Bexpression* var_ref =
6635 gogo->backend()->var_expression(var_decl, VE_lvalue, loc);
6636 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
6637 val, loc);
6640 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
6641 if (decl_init != NULL)
6642 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
6643 return block_stmt;
6646 // Export the variable
6648 void
6649 Variable::export_var(Export* exp, const std::string& name) const
6651 go_assert(this->is_global_);
6652 exp->write_c_string("var ");
6653 exp->write_string(name);
6654 exp->write_c_string(" ");
6655 exp->write_type(this->type());
6656 exp->write_c_string(";\n");
6659 // Import a variable.
6661 void
6662 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
6664 imp->require_c_string("var ");
6665 *pname = imp->read_identifier();
6666 imp->require_c_string(" ");
6667 *ptype = imp->read_type();
6668 imp->require_c_string(";\n");
6671 // Convert a variable to the backend representation.
6673 Bvariable*
6674 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
6675 const Package* package, const std::string& name)
6677 if (this->backend_ == NULL)
6679 Backend* backend = gogo->backend();
6680 Type* type = this->type_;
6681 if (type->is_error_type()
6682 || (type->is_undefined()
6683 && (!this->is_global_ || package == NULL)))
6684 this->backend_ = backend->error_variable();
6685 else
6687 bool is_parameter = this->is_parameter_;
6688 if (this->is_receiver_ && type->points_to() == NULL)
6689 is_parameter = false;
6690 if (this->is_in_heap())
6692 is_parameter = false;
6693 type = Type::make_pointer_type(type);
6696 const std::string n = Gogo::unpack_hidden_name(name);
6697 Btype* btype = type->get_backend(gogo);
6699 Bvariable* bvar;
6700 if (Map_type::is_zero_value(this))
6701 bvar = Map_type::backend_zero_value(gogo);
6702 else if (this->is_global_)
6704 std::string var_name(package != NULL
6705 ? package->package_name()
6706 : gogo->package_name());
6707 var_name.push_back('.');
6708 var_name.append(n);
6710 std::string asm_name(gogo->global_var_asm_name(name, package));
6712 bool is_hidden = Gogo::is_hidden_name(name);
6713 // Hack to export runtime.writeBarrier. FIXME.
6714 // This is because go:linkname doesn't work on variables.
6715 if (gogo->compiling_runtime()
6716 && var_name == "runtime.writeBarrier")
6717 is_hidden = false;
6719 bvar = backend->global_variable(var_name,
6720 asm_name,
6721 btype,
6722 package != NULL,
6723 is_hidden,
6724 this->in_unique_section_,
6725 this->location_);
6727 else if (function == NULL)
6729 go_assert(saw_errors());
6730 bvar = backend->error_variable();
6732 else
6734 Bfunction* bfunction = function->func_value()->get_decl();
6735 bool is_address_taken = (this->is_non_escaping_address_taken_
6736 && !this->is_in_heap());
6737 if (this->is_closure())
6738 bvar = backend->static_chain_variable(bfunction, n, btype,
6739 this->location_);
6740 else if (is_parameter)
6741 bvar = backend->parameter_variable(bfunction, n, btype,
6742 is_address_taken,
6743 this->location_);
6744 else
6745 bvar = backend->local_variable(bfunction, n, btype,
6746 is_address_taken,
6747 this->location_);
6749 this->backend_ = bvar;
6752 return this->backend_;
6755 // Class Result_variable.
6757 // Convert a result variable to the backend representation.
6759 Bvariable*
6760 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
6761 const std::string& name)
6763 if (this->backend_ == NULL)
6765 Backend* backend = gogo->backend();
6766 Type* type = this->type_;
6767 if (type->is_error())
6768 this->backend_ = backend->error_variable();
6769 else
6771 if (this->is_in_heap())
6772 type = Type::make_pointer_type(type);
6773 Btype* btype = type->get_backend(gogo);
6774 Bfunction* bfunction = function->func_value()->get_decl();
6775 std::string n = Gogo::unpack_hidden_name(name);
6776 bool is_address_taken = (this->is_non_escaping_address_taken_
6777 && !this->is_in_heap());
6778 this->backend_ = backend->local_variable(bfunction, n, btype,
6779 is_address_taken,
6780 this->location_);
6783 return this->backend_;
6786 // Class Named_constant.
6788 // Traverse the initializer expression.
6791 Named_constant::traverse_expression(Traverse* traverse)
6793 return Expression::traverse(&this->expr_, traverse);
6796 // Determine the type of the constant.
6798 void
6799 Named_constant::determine_type()
6801 if (this->type_ != NULL)
6803 Type_context context(this->type_, false);
6804 this->expr_->determine_type(&context);
6806 else
6808 // A constant may have an abstract type.
6809 Type_context context(NULL, true);
6810 this->expr_->determine_type(&context);
6811 this->type_ = this->expr_->type();
6812 go_assert(this->type_ != NULL);
6816 // Indicate that we found and reported an error for this constant.
6818 void
6819 Named_constant::set_error()
6821 this->type_ = Type::make_error_type();
6822 this->expr_ = Expression::make_error(this->location_);
6825 // Export a constant.
6827 void
6828 Named_constant::export_const(Export* exp, const std::string& name) const
6830 exp->write_c_string("const ");
6831 exp->write_string(name);
6832 exp->write_c_string(" ");
6833 if (!this->type_->is_abstract())
6835 exp->write_type(this->type_);
6836 exp->write_c_string(" ");
6838 exp->write_c_string("= ");
6839 this->expr()->export_expression(exp);
6840 exp->write_c_string(";\n");
6843 // Import a constant.
6845 void
6846 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
6847 Expression** pexpr)
6849 imp->require_c_string("const ");
6850 *pname = imp->read_identifier();
6851 imp->require_c_string(" ");
6852 if (imp->peek_char() == '=')
6853 *ptype = NULL;
6854 else
6856 *ptype = imp->read_type();
6857 imp->require_c_string(" ");
6859 imp->require_c_string("= ");
6860 *pexpr = Expression::import_expression(imp);
6861 imp->require_c_string(";\n");
6864 // Get the backend representation.
6866 Bexpression*
6867 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
6869 if (this->bconst_ == NULL)
6871 Translate_context subcontext(gogo, NULL, NULL, NULL);
6872 Type* type = this->type();
6873 Location loc = this->location();
6875 Expression* const_ref = Expression::make_const_reference(const_no, loc);
6876 Bexpression* const_decl = const_ref->get_backend(&subcontext);
6877 if (type != NULL && type->is_numeric_type())
6879 Btype* btype = type->get_backend(gogo);
6880 std::string name = const_no->get_id(gogo);
6881 const_decl =
6882 gogo->backend()->named_constant_expression(btype, name,
6883 const_decl, loc);
6885 this->bconst_ = const_decl;
6887 return this->bconst_;
6890 // Add a method.
6892 Named_object*
6893 Type_declaration::add_method(const std::string& name, Function* function)
6895 Named_object* ret = Named_object::make_function(name, NULL, function);
6896 this->methods_.push_back(ret);
6897 return ret;
6900 // Add a method declaration.
6902 Named_object*
6903 Type_declaration::add_method_declaration(const std::string& name,
6904 Package* package,
6905 Function_type* type,
6906 Location location)
6908 Named_object* ret = Named_object::make_function_declaration(name, package,
6909 type, location);
6910 this->methods_.push_back(ret);
6911 return ret;
6914 // Return whether any methods are defined.
6916 bool
6917 Type_declaration::has_methods() const
6919 return !this->methods_.empty();
6922 // Define methods for the real type.
6924 void
6925 Type_declaration::define_methods(Named_type* nt)
6927 if (this->methods_.empty())
6928 return;
6930 while (nt->is_alias())
6932 Type *t = nt->real_type()->forwarded();
6933 if (t->named_type() != NULL)
6934 nt = t->named_type();
6935 else if (t->forward_declaration_type() != NULL)
6937 Named_object* no = t->forward_declaration_type()->named_object();
6938 Type_declaration* td = no->type_declaration_value();
6939 td->methods_.insert(td->methods_.end(), this->methods_.begin(),
6940 this->methods_.end());
6941 this->methods_.clear();
6942 return;
6944 else
6946 for (std::vector<Named_object*>::const_iterator p =
6947 this->methods_.begin();
6948 p != this->methods_.end();
6949 ++p)
6950 go_error_at((*p)->location(),
6951 ("invalid receiver type "
6952 "(receiver must be a named type"));
6953 return;
6957 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
6958 p != this->methods_.end();
6959 ++p)
6961 if (!(*p)->func_value()->is_sink())
6962 nt->add_existing_method(*p);
6966 // We are using the type. Return true if we should issue a warning.
6968 bool
6969 Type_declaration::using_type()
6971 bool ret = !this->issued_warning_;
6972 this->issued_warning_ = true;
6973 return ret;
6976 // Class Unknown_name.
6978 // Set the real named object.
6980 void
6981 Unknown_name::set_real_named_object(Named_object* no)
6983 go_assert(this->real_named_object_ == NULL);
6984 go_assert(!no->is_unknown());
6985 this->real_named_object_ = no;
6988 // Class Named_object.
6990 Named_object::Named_object(const std::string& name,
6991 const Package* package,
6992 Classification classification)
6993 : name_(name), package_(package), classification_(classification),
6994 is_redefinition_(false)
6996 if (Gogo::is_sink_name(name))
6997 go_assert(classification == NAMED_OBJECT_SINK);
7000 // Make an unknown name. This is used by the parser. The name must
7001 // be resolved later. Unknown names are only added in the current
7002 // package.
7004 Named_object*
7005 Named_object::make_unknown_name(const std::string& name,
7006 Location location)
7008 Named_object* named_object = new Named_object(name, NULL,
7009 NAMED_OBJECT_UNKNOWN);
7010 Unknown_name* value = new Unknown_name(location);
7011 named_object->u_.unknown_value = value;
7012 return named_object;
7015 // Make a constant.
7017 Named_object*
7018 Named_object::make_constant(const Typed_identifier& tid,
7019 const Package* package, Expression* expr,
7020 int iota_value)
7022 Named_object* named_object = new Named_object(tid.name(), package,
7023 NAMED_OBJECT_CONST);
7024 Named_constant* named_constant = new Named_constant(tid.type(), expr,
7025 iota_value,
7026 tid.location());
7027 named_object->u_.const_value = named_constant;
7028 return named_object;
7031 // Make a named type.
7033 Named_object*
7034 Named_object::make_type(const std::string& name, const Package* package,
7035 Type* type, Location location)
7037 Named_object* named_object = new Named_object(name, package,
7038 NAMED_OBJECT_TYPE);
7039 Named_type* named_type = Type::make_named_type(named_object, type, location);
7040 named_object->u_.type_value = named_type;
7041 return named_object;
7044 // Make a type declaration.
7046 Named_object*
7047 Named_object::make_type_declaration(const std::string& name,
7048 const Package* package,
7049 Location location)
7051 Named_object* named_object = new Named_object(name, package,
7052 NAMED_OBJECT_TYPE_DECLARATION);
7053 Type_declaration* type_declaration = new Type_declaration(location);
7054 named_object->u_.type_declaration = type_declaration;
7055 return named_object;
7058 // Make a variable.
7060 Named_object*
7061 Named_object::make_variable(const std::string& name, const Package* package,
7062 Variable* variable)
7064 Named_object* named_object = new Named_object(name, package,
7065 NAMED_OBJECT_VAR);
7066 named_object->u_.var_value = variable;
7067 return named_object;
7070 // Make a result variable.
7072 Named_object*
7073 Named_object::make_result_variable(const std::string& name,
7074 Result_variable* result)
7076 Named_object* named_object = new Named_object(name, NULL,
7077 NAMED_OBJECT_RESULT_VAR);
7078 named_object->u_.result_var_value = result;
7079 return named_object;
7082 // Make a sink. This is used for the special blank identifier _.
7084 Named_object*
7085 Named_object::make_sink()
7087 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
7090 // Make a named function.
7092 Named_object*
7093 Named_object::make_function(const std::string& name, const Package* package,
7094 Function* function)
7096 Named_object* named_object = new Named_object(name, package,
7097 NAMED_OBJECT_FUNC);
7098 named_object->u_.func_value = function;
7099 return named_object;
7102 // Make a function declaration.
7104 Named_object*
7105 Named_object::make_function_declaration(const std::string& name,
7106 const Package* package,
7107 Function_type* fntype,
7108 Location location)
7110 Named_object* named_object = new Named_object(name, package,
7111 NAMED_OBJECT_FUNC_DECLARATION);
7112 Function_declaration *func_decl = new Function_declaration(fntype, location);
7113 named_object->u_.func_declaration_value = func_decl;
7114 return named_object;
7117 // Make a package.
7119 Named_object*
7120 Named_object::make_package(const std::string& alias, Package* package)
7122 Named_object* named_object = new Named_object(alias, NULL,
7123 NAMED_OBJECT_PACKAGE);
7124 named_object->u_.package_value = package;
7125 return named_object;
7128 // Return the name to use in an error message.
7130 std::string
7131 Named_object::message_name() const
7133 if (this->package_ == NULL)
7134 return Gogo::message_name(this->name_);
7135 std::string ret;
7136 if (this->package_->has_package_name())
7137 ret = this->package_->package_name();
7138 else
7139 ret = this->package_->pkgpath();
7140 ret = Gogo::message_name(ret);
7141 ret += '.';
7142 ret += Gogo::message_name(this->name_);
7143 return ret;
7146 // Set the type when a declaration is defined.
7148 void
7149 Named_object::set_type_value(Named_type* named_type)
7151 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
7152 Type_declaration* td = this->u_.type_declaration;
7153 td->define_methods(named_type);
7154 unsigned int index;
7155 Named_object* in_function = td->in_function(&index);
7156 if (in_function != NULL)
7157 named_type->set_in_function(in_function, index);
7158 delete td;
7159 this->classification_ = NAMED_OBJECT_TYPE;
7160 this->u_.type_value = named_type;
7163 // Define a function which was previously declared.
7165 void
7166 Named_object::set_function_value(Function* function)
7168 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
7169 if (this->func_declaration_value()->has_descriptor())
7171 Expression* descriptor =
7172 this->func_declaration_value()->descriptor(NULL, NULL);
7173 function->set_descriptor(descriptor);
7175 this->classification_ = NAMED_OBJECT_FUNC;
7176 // FIXME: We should free the old value.
7177 this->u_.func_value = function;
7180 // Declare an unknown object as a type declaration.
7182 void
7183 Named_object::declare_as_type()
7185 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
7186 Unknown_name* unk = this->u_.unknown_value;
7187 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
7188 this->u_.type_declaration = new Type_declaration(unk->location());
7189 delete unk;
7192 // Return the location of a named object.
7194 Location
7195 Named_object::location() const
7197 switch (this->classification_)
7199 default:
7200 case NAMED_OBJECT_UNINITIALIZED:
7201 go_unreachable();
7203 case NAMED_OBJECT_ERRONEOUS:
7204 return Linemap::unknown_location();
7206 case NAMED_OBJECT_UNKNOWN:
7207 return this->unknown_value()->location();
7209 case NAMED_OBJECT_CONST:
7210 return this->const_value()->location();
7212 case NAMED_OBJECT_TYPE:
7213 return this->type_value()->location();
7215 case NAMED_OBJECT_TYPE_DECLARATION:
7216 return this->type_declaration_value()->location();
7218 case NAMED_OBJECT_VAR:
7219 return this->var_value()->location();
7221 case NAMED_OBJECT_RESULT_VAR:
7222 return this->result_var_value()->location();
7224 case NAMED_OBJECT_SINK:
7225 go_unreachable();
7227 case NAMED_OBJECT_FUNC:
7228 return this->func_value()->location();
7230 case NAMED_OBJECT_FUNC_DECLARATION:
7231 return this->func_declaration_value()->location();
7233 case NAMED_OBJECT_PACKAGE:
7234 return this->package_value()->location();
7238 // Export a named object.
7240 void
7241 Named_object::export_named_object(Export* exp) const
7243 switch (this->classification_)
7245 default:
7246 case NAMED_OBJECT_UNINITIALIZED:
7247 case NAMED_OBJECT_UNKNOWN:
7248 go_unreachable();
7250 case NAMED_OBJECT_ERRONEOUS:
7251 break;
7253 case NAMED_OBJECT_CONST:
7254 this->const_value()->export_const(exp, this->name_);
7255 break;
7257 case NAMED_OBJECT_TYPE:
7258 this->type_value()->export_named_type(exp, this->name_);
7259 break;
7261 case NAMED_OBJECT_TYPE_DECLARATION:
7262 go_error_at(this->type_declaration_value()->location(),
7263 "attempt to export %<%s%> which was declared but not defined",
7264 this->message_name().c_str());
7265 break;
7267 case NAMED_OBJECT_FUNC_DECLARATION:
7268 this->func_declaration_value()->export_func(exp, this->name_);
7269 break;
7271 case NAMED_OBJECT_VAR:
7272 this->var_value()->export_var(exp, this->name_);
7273 break;
7275 case NAMED_OBJECT_RESULT_VAR:
7276 case NAMED_OBJECT_SINK:
7277 go_unreachable();
7279 case NAMED_OBJECT_FUNC:
7280 this->func_value()->export_func(exp, this->name_);
7281 break;
7285 // Convert a variable to the backend representation.
7287 Bvariable*
7288 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
7290 if (this->classification_ == NAMED_OBJECT_VAR)
7291 return this->var_value()->get_backend_variable(gogo, function,
7292 this->package_, this->name_);
7293 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
7294 return this->result_var_value()->get_backend_variable(gogo, function,
7295 this->name_);
7296 else
7297 go_unreachable();
7300 // Return the external identifier for this object.
7302 std::string
7303 Named_object::get_id(Gogo* gogo)
7305 go_assert(!this->is_variable()
7306 && !this->is_result_variable()
7307 && !this->is_type());
7308 std::string decl_name;
7309 if (this->is_function_declaration()
7310 && !this->func_declaration_value()->asm_name().empty())
7311 decl_name = this->func_declaration_value()->asm_name();
7312 else
7314 std::string package_name;
7315 if (this->package_ == NULL)
7316 package_name = gogo->package_name();
7317 else
7318 package_name = this->package_->package_name();
7320 // Note that this will be misleading if this is an unexported
7321 // method generated for an embedded imported type. In that case
7322 // the unexported method should have the package name of the
7323 // package from which it is imported, but we are going to give
7324 // it our package name. Fixing this would require knowing the
7325 // package name, but we only know the package path. It might be
7326 // better to use package paths here anyhow. This doesn't affect
7327 // the assembler code, because we always set that name in
7328 // Function::get_or_make_decl anyhow. FIXME.
7330 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
7332 Function_type* fntype;
7333 if (this->is_function())
7334 fntype = this->func_value()->type();
7335 else if (this->is_function_declaration())
7336 fntype = this->func_declaration_value()->type();
7337 else
7338 fntype = NULL;
7339 if (fntype != NULL && fntype->is_method())
7341 decl_name.push_back('.');
7342 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
7345 return decl_name;
7348 // Get the backend representation for this named object.
7350 void
7351 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
7352 std::vector<Btype*>& type_decls,
7353 std::vector<Bfunction*>& func_decls)
7355 // If this is a definition, avoid trying to get the backend
7356 // representation, as that can crash.
7357 if (this->is_redefinition_)
7359 go_assert(saw_errors());
7360 return;
7363 switch (this->classification_)
7365 case NAMED_OBJECT_CONST:
7366 if (!Gogo::is_erroneous_name(this->name_))
7367 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
7368 break;
7370 case NAMED_OBJECT_TYPE:
7372 Named_type* named_type = this->u_.type_value;
7373 if (!Gogo::is_erroneous_name(this->name_))
7374 type_decls.push_back(named_type->get_backend(gogo));
7376 // We need to produce a type descriptor for every named
7377 // type, and for a pointer to every named type, since
7378 // other files or packages might refer to them. We need
7379 // to do this even for hidden types, because they might
7380 // still be returned by some function. Simply calling the
7381 // type_descriptor method is enough to create the type
7382 // descriptor, even though we don't do anything with it.
7383 if (this->package_ == NULL && !saw_errors())
7385 named_type->
7386 type_descriptor_pointer(gogo, Linemap::predeclared_location());
7387 named_type->gc_symbol_pointer(gogo);
7388 Type* pn = Type::make_pointer_type(named_type);
7389 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
7390 pn->gc_symbol_pointer(gogo);
7393 break;
7395 case NAMED_OBJECT_TYPE_DECLARATION:
7396 go_error_at(Linemap::unknown_location(),
7397 "reference to undefined type %qs",
7398 this->message_name().c_str());
7399 return;
7401 case NAMED_OBJECT_VAR:
7402 case NAMED_OBJECT_RESULT_VAR:
7403 case NAMED_OBJECT_SINK:
7404 go_unreachable();
7406 case NAMED_OBJECT_FUNC:
7408 Function* func = this->u_.func_value;
7409 if (!Gogo::is_erroneous_name(this->name_))
7410 func_decls.push_back(func->get_or_make_decl(gogo, this));
7412 if (func->block() != NULL)
7413 func->build(gogo, this);
7415 break;
7417 case NAMED_OBJECT_ERRONEOUS:
7418 break;
7420 default:
7421 go_unreachable();
7425 // Class Bindings.
7427 Bindings::Bindings(Bindings* enclosing)
7428 : enclosing_(enclosing), named_objects_(), bindings_()
7432 // Clear imports.
7434 void
7435 Bindings::clear_file_scope(Gogo* gogo)
7437 Contour::iterator p = this->bindings_.begin();
7438 while (p != this->bindings_.end())
7440 bool keep;
7441 if (p->second->package() != NULL)
7442 keep = false;
7443 else if (p->second->is_package())
7444 keep = false;
7445 else if (p->second->is_function()
7446 && !p->second->func_value()->type()->is_method()
7447 && Gogo::unpack_hidden_name(p->second->name()) == "init")
7448 keep = false;
7449 else
7450 keep = true;
7452 if (keep)
7453 ++p;
7454 else
7456 gogo->add_file_block_name(p->second->name(), p->second->location());
7457 p = this->bindings_.erase(p);
7462 // Look up a symbol.
7464 Named_object*
7465 Bindings::lookup(const std::string& name) const
7467 Contour::const_iterator p = this->bindings_.find(name);
7468 if (p != this->bindings_.end())
7469 return p->second->resolve();
7470 else if (this->enclosing_ != NULL)
7471 return this->enclosing_->lookup(name);
7472 else
7473 return NULL;
7476 // Look up a symbol locally.
7478 Named_object*
7479 Bindings::lookup_local(const std::string& name) const
7481 Contour::const_iterator p = this->bindings_.find(name);
7482 if (p == this->bindings_.end())
7483 return NULL;
7484 return p->second;
7487 // Remove an object from a set of bindings. This is used for a
7488 // special case in thunks for functions which call recover.
7490 void
7491 Bindings::remove_binding(Named_object* no)
7493 Contour::iterator pb = this->bindings_.find(no->name());
7494 go_assert(pb != this->bindings_.end());
7495 this->bindings_.erase(pb);
7496 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
7497 pn != this->named_objects_.end();
7498 ++pn)
7500 if (*pn == no)
7502 this->named_objects_.erase(pn);
7503 return;
7506 go_unreachable();
7509 // Add a method to the list of objects. This is not added to the
7510 // lookup table. This is so that we have a single list of objects
7511 // declared at the top level, which we walk through when it's time to
7512 // convert to trees.
7514 void
7515 Bindings::add_method(Named_object* method)
7517 this->named_objects_.push_back(method);
7520 // Add a generic Named_object to a Contour.
7522 Named_object*
7523 Bindings::add_named_object_to_contour(Contour* contour,
7524 Named_object* named_object)
7526 go_assert(named_object == named_object->resolve());
7527 const std::string& name(named_object->name());
7528 go_assert(!Gogo::is_sink_name(name));
7530 std::pair<Contour::iterator, bool> ins =
7531 contour->insert(std::make_pair(name, named_object));
7532 if (!ins.second)
7534 // The name was already there.
7535 if (named_object->package() != NULL
7536 && ins.first->second->package() == named_object->package()
7537 && (ins.first->second->classification()
7538 == named_object->classification()))
7540 // This is a second import of the same object.
7541 return ins.first->second;
7543 ins.first->second = this->new_definition(ins.first->second,
7544 named_object);
7545 return ins.first->second;
7547 else
7549 // Don't push declarations on the list. We push them on when
7550 // and if we find the definitions. That way we genericize the
7551 // functions in order.
7552 if (!named_object->is_type_declaration()
7553 && !named_object->is_function_declaration()
7554 && !named_object->is_unknown())
7555 this->named_objects_.push_back(named_object);
7556 return named_object;
7560 // We had an existing named object OLD_OBJECT, and we've seen a new
7561 // one NEW_OBJECT with the same name. FIXME: This does not free the
7562 // new object when we don't need it.
7564 Named_object*
7565 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
7567 if (new_object->is_erroneous() && !old_object->is_erroneous())
7568 return new_object;
7570 std::string reason;
7571 switch (old_object->classification())
7573 default:
7574 case Named_object::NAMED_OBJECT_UNINITIALIZED:
7575 go_unreachable();
7577 case Named_object::NAMED_OBJECT_ERRONEOUS:
7578 return old_object;
7580 case Named_object::NAMED_OBJECT_UNKNOWN:
7582 Named_object* real = old_object->unknown_value()->real_named_object();
7583 if (real != NULL)
7584 return this->new_definition(real, new_object);
7585 go_assert(!new_object->is_unknown());
7586 old_object->unknown_value()->set_real_named_object(new_object);
7587 if (!new_object->is_type_declaration()
7588 && !new_object->is_function_declaration())
7589 this->named_objects_.push_back(new_object);
7590 return new_object;
7593 case Named_object::NAMED_OBJECT_CONST:
7594 break;
7596 case Named_object::NAMED_OBJECT_TYPE:
7597 if (new_object->is_type_declaration())
7598 return old_object;
7599 break;
7601 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7602 if (new_object->is_type_declaration())
7603 return old_object;
7604 if (new_object->is_type())
7606 old_object->set_type_value(new_object->type_value());
7607 new_object->type_value()->set_named_object(old_object);
7608 this->named_objects_.push_back(old_object);
7609 return old_object;
7611 break;
7613 case Named_object::NAMED_OBJECT_VAR:
7614 case Named_object::NAMED_OBJECT_RESULT_VAR:
7615 // We have already given an error in the parser for cases where
7616 // one parameter or result variable redeclares another one.
7617 if ((new_object->is_variable()
7618 && new_object->var_value()->is_parameter())
7619 || new_object->is_result_variable())
7620 return old_object;
7621 break;
7623 case Named_object::NAMED_OBJECT_SINK:
7624 go_unreachable();
7626 case Named_object::NAMED_OBJECT_FUNC:
7627 if (new_object->is_function_declaration())
7629 if (!new_object->func_declaration_value()->asm_name().empty())
7630 go_error_at(Linemap::unknown_location(),
7631 ("sorry, not implemented: "
7632 "__asm__ for function definitions"));
7633 Function_type* old_type = old_object->func_value()->type();
7634 Function_type* new_type =
7635 new_object->func_declaration_value()->type();
7636 if (old_type->is_valid_redeclaration(new_type, &reason))
7637 return old_object;
7639 break;
7641 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7643 if (new_object->is_function())
7645 Function_type* old_type =
7646 old_object->func_declaration_value()->type();
7647 Function_type* new_type = new_object->func_value()->type();
7648 if (old_type->is_valid_redeclaration(new_type, &reason))
7650 if (!old_object->func_declaration_value()->asm_name().empty())
7651 go_error_at(Linemap::unknown_location(),
7652 ("sorry, not implemented: "
7653 "__asm__ for function definitions"));
7654 old_object->set_function_value(new_object->func_value());
7655 this->named_objects_.push_back(old_object);
7656 return old_object;
7660 break;
7662 case Named_object::NAMED_OBJECT_PACKAGE:
7663 break;
7666 std::string n = old_object->message_name();
7667 if (reason.empty())
7668 go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
7669 else
7670 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
7671 reason.c_str());
7672 old_object->set_is_redefinition();
7673 new_object->set_is_redefinition();
7675 go_inform(old_object->location(), "previous definition of %qs was here",
7676 n.c_str());
7678 return old_object;
7681 // Add a named type.
7683 Named_object*
7684 Bindings::add_named_type(Named_type* named_type)
7686 return this->add_named_object(named_type->named_object());
7689 // Add a function.
7691 Named_object*
7692 Bindings::add_function(const std::string& name, const Package* package,
7693 Function* function)
7695 return this->add_named_object(Named_object::make_function(name, package,
7696 function));
7699 // Add a function declaration.
7701 Named_object*
7702 Bindings::add_function_declaration(const std::string& name,
7703 const Package* package,
7704 Function_type* type,
7705 Location location)
7707 Named_object* no = Named_object::make_function_declaration(name, package,
7708 type, location);
7709 return this->add_named_object(no);
7712 // Define a type which was previously declared.
7714 void
7715 Bindings::define_type(Named_object* no, Named_type* type)
7717 no->set_type_value(type);
7718 this->named_objects_.push_back(no);
7721 // Mark all local variables as used. This is used for some types of
7722 // parse error.
7724 void
7725 Bindings::mark_locals_used()
7727 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
7728 p != this->named_objects_.end();
7729 ++p)
7730 if ((*p)->is_variable())
7731 (*p)->var_value()->set_is_used();
7734 // Traverse bindings.
7737 Bindings::traverse(Traverse* traverse, bool is_global)
7739 unsigned int traverse_mask = traverse->traverse_mask();
7741 // We don't use an iterator because we permit the traversal to add
7742 // new global objects.
7743 const unsigned int e_or_t = (Traverse::traverse_expressions
7744 | Traverse::traverse_types);
7745 const unsigned int e_or_t_or_s = (e_or_t
7746 | Traverse::traverse_statements);
7747 for (size_t i = 0; i < this->named_objects_.size(); ++i)
7749 Named_object* p = this->named_objects_[i];
7750 int t = TRAVERSE_CONTINUE;
7751 switch (p->classification())
7753 case Named_object::NAMED_OBJECT_CONST:
7754 if ((traverse_mask & Traverse::traverse_constants) != 0)
7755 t = traverse->constant(p, is_global);
7756 if (t == TRAVERSE_CONTINUE
7757 && (traverse_mask & e_or_t) != 0)
7759 Type* tc = p->const_value()->type();
7760 if (tc != NULL
7761 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
7762 return TRAVERSE_EXIT;
7763 t = p->const_value()->traverse_expression(traverse);
7765 break;
7767 case Named_object::NAMED_OBJECT_VAR:
7768 case Named_object::NAMED_OBJECT_RESULT_VAR:
7769 if ((traverse_mask & Traverse::traverse_variables) != 0)
7770 t = traverse->variable(p);
7771 if (t == TRAVERSE_CONTINUE
7772 && (traverse_mask & e_or_t) != 0)
7774 if (p->is_result_variable()
7775 || p->var_value()->has_type())
7777 Type* tv = (p->is_variable()
7778 ? p->var_value()->type()
7779 : p->result_var_value()->type());
7780 if (tv != NULL
7781 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
7782 return TRAVERSE_EXIT;
7785 if (t == TRAVERSE_CONTINUE
7786 && (traverse_mask & e_or_t_or_s) != 0
7787 && p->is_variable())
7788 t = p->var_value()->traverse_expression(traverse, traverse_mask);
7789 break;
7791 case Named_object::NAMED_OBJECT_FUNC:
7792 if ((traverse_mask & Traverse::traverse_functions) != 0)
7793 t = traverse->function(p);
7795 if (t == TRAVERSE_CONTINUE
7796 && (traverse_mask
7797 & (Traverse::traverse_variables
7798 | Traverse::traverse_constants
7799 | Traverse::traverse_functions
7800 | Traverse::traverse_blocks
7801 | Traverse::traverse_statements
7802 | Traverse::traverse_expressions
7803 | Traverse::traverse_types)) != 0)
7804 t = p->func_value()->traverse(traverse);
7805 break;
7807 case Named_object::NAMED_OBJECT_PACKAGE:
7808 // These are traversed in Gogo::traverse.
7809 go_assert(is_global);
7810 break;
7812 case Named_object::NAMED_OBJECT_TYPE:
7813 if ((traverse_mask & e_or_t) != 0)
7814 t = Type::traverse(p->type_value(), traverse);
7815 break;
7817 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7818 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7819 case Named_object::NAMED_OBJECT_UNKNOWN:
7820 case Named_object::NAMED_OBJECT_ERRONEOUS:
7821 break;
7823 case Named_object::NAMED_OBJECT_SINK:
7824 default:
7825 go_unreachable();
7828 if (t == TRAVERSE_EXIT)
7829 return TRAVERSE_EXIT;
7832 // If we need to traverse types, check the function declarations,
7833 // which have types. Also check any methods of a type declaration.
7834 if ((traverse_mask & e_or_t) != 0)
7836 for (Bindings::const_declarations_iterator p =
7837 this->begin_declarations();
7838 p != this->end_declarations();
7839 ++p)
7841 if (p->second->is_function_declaration())
7843 if (Type::traverse(p->second->func_declaration_value()->type(),
7844 traverse)
7845 == TRAVERSE_EXIT)
7846 return TRAVERSE_EXIT;
7848 else if (p->second->is_type_declaration())
7850 const std::vector<Named_object*>* methods =
7851 p->second->type_declaration_value()->methods();
7852 for (std::vector<Named_object*>::const_iterator pm =
7853 methods->begin();
7854 pm != methods->end();
7855 pm++)
7857 Named_object* no = *pm;
7858 Type *t;
7859 if (no->is_function())
7860 t = no->func_value()->type();
7861 else if (no->is_function_declaration())
7862 t = no->func_declaration_value()->type();
7863 else
7864 continue;
7865 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
7866 return TRAVERSE_EXIT;
7872 return TRAVERSE_CONTINUE;
7875 // Class Label.
7877 // Clear any references to this label.
7879 void
7880 Label::clear_refs()
7882 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
7883 p != this->refs_.end();
7884 ++p)
7885 delete *p;
7886 this->refs_.clear();
7889 // Get the backend representation for a label.
7891 Blabel*
7892 Label::get_backend_label(Translate_context* context)
7894 if (this->blabel_ == NULL)
7896 Function* function = context->function()->func_value();
7897 Bfunction* bfunction = function->get_decl();
7898 this->blabel_ = context->backend()->label(bfunction, this->name_,
7899 this->location_);
7901 return this->blabel_;
7904 // Return an expression for the address of this label.
7906 Bexpression*
7907 Label::get_addr(Translate_context* context, Location location)
7909 Blabel* label = this->get_backend_label(context);
7910 return context->backend()->label_address(label, location);
7913 // Return the dummy label that represents any instance of the blank label.
7915 Label*
7916 Label::create_dummy_label()
7918 static Label* dummy_label;
7919 if (dummy_label == NULL)
7921 dummy_label = new Label("_");
7922 dummy_label->set_is_used();
7924 return dummy_label;
7927 // Class Unnamed_label.
7929 // Get the backend representation for an unnamed label.
7931 Blabel*
7932 Unnamed_label::get_blabel(Translate_context* context)
7934 if (this->blabel_ == NULL)
7936 Function* function = context->function()->func_value();
7937 Bfunction* bfunction = function->get_decl();
7938 this->blabel_ = context->backend()->label(bfunction, "",
7939 this->location_);
7941 return this->blabel_;
7944 // Return a statement which defines this unnamed label.
7946 Bstatement*
7947 Unnamed_label::get_definition(Translate_context* context)
7949 Blabel* blabel = this->get_blabel(context);
7950 return context->backend()->label_definition_statement(blabel);
7953 // Return a goto statement to this unnamed label.
7955 Bstatement*
7956 Unnamed_label::get_goto(Translate_context* context, Location location)
7958 Blabel* blabel = this->get_blabel(context);
7959 return context->backend()->goto_statement(blabel, location);
7962 // Class Package.
7964 Package::Package(const std::string& pkgpath,
7965 const std::string& pkgpath_symbol, Location location)
7966 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
7967 package_name_(), bindings_(new Bindings(NULL)),
7968 location_(location)
7970 go_assert(!pkgpath.empty());
7973 // Set the package name.
7975 void
7976 Package::set_package_name(const std::string& package_name, Location location)
7978 go_assert(!package_name.empty());
7979 if (this->package_name_.empty())
7980 this->package_name_ = package_name;
7981 else if (this->package_name_ != package_name)
7982 go_error_at(location,
7983 ("saw two different packages with "
7984 "the same package path %s: %s, %s"),
7985 this->pkgpath_.c_str(), this->package_name_.c_str(),
7986 package_name.c_str());
7989 // Return the pkgpath symbol, which is a prefix for symbols defined in
7990 // this package.
7992 std::string
7993 Package::pkgpath_symbol() const
7995 if (this->pkgpath_symbol_.empty())
7996 return Gogo::pkgpath_for_symbol(this->pkgpath_);
7997 return this->pkgpath_symbol_;
8000 // Set the package path symbol.
8002 void
8003 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
8005 go_assert(!pkgpath_symbol.empty());
8006 if (this->pkgpath_symbol_.empty())
8007 this->pkgpath_symbol_ = pkgpath_symbol;
8008 else
8009 go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
8012 // Note that symbol from this package was and qualified by ALIAS.
8014 void
8015 Package::note_usage(const std::string& alias) const
8017 Aliases::const_iterator p = this->aliases_.find(alias);
8018 go_assert(p != this->aliases_.end());
8019 p->second->note_usage();
8022 // Forget a given usage. If forgetting this usage means this package becomes
8023 // unused, report that error.
8025 void
8026 Package::forget_usage(Expression* usage) const
8028 if (this->fake_uses_.empty())
8029 return;
8031 std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
8032 go_assert(p != this->fake_uses_.end());
8033 this->fake_uses_.erase(p);
8035 if (this->fake_uses_.empty())
8036 go_error_at(this->location(), "imported and not used: %s",
8037 Gogo::message_name(this->package_name()).c_str());
8040 // Clear the used field for the next file. If the only usages of this package
8041 // are possibly fake, keep the fake usages for lowering.
8043 void
8044 Package::clear_used()
8046 std::string dot_alias = "." + this->package_name();
8047 Aliases::const_iterator p = this->aliases_.find(dot_alias);
8048 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
8049 this->fake_uses_.clear();
8051 this->aliases_.clear();
8054 Package_alias*
8055 Package::add_alias(const std::string& alias, Location location)
8057 Aliases::const_iterator p = this->aliases_.find(alias);
8058 if (p == this->aliases_.end())
8060 std::pair<Aliases::iterator, bool> ret;
8061 ret = this->aliases_.insert(std::make_pair(alias,
8062 new Package_alias(location)));
8063 p = ret.first;
8065 return p->second;
8068 // Determine types of constants. Everything else in a package
8069 // (variables, function declarations) should already have a fixed
8070 // type. Constants may have abstract types.
8072 void
8073 Package::determine_types()
8075 Bindings* bindings = this->bindings_;
8076 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
8077 p != bindings->end_definitions();
8078 ++p)
8080 if ((*p)->is_const())
8081 (*p)->const_value()->determine_type();
8085 // Class Traverse.
8087 // Destructor.
8089 Traverse::~Traverse()
8091 if (this->types_seen_ != NULL)
8092 delete this->types_seen_;
8093 if (this->expressions_seen_ != NULL)
8094 delete this->expressions_seen_;
8097 // Record that we are looking at a type, and return true if we have
8098 // already seen it.
8100 bool
8101 Traverse::remember_type(const Type* type)
8103 if (type->is_error_type())
8104 return true;
8105 go_assert((this->traverse_mask() & traverse_types) != 0
8106 || (this->traverse_mask() & traverse_expressions) != 0);
8107 // We mostly only have to remember named types. But it turns out
8108 // that an interface type can refer to itself without using a name
8109 // by relying on interface inheritance, as in
8110 // type I interface { F() interface{I} }
8111 if (type->classification() != Type::TYPE_NAMED
8112 && type->classification() != Type::TYPE_INTERFACE)
8113 return false;
8114 if (this->types_seen_ == NULL)
8115 this->types_seen_ = new Types_seen();
8116 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
8117 return !ins.second;
8120 // Record that we are looking at an expression, and return true if we
8121 // have already seen it. NB: this routine used to assert if the traverse
8122 // mask did not include expressions/types -- this is no longer the case,
8123 // since it can be useful to remember specific expressions during
8124 // walks that only cover statements.
8126 bool
8127 Traverse::remember_expression(const Expression* expression)
8129 if (this->expressions_seen_ == NULL)
8130 this->expressions_seen_ = new Expressions_seen();
8131 std::pair<Expressions_seen::iterator, bool> ins =
8132 this->expressions_seen_->insert(expression);
8133 return !ins.second;
8136 // The default versions of these functions should never be called: the
8137 // traversal mask indicates which functions may be called.
8140 Traverse::variable(Named_object*)
8142 go_unreachable();
8146 Traverse::constant(Named_object*, bool)
8148 go_unreachable();
8152 Traverse::function(Named_object*)
8154 go_unreachable();
8158 Traverse::block(Block*)
8160 go_unreachable();
8164 Traverse::statement(Block*, size_t*, Statement*)
8166 go_unreachable();
8170 Traverse::expression(Expression**)
8172 go_unreachable();
8176 Traverse::type(Type*)
8178 go_unreachable();
8181 // Class Statement_inserter.
8183 void
8184 Statement_inserter::insert(Statement* s)
8186 if (this->block_ != NULL)
8188 go_assert(this->pindex_ != NULL);
8189 this->block_->insert_statement_before(*this->pindex_, s);
8190 ++*this->pindex_;
8192 else if (this->var_ != NULL)
8193 this->var_->add_preinit_statement(this->gogo_, s);
8194 else
8195 go_assert(saw_errors());