compiler: avoid GCC middle-end control warnings
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blobb1c780794c905162e2badc5e60a8c8e07e8a8125
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 nil_check_size_threshold_(4096),
59 verify_types_(),
60 interface_types_(),
61 specific_type_functions_(),
62 specific_type_functions_are_written_(false),
63 named_types_are_converted_(false),
64 analysis_sets_(),
65 gc_roots_()
67 const Location loc = Linemap::predeclared_location();
69 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
70 RUNTIME_TYPE_KIND_UINT8);
71 this->add_named_type(uint8_type);
72 this->add_named_type(Type::make_integer_type("uint16", true, 16,
73 RUNTIME_TYPE_KIND_UINT16));
74 this->add_named_type(Type::make_integer_type("uint32", true, 32,
75 RUNTIME_TYPE_KIND_UINT32));
76 this->add_named_type(Type::make_integer_type("uint64", true, 64,
77 RUNTIME_TYPE_KIND_UINT64));
79 this->add_named_type(Type::make_integer_type("int8", false, 8,
80 RUNTIME_TYPE_KIND_INT8));
81 this->add_named_type(Type::make_integer_type("int16", false, 16,
82 RUNTIME_TYPE_KIND_INT16));
83 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
84 RUNTIME_TYPE_KIND_INT32);
85 this->add_named_type(int32_type);
86 this->add_named_type(Type::make_integer_type("int64", false, 64,
87 RUNTIME_TYPE_KIND_INT64));
89 this->add_named_type(Type::make_float_type("float32", 32,
90 RUNTIME_TYPE_KIND_FLOAT32));
91 this->add_named_type(Type::make_float_type("float64", 64,
92 RUNTIME_TYPE_KIND_FLOAT64));
94 this->add_named_type(Type::make_complex_type("complex64", 64,
95 RUNTIME_TYPE_KIND_COMPLEX64));
96 this->add_named_type(Type::make_complex_type("complex128", 128,
97 RUNTIME_TYPE_KIND_COMPLEX128));
99 int int_type_size = pointer_size;
100 if (int_type_size < 32)
101 int_type_size = 32;
102 this->add_named_type(Type::make_integer_type("uint", true,
103 int_type_size,
104 RUNTIME_TYPE_KIND_UINT));
105 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
106 RUNTIME_TYPE_KIND_INT);
107 this->add_named_type(int_type);
109 this->add_named_type(Type::make_integer_type("uintptr", true,
110 pointer_size,
111 RUNTIME_TYPE_KIND_UINTPTR));
113 // "byte" is an alias for "uint8".
114 uint8_type->integer_type()->set_is_byte();
115 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
116 loc);
117 byte_type->type_value()->set_is_alias();
118 this->add_named_type(byte_type->type_value());
120 // "rune" is an alias for "int32".
121 int32_type->integer_type()->set_is_rune();
122 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
123 loc);
124 rune_type->type_value()->set_is_alias();
125 this->add_named_type(rune_type->type_value());
127 this->add_named_type(Type::make_named_bool_type());
129 this->add_named_type(Type::make_named_string_type());
131 // "error" is interface { Error() string }.
133 Typed_identifier_list *methods = new Typed_identifier_list;
134 Typed_identifier_list *results = new Typed_identifier_list;
135 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
136 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
137 methods->push_back(Typed_identifier("Error", method_type, loc));
138 Interface_type *error_iface = Type::make_interface_type(methods, loc);
139 error_iface->finalize_methods();
140 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
141 this->add_named_type(error_type);
144 this->globals_->add_constant(Typed_identifier("true",
145 Type::make_boolean_type(),
146 loc),
147 NULL,
148 Expression::make_boolean(true, loc),
150 this->globals_->add_constant(Typed_identifier("false",
151 Type::make_boolean_type(),
152 loc),
153 NULL,
154 Expression::make_boolean(false, loc),
157 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
158 loc),
159 NULL,
160 Expression::make_nil(loc),
163 Type* abstract_int_type = Type::make_abstract_integer_type();
164 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
165 loc),
166 NULL,
167 Expression::make_iota(),
170 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
171 new_type->set_is_varargs();
172 new_type->set_is_builtin();
173 this->globals_->add_function_declaration("new", NULL, new_type, loc);
175 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
176 make_type->set_is_varargs();
177 make_type->set_is_builtin();
178 this->globals_->add_function_declaration("make", NULL, make_type, loc);
180 Typed_identifier_list* len_result = new Typed_identifier_list();
181 len_result->push_back(Typed_identifier("", int_type, loc));
182 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
183 loc);
184 len_type->set_is_builtin();
185 this->globals_->add_function_declaration("len", NULL, len_type, loc);
187 Typed_identifier_list* cap_result = new Typed_identifier_list();
188 cap_result->push_back(Typed_identifier("", int_type, loc));
189 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
190 loc);
191 cap_type->set_is_builtin();
192 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
194 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
195 print_type->set_is_varargs();
196 print_type->set_is_builtin();
197 this->globals_->add_function_declaration("print", NULL, print_type, loc);
199 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
200 print_type->set_is_varargs();
201 print_type->set_is_builtin();
202 this->globals_->add_function_declaration("println", NULL, print_type, loc);
204 Type *empty = Type::make_empty_interface_type(loc);
205 Typed_identifier_list* panic_parms = new Typed_identifier_list();
206 panic_parms->push_back(Typed_identifier("e", empty, loc));
207 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
208 NULL, loc);
209 panic_type->set_is_builtin();
210 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
212 Typed_identifier_list* recover_result = new Typed_identifier_list();
213 recover_result->push_back(Typed_identifier("", empty, loc));
214 Function_type* recover_type = Type::make_function_type(NULL, NULL,
215 recover_result,
216 loc);
217 recover_type->set_is_builtin();
218 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
220 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
221 close_type->set_is_varargs();
222 close_type->set_is_builtin();
223 this->globals_->add_function_declaration("close", NULL, close_type, loc);
225 Typed_identifier_list* copy_result = new Typed_identifier_list();
226 copy_result->push_back(Typed_identifier("", int_type, loc));
227 Function_type* copy_type = Type::make_function_type(NULL, NULL,
228 copy_result, loc);
229 copy_type->set_is_varargs();
230 copy_type->set_is_builtin();
231 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
233 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
234 append_type->set_is_varargs();
235 append_type->set_is_builtin();
236 this->globals_->add_function_declaration("append", NULL, append_type, loc);
238 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
239 complex_type->set_is_varargs();
240 complex_type->set_is_builtin();
241 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
243 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
244 real_type->set_is_varargs();
245 real_type->set_is_builtin();
246 this->globals_->add_function_declaration("real", NULL, real_type, loc);
248 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
249 imag_type->set_is_varargs();
250 imag_type->set_is_builtin();
251 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
253 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
254 delete_type->set_is_varargs();
255 delete_type->set_is_builtin();
256 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
259 // Convert a pkgpath into a string suitable for a symbol. Note that
260 // this transformation is convenient but imperfect. A -fgo-pkgpath
261 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
262 // possibly leading to link time errors.
264 std::string
265 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
267 std::string s = pkgpath;
268 for (size_t i = 0; i < s.length(); ++i)
270 char c = s[i];
271 if ((c >= 'a' && c <= 'z')
272 || (c >= 'A' && c <= 'Z')
273 || (c >= '0' && c <= '9'))
275 else
276 s[i] = '_';
278 return s;
281 // Get the package path to use for type reflection data. This should
282 // ideally be unique across the entire link.
284 const std::string&
285 Gogo::pkgpath() const
287 go_assert(this->pkgpath_set_);
288 return this->pkgpath_;
291 // Set the package path from the -fgo-pkgpath command line option.
293 void
294 Gogo::set_pkgpath(const std::string& arg)
296 go_assert(!this->pkgpath_set_);
297 this->pkgpath_ = arg;
298 this->pkgpath_set_ = true;
299 this->pkgpath_from_option_ = true;
302 // Get the package path to use for symbol names.
304 const std::string&
305 Gogo::pkgpath_symbol() const
307 go_assert(this->pkgpath_set_);
308 return this->pkgpath_symbol_;
311 // Set the unique prefix to use to determine the package path, from
312 // the -fgo-prefix command line option.
314 void
315 Gogo::set_prefix(const std::string& arg)
317 go_assert(!this->prefix_from_option_);
318 this->prefix_ = arg;
319 this->prefix_from_option_ = true;
322 // Munge name for use in an error message.
324 std::string
325 Gogo::message_name(const std::string& name)
327 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
330 // Get the package name.
332 const std::string&
333 Gogo::package_name() const
335 go_assert(this->package_ != NULL);
336 return this->package_->package_name();
339 // Set the package name.
341 void
342 Gogo::set_package_name(const std::string& package_name,
343 Location location)
345 if (this->package_ != NULL)
347 if (this->package_->package_name() != package_name)
348 go_error_at(location, "expected package %<%s%>",
349 Gogo::message_name(this->package_->package_name()).c_str());
350 return;
353 // Now that we know the name of the package we are compiling, set
354 // the package path to use for reflect.Type.PkgPath and global
355 // symbol names.
356 if (this->pkgpath_set_)
357 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
358 else
360 if (!this->prefix_from_option_ && package_name == "main")
362 this->pkgpath_ = package_name;
363 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(package_name);
365 else
367 if (!this->prefix_from_option_)
368 this->prefix_ = "go";
369 this->pkgpath_ = this->prefix_ + '.' + package_name;
370 this->pkgpath_symbol_ = (Gogo::pkgpath_for_symbol(this->prefix_) + '.'
371 + Gogo::pkgpath_for_symbol(package_name));
373 this->pkgpath_set_ = true;
376 this->package_ = this->register_package(this->pkgpath_,
377 this->pkgpath_symbol_, location);
378 this->package_->set_package_name(package_name, location);
380 if (this->is_main_package())
382 // Declare "main" as a function which takes no parameters and
383 // returns no value.
384 Location uloc = Linemap::unknown_location();
385 this->declare_function(Gogo::pack_hidden_name("main", false),
386 Type::make_function_type (NULL, NULL, NULL, uloc),
387 uloc);
391 // Return whether this is the "main" package. This is not true if
392 // -fgo-pkgpath or -fgo-prefix was used.
394 bool
395 Gogo::is_main_package() const
397 return (this->package_name() == "main"
398 && !this->pkgpath_from_option_
399 && !this->prefix_from_option_);
402 // Import a package.
404 void
405 Gogo::import_package(const std::string& filename,
406 const std::string& local_name,
407 bool is_local_name_exported,
408 bool must_exist,
409 Location location)
411 if (filename.empty())
413 go_error_at(location, "import path is empty");
414 return;
417 const char *pf = filename.data();
418 const char *pend = pf + filename.length();
419 while (pf < pend)
421 unsigned int c;
422 int adv = Lex::fetch_char(pf, &c);
423 if (adv == 0)
425 go_error_at(location, "import path contains invalid UTF-8 sequence");
426 return;
428 if (c == '\0')
430 go_error_at(location, "import path contains NUL");
431 return;
433 if (c < 0x20 || c == 0x7f)
435 go_error_at(location, "import path contains control character");
436 return;
438 if (c == '\\')
440 go_error_at(location, "import path contains backslash; use slash");
441 return;
443 if (Lex::is_unicode_space(c))
445 go_error_at(location, "import path contains space character");
446 return;
448 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
450 go_error_at(location,
451 "import path contains invalid character '%c'", c);
452 return;
454 pf += adv;
457 if (IS_ABSOLUTE_PATH(filename.c_str()))
459 go_error_at(location, "import path cannot be absolute path");
460 return;
463 if (local_name == "init")
464 go_error_at(location, "cannot import package as init");
466 if (filename == "unsafe")
468 this->import_unsafe(local_name, is_local_name_exported, location);
469 this->current_file_imported_unsafe_ = true;
470 return;
473 Imports::const_iterator p = this->imports_.find(filename);
474 if (p != this->imports_.end())
476 Package* package = p->second;
477 package->set_location(location);
478 std::string ln = local_name;
479 bool is_ln_exported = is_local_name_exported;
480 if (ln.empty())
482 ln = package->package_name();
483 go_assert(!ln.empty());
484 is_ln_exported = Lex::is_exported_name(ln);
486 if (ln == "_")
488 else if (ln == ".")
490 Bindings* bindings = package->bindings();
491 for (Bindings::const_declarations_iterator p =
492 bindings->begin_declarations();
493 p != bindings->end_declarations();
494 ++p)
495 this->add_dot_import_object(p->second);
496 std::string dot_alias = "." + package->package_name();
497 package->add_alias(dot_alias, location);
499 else
501 package->add_alias(ln, location);
502 ln = this->pack_hidden_name(ln, is_ln_exported);
503 this->package_->bindings()->add_package(ln, package);
505 return;
508 Import::Stream* stream = Import::open_package(filename, location,
509 this->relative_import_path_);
510 if (stream == NULL)
512 if (must_exist)
513 go_error_at(location, "import file %qs not found", filename.c_str());
514 return;
517 Import imp(stream, location);
518 imp.register_builtin_types(this);
519 Package* package = imp.import(this, local_name, is_local_name_exported);
520 if (package != NULL)
522 if (package->pkgpath() == this->pkgpath())
523 go_error_at(location,
524 ("imported package uses same package path as package "
525 "being compiled (see -fgo-pkgpath option)"));
527 this->imports_.insert(std::make_pair(filename, package));
530 delete stream;
533 Import_init *
534 Gogo::lookup_init(const std::string& init_name)
536 Import_init tmp("", init_name, -1);
537 Import_init_set::iterator it = this->imported_init_fns_.find(&tmp);
538 return (it != this->imported_init_fns_.end()) ? *it : NULL;
541 // Add an import control function for an imported package to the list.
543 void
544 Gogo::add_import_init_fn(const std::string& package_name,
545 const std::string& init_name, int prio)
547 for (Import_init_set::iterator p =
548 this->imported_init_fns_.begin();
549 p != this->imported_init_fns_.end();
550 ++p)
552 Import_init *ii = (*p);
553 if (ii->init_name() == init_name)
555 // If a test of package P1, built as part of package P1,
556 // imports package P2, and P2 imports P1 (perhaps
557 // indirectly), then we will see the same import name with
558 // different import priorities. That is OK, so don't give
559 // an error about it.
560 if (ii->package_name() != package_name)
562 go_error_at(Linemap::unknown_location(),
563 "duplicate package initialization name %qs",
564 Gogo::message_name(init_name).c_str());
565 go_inform(Linemap::unknown_location(), "used by package %qs",
566 Gogo::message_name(ii->package_name()).c_str());
567 go_inform(Linemap::unknown_location(), " and by package %qs",
568 Gogo::message_name(package_name).c_str());
570 ii->set_priority(prio);
571 return;
575 Import_init* nii = new Import_init(package_name, init_name, prio);
576 this->imported_init_fns_.insert(nii);
579 // Return whether we are at the global binding level.
581 bool
582 Gogo::in_global_scope() const
584 return this->functions_.empty();
587 // Return the current binding contour.
589 Bindings*
590 Gogo::current_bindings()
592 if (!this->functions_.empty())
593 return this->functions_.back().blocks.back()->bindings();
594 else if (this->package_ != NULL)
595 return this->package_->bindings();
596 else
597 return this->globals_;
600 const Bindings*
601 Gogo::current_bindings() const
603 if (!this->functions_.empty())
604 return this->functions_.back().blocks.back()->bindings();
605 else if (this->package_ != NULL)
606 return this->package_->bindings();
607 else
608 return this->globals_;
611 void
612 Gogo::update_init_priority(Import_init* ii,
613 std::set<const Import_init *>* visited)
615 visited->insert(ii);
616 int succ_prior = -1;
618 for (std::set<std::string>::const_iterator pci =
619 ii->precursors().begin();
620 pci != ii->precursors().end();
621 ++pci)
623 Import_init* succ = this->lookup_init(*pci);
624 if (visited->find(succ) == visited->end())
625 update_init_priority(succ, visited);
626 succ_prior = std::max(succ_prior, succ->priority());
628 if (ii->priority() <= succ_prior)
629 ii->set_priority(succ_prior + 1);
632 void
633 Gogo::recompute_init_priorities()
635 std::set<Import_init *> nonroots;
637 for (Import_init_set::const_iterator p =
638 this->imported_init_fns_.begin();
639 p != this->imported_init_fns_.end();
640 ++p)
642 const Import_init *ii = *p;
643 for (std::set<std::string>::const_iterator pci =
644 ii->precursors().begin();
645 pci != ii->precursors().end();
646 ++pci)
648 Import_init* ii = this->lookup_init(*pci);
649 nonroots.insert(ii);
653 // Recursively update priorities starting at roots.
654 std::set<const Import_init*> visited;
655 for (Import_init_set::iterator p =
656 this->imported_init_fns_.begin();
657 p != this->imported_init_fns_.end();
658 ++p)
660 Import_init* ii = *p;
661 if (nonroots.find(ii) != nonroots.end())
662 continue;
663 update_init_priority(ii, &visited);
667 // Add statements to INIT_STMTS which run the initialization
668 // functions for imported packages. This is only used for the "main"
669 // package.
671 void
672 Gogo::init_imports(std::vector<Bstatement*>& init_stmts, Bfunction *bfunction)
674 go_assert(this->is_main_package());
676 if (this->imported_init_fns_.empty())
677 return;
679 Location unknown_loc = Linemap::unknown_location();
680 Function_type* func_type =
681 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
682 Btype* fntype = func_type->get_backend_fntype(this);
684 // Recompute init priorities based on a walk of the init graph.
685 recompute_init_priorities();
687 // We must call them in increasing priority order.
688 std::vector<const Import_init*> v;
689 for (Import_init_set::const_iterator p =
690 this->imported_init_fns_.begin();
691 p != this->imported_init_fns_.end();
692 ++p)
694 if ((*p)->priority() < 0)
695 go_error_at(Linemap::unknown_location(),
696 "internal error: failed to set init priority for %s",
697 (*p)->package_name().c_str());
698 v.push_back(*p);
700 std::sort(v.begin(), v.end(), priority_compare);
702 // We build calls to the init functions, which take no arguments.
703 std::vector<Bexpression*> empty_args;
704 for (std::vector<const Import_init*>::const_iterator p = v.begin();
705 p != v.end();
706 ++p)
708 const Import_init* ii = *p;
709 std::string user_name = ii->package_name() + ".init";
710 const std::string& init_name(ii->init_name());
712 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
713 true, true, true, false,
714 false, false, unknown_loc);
715 Bexpression* pfunc_code =
716 this->backend()->function_code_expression(pfunc, unknown_loc);
717 Bexpression* pfunc_call =
718 this->backend()->call_expression(bfunction, pfunc_code, empty_args,
719 NULL, unknown_loc);
720 init_stmts.push_back(this->backend()->expression_statement(bfunction,
721 pfunc_call));
725 // Register global variables with the garbage collector. We need to
726 // register all variables which can hold a pointer value. They become
727 // roots during the mark phase. We build a struct that is easy to
728 // hook into a list of roots.
730 // type gcRoot struct {
731 // decl unsafe.Pointer // Pointer to variable.
732 // size uintptr // Total size of variable.
733 // ptrdata uintptr // Length of variable's gcdata.
734 // gcdata *byte // Pointer mask.
735 // }
737 // type gcRootList struct {
738 // next *gcRootList
739 // count int
740 // roots [...]gcRoot
741 // }
743 // The last entry in the roots array has a NULL decl field.
745 void
746 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
747 std::vector<Bstatement*>& init_stmts,
748 Bfunction* init_bfn)
750 if (var_gc.empty() && this->gc_roots_.empty())
751 return;
753 Type* pvt = Type::make_pointer_type(Type::make_void_type());
754 Type* uintptr_type = Type::lookup_integer_type("uintptr");
755 Type* byte_type = this->lookup_global("byte")->type_value();
756 Type* pointer_byte_type = Type::make_pointer_type(byte_type);
757 Struct_type* root_type =
758 Type::make_builtin_struct_type(4,
759 "decl", pvt,
760 "size", uintptr_type,
761 "ptrdata", uintptr_type,
762 "gcdata", pointer_byte_type);
764 Location builtin_loc = Linemap::predeclared_location();
765 unsigned long roots_len = var_gc.size() + this->gc_roots_.size();
766 Expression* length = Expression::make_integer_ul(roots_len, NULL,
767 builtin_loc);
768 Array_type* root_array_type = Type::make_array_type(root_type, length);
769 root_array_type->set_is_array_incomparable();
771 Type* int_type = Type::lookup_integer_type("int");
772 Struct_type* root_list_type =
773 Type::make_builtin_struct_type(3,
774 "next", pvt,
775 "count", int_type,
776 "roots", root_array_type);
778 // Build an initializer for the roots array.
780 Expression_list* roots_init = new Expression_list();
782 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
783 p != var_gc.end();
784 ++p)
786 Expression_list* init = new Expression_list();
788 Location no_loc = (*p)->location();
789 Expression* decl = Expression::make_var_reference(*p, no_loc);
790 Expression* decl_addr =
791 Expression::make_unary(OPERATOR_AND, decl, no_loc);
792 decl_addr->unary_expression()->set_does_not_escape();
793 decl_addr = Expression::make_cast(pvt, decl_addr, no_loc);
794 init->push_back(decl_addr);
796 Expression* size =
797 Expression::make_type_info(decl->type(),
798 Expression::TYPE_INFO_SIZE);
799 init->push_back(size);
801 Expression* ptrdata =
802 Expression::make_type_info(decl->type(),
803 Expression::TYPE_INFO_BACKEND_PTRDATA);
804 init->push_back(ptrdata);
806 Expression* gcdata = Expression::make_ptrmask_symbol(decl->type());
807 init->push_back(gcdata);
809 Expression* root_ctor =
810 Expression::make_struct_composite_literal(root_type, init, no_loc);
811 roots_init->push_back(root_ctor);
814 for (std::vector<Expression*>::const_iterator p = this->gc_roots_.begin();
815 p != this->gc_roots_.end();
816 ++p)
818 Expression_list *init = new Expression_list();
820 Expression* expr = *p;
821 Location eloc = expr->location();
822 init->push_back(Expression::make_cast(pvt, expr, eloc));
824 Type* type = expr->type()->points_to();
825 go_assert(type != NULL);
827 Expression* size =
828 Expression::make_type_info(type,
829 Expression::TYPE_INFO_SIZE);
830 init->push_back(size);
832 Expression* ptrdata =
833 Expression::make_type_info(type,
834 Expression::TYPE_INFO_BACKEND_PTRDATA);
835 init->push_back(ptrdata);
837 Expression* gcdata = Expression::make_ptrmask_symbol(type);
838 init->push_back(gcdata);
840 Expression* root_ctor =
841 Expression::make_struct_composite_literal(root_type, init, eloc);
842 roots_init->push_back(root_ctor);
845 // Build a constructor for the struct.
847 Expression_list* root_list_init = new Expression_list();
848 root_list_init->push_back(Expression::make_nil(builtin_loc));
849 root_list_init->push_back(Expression::make_integer_ul(roots_len, int_type,
850 builtin_loc));
852 Expression* roots_ctor =
853 Expression::make_array_composite_literal(root_array_type, roots_init,
854 builtin_loc);
855 root_list_init->push_back(roots_ctor);
857 Expression* root_list_ctor =
858 Expression::make_struct_composite_literal(root_list_type, root_list_init,
859 builtin_loc);
861 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
862 builtin_loc);
863 root_addr->unary_expression()->set_is_gc_root();
864 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
865 builtin_loc, 1, root_addr);
867 Translate_context context(this, NULL, NULL, NULL);
868 Bexpression* bcall = register_roots->get_backend(&context);
869 init_stmts.push_back(this->backend()->expression_statement(init_bfn, bcall));
872 // Build the decl for the initialization function.
874 Named_object*
875 Gogo::initialization_function_decl()
877 std::string name = this->get_init_fn_name();
878 Location loc = this->package_->location();
880 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
881 Function* initfn = new Function(fntype, NULL, NULL, loc);
882 return Named_object::make_function(name, NULL, initfn);
885 // Create the magic initialization function. CODE_STMT is the
886 // code that it needs to run.
888 Named_object*
889 Gogo::create_initialization_function(Named_object* initfn,
890 Bstatement* code_stmt)
892 // Make sure that we thought we needed an initialization function,
893 // as otherwise we will not have reported it in the export data.
894 go_assert(this->is_main_package() || this->need_init_fn_);
896 if (initfn == NULL)
897 initfn = this->initialization_function_decl();
899 // Bind the initialization function code to a block.
900 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
901 Location pkg_loc = this->package_->location();
902 std::vector<Bvariable*> vars;
903 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
905 if (!this->backend()->function_set_body(fndecl, code_stmt))
907 go_assert(saw_errors());
908 return NULL;
910 return initfn;
913 // Search for references to VAR in any statements or called functions.
915 class Find_var : public Traverse
917 public:
918 // A hash table we use to avoid looping. The index is the name of a
919 // named object. We only look through objects defined in this
920 // package.
921 typedef Unordered_set(const void*) Seen_objects;
923 Find_var(Named_object* var, Seen_objects* seen_objects)
924 : Traverse(traverse_expressions),
925 var_(var), seen_objects_(seen_objects), found_(false)
928 // Whether the variable was found.
929 bool
930 found() const
931 { return this->found_; }
934 expression(Expression**);
936 private:
937 // The variable we are looking for.
938 Named_object* var_;
939 // Names of objects we have already seen.
940 Seen_objects* seen_objects_;
941 // True if the variable was found.
942 bool found_;
945 // See if EXPR refers to VAR, looking through function calls and
946 // variable initializations.
949 Find_var::expression(Expression** pexpr)
951 Expression* e = *pexpr;
953 Var_expression* ve = e->var_expression();
954 if (ve != NULL)
956 Named_object* v = ve->named_object();
957 if (v == this->var_)
959 this->found_ = true;
960 return TRAVERSE_EXIT;
963 if (v->is_variable() && v->package() == NULL)
965 Expression* init = v->var_value()->init();
966 if (init != NULL)
968 std::pair<Seen_objects::iterator, bool> ins =
969 this->seen_objects_->insert(v);
970 if (ins.second)
972 // This is the first time we have seen this name.
973 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
974 return TRAVERSE_EXIT;
980 // We traverse the code of any function or bound method we see. Note that
981 // this means that we will traverse the code of a function or bound method
982 // whose address is taken even if it is not called.
983 Func_expression* fe = e->func_expression();
984 Bound_method_expression* bme = e->bound_method_expression();
985 if (fe != NULL || bme != NULL)
987 const Named_object* f = fe != NULL ? fe->named_object() : bme->function();
988 if (f->is_function() && f->package() == NULL)
990 std::pair<Seen_objects::iterator, bool> ins =
991 this->seen_objects_->insert(f);
992 if (ins.second)
994 // This is the first time we have seen this name.
995 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
996 return TRAVERSE_EXIT;
1001 Temporary_reference_expression* tre = e->temporary_reference_expression();
1002 if (tre != NULL)
1004 Temporary_statement* ts = tre->statement();
1005 Expression* init = ts->init();
1006 if (init != NULL)
1008 std::pair<Seen_objects::iterator, bool> ins =
1009 this->seen_objects_->insert(ts);
1010 if (ins.second)
1012 // This is the first time we have seen this temporary
1013 // statement.
1014 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
1015 return TRAVERSE_EXIT;
1020 return TRAVERSE_CONTINUE;
1023 // Return true if EXPR, PREINIT, or DEP refers to VAR.
1025 static bool
1026 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1027 Named_object* var)
1029 Find_var::Seen_objects seen_objects;
1030 Find_var find_var(var, &seen_objects);
1031 if (expr != NULL)
1032 Expression::traverse(&expr, &find_var);
1033 if (preinit != NULL)
1034 preinit->traverse(&find_var);
1035 if (dep != NULL)
1037 Expression* init = dep->var_value()->init();
1038 if (init != NULL)
1039 Expression::traverse(&init, &find_var);
1040 if (dep->var_value()->has_pre_init())
1041 dep->var_value()->preinit()->traverse(&find_var);
1044 return find_var.found();
1047 // Sort variable initializations. If the initialization expression
1048 // for variable A refers directly or indirectly to the initialization
1049 // expression for variable B, then we must initialize B before A.
1051 class Var_init
1053 public:
1054 Var_init()
1055 : var_(NULL), init_(NULL), dep_count_(0)
1058 Var_init(Named_object* var, Bstatement* init)
1059 : var_(var), init_(init), dep_count_(0)
1062 // Return the variable.
1063 Named_object*
1064 var() const
1065 { return this->var_; }
1067 // Return the initialization expression.
1068 Bstatement*
1069 init() const
1070 { return this->init_; }
1072 // Return the number of remaining dependencies.
1073 size_t
1074 dep_count() const
1075 { return this->dep_count_; }
1077 // Increment the number of dependencies.
1078 void
1079 add_dependency()
1080 { ++this->dep_count_; }
1082 // Decrement the number of dependencies.
1083 void
1084 remove_dependency()
1085 { --this->dep_count_; }
1087 private:
1088 // The variable being initialized.
1089 Named_object* var_;
1090 // The initialization statement.
1091 Bstatement* init_;
1092 // The number of initializations this is dependent on. A variable
1093 // initialization should not be emitted if any of its dependencies
1094 // have not yet been resolved.
1095 size_t dep_count_;
1098 // For comparing Var_init keys in a map.
1100 inline bool
1101 operator<(const Var_init& v1, const Var_init& v2)
1102 { return v1.var()->name() < v2.var()->name(); }
1104 typedef std::list<Var_init> Var_inits;
1106 // Sort the variable initializations. The rule we follow is that we
1107 // emit them in the order they appear in the array, except that if the
1108 // initialization expression for a variable V1 depends upon another
1109 // variable V2 then we initialize V1 after V2.
1111 static void
1112 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1114 if (var_inits->empty())
1115 return;
1117 typedef std::pair<Named_object*, Named_object*> No_no;
1118 typedef std::map<No_no, bool> Cache;
1119 Cache cache;
1121 // A mapping from a variable initialization to a set of
1122 // variable initializations that depend on it.
1123 typedef std::map<Var_init, std::set<Var_init*> > Init_deps;
1124 Init_deps init_deps;
1125 bool init_loop = false;
1126 for (Var_inits::iterator p1 = var_inits->begin();
1127 p1 != var_inits->end();
1128 ++p1)
1130 Named_object* var = p1->var();
1131 Expression* init = var->var_value()->init();
1132 Block* preinit = var->var_value()->preinit();
1133 Named_object* dep = gogo->var_depends_on(var->var_value());
1135 // Start walking through the list to see which variables VAR
1136 // needs to wait for.
1137 for (Var_inits::iterator p2 = var_inits->begin();
1138 p2 != var_inits->end();
1139 ++p2)
1141 if (var == p2->var())
1142 continue;
1144 Named_object* p2var = p2->var();
1145 No_no key(var, p2var);
1146 std::pair<Cache::iterator, bool> ins =
1147 cache.insert(std::make_pair(key, false));
1148 if (ins.second)
1149 ins.first->second = expression_requires(init, preinit, dep, p2var);
1150 if (ins.first->second)
1152 // VAR depends on P2VAR.
1153 init_deps[*p2].insert(&(*p1));
1154 p1->add_dependency();
1156 // Check for cycles.
1157 key = std::make_pair(p2var, var);
1158 ins = cache.insert(std::make_pair(key, false));
1159 if (ins.second)
1160 ins.first->second =
1161 expression_requires(p2var->var_value()->init(),
1162 p2var->var_value()->preinit(),
1163 gogo->var_depends_on(p2var->var_value()),
1164 var);
1165 if (ins.first->second)
1167 go_error_at(var->location(),
1168 ("initialization expressions for %qs and "
1169 "%qs depend upon each other"),
1170 var->message_name().c_str(),
1171 p2var->message_name().c_str());
1172 go_inform(p2->var()->location(), "%qs defined here",
1173 p2var->message_name().c_str());
1174 init_loop = true;
1175 break;
1181 // If there are no dependencies then the declaration order is sorted.
1182 if (!init_deps.empty() && !init_loop)
1184 // Otherwise, sort variable initializations by emitting all variables with
1185 // no dependencies in declaration order. VAR_INITS is already in
1186 // declaration order.
1187 Var_inits ready;
1188 while (!var_inits->empty())
1190 Var_inits::iterator v1;;
1191 for (v1 = var_inits->begin(); v1 != var_inits->end(); ++v1)
1193 if (v1->dep_count() == 0)
1194 break;
1196 go_assert(v1 != var_inits->end());
1198 // V1 either has no dependencies or its dependencies have already
1199 // been emitted, add it to READY next. When V1 is emitted, remove
1200 // a dependency from each V that depends on V1.
1201 ready.splice(ready.end(), *var_inits, v1);
1203 Init_deps::iterator p1 = init_deps.find(*v1);
1204 if (p1 != init_deps.end())
1206 std::set<Var_init*> resolved = p1->second;
1207 for (std::set<Var_init*>::iterator pv = resolved.begin();
1208 pv != resolved.end();
1209 ++pv)
1210 (*pv)->remove_dependency();
1211 init_deps.erase(p1);
1214 var_inits->swap(ready);
1215 go_assert(init_deps.empty());
1218 // VAR_INITS is in the correct order. For each VAR in VAR_INITS,
1219 // check for a loop of VAR on itself.
1220 // interpret as a loop.
1221 for (Var_inits::const_iterator p = var_inits->begin();
1222 p != var_inits->end();
1223 ++p)
1224 gogo->check_self_dep(p->var());
1227 // Give an error if the initialization expression for VAR depends on
1228 // itself. We only check if INIT is not NULL and there is no
1229 // dependency; when INIT is NULL, it means that PREINIT sets VAR,
1230 // which we will interpret as a loop.
1232 void
1233 Gogo::check_self_dep(Named_object* var)
1235 Expression* init = var->var_value()->init();
1236 Block* preinit = var->var_value()->preinit();
1237 Named_object* dep = this->var_depends_on(var->var_value());
1238 if (init != NULL
1239 && dep == NULL
1240 && expression_requires(init, preinit, NULL, var))
1241 go_error_at(var->location(),
1242 "initialization expression for %qs depends upon itself",
1243 var->message_name().c_str());
1246 // Write out the global definitions.
1248 void
1249 Gogo::write_globals()
1251 this->build_interface_method_tables();
1253 Bindings* bindings = this->current_bindings();
1255 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1256 p != bindings->end_declarations();
1257 ++p)
1259 // If any function declarations needed a descriptor, make sure
1260 // we build it.
1261 Named_object* no = p->second;
1262 if (no->is_function_declaration())
1263 no->func_declaration_value()->build_backend_descriptor(this);
1266 // Lists of globally declared types, variables, constants, and functions
1267 // that must be defined.
1268 std::vector<Btype*> type_decls;
1269 std::vector<Bvariable*> var_decls;
1270 std::vector<Bexpression*> const_decls;
1271 std::vector<Bfunction*> func_decls;
1273 // The init function declaration and associated Bfunction, if necessary.
1274 Named_object* init_fndecl = NULL;
1275 Bfunction* init_bfn = NULL;
1277 std::vector<Bstatement*> init_stmts;
1278 std::vector<Bstatement*> var_init_stmts;
1280 if (this->is_main_package())
1282 init_fndecl = this->initialization_function_decl();
1283 init_bfn = init_fndecl->func_value()->get_or_make_decl(this, init_fndecl);
1284 this->init_imports(init_stmts, init_bfn);
1287 // A list of variable initializations.
1288 Var_inits var_inits;
1290 // A list of variables which need to be registered with the garbage
1291 // collector.
1292 size_t count_definitions = bindings->size_definitions();
1293 std::vector<Named_object*> var_gc;
1294 var_gc.reserve(count_definitions);
1296 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1297 p != bindings->end_definitions();
1298 ++p)
1300 Named_object* no = *p;
1301 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1303 // There is nothing to do for a package.
1304 if (no->is_package())
1305 continue;
1307 // There is nothing to do for an object which was imported from
1308 // a different package into the global scope.
1309 if (no->package() != NULL)
1310 continue;
1312 // Skip blank named functions and constants.
1313 if ((no->is_function() && no->func_value()->is_sink())
1314 || (no->is_const() && no->const_value()->is_sink()))
1315 continue;
1317 // There is nothing useful we can output for constants which
1318 // have ideal or non-integral type.
1319 if (no->is_const())
1321 Type* type = no->const_value()->type();
1322 if (type == NULL)
1323 type = no->const_value()->expr()->type();
1324 if (type->is_abstract() || !type->is_numeric_type())
1325 continue;
1328 if (!no->is_variable())
1329 no->get_backend(this, const_decls, type_decls, func_decls);
1330 else
1332 Variable* var = no->var_value();
1333 Bvariable* bvar = no->get_backend_variable(this, NULL);
1334 var_decls.push_back(bvar);
1336 // Check for a sink variable, which may be used to run an
1337 // initializer purely for its side effects.
1338 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1340 Bstatement* var_init_stmt = NULL;
1341 if (!var->has_pre_init())
1343 // If the backend representation of the variable initializer is
1344 // constant, we can just set the initial value using
1345 // global_var_set_init instead of during the init() function.
1346 // The initializer is constant if it is the zero-value of the
1347 // variable's type or if the initial value is an immutable value
1348 // that is not copied to the heap.
1349 bool is_static_initializer = false;
1350 if (var->init() == NULL)
1351 is_static_initializer = true;
1352 else
1354 Type* var_type = var->type();
1355 Expression* init = var->init();
1356 Expression* init_cast =
1357 Expression::make_cast(var_type, init, var->location());
1358 is_static_initializer = init_cast->is_static_initializer();
1361 // Non-constant variable initializations might need to create
1362 // temporary variables, which will need the initialization
1363 // function as context.
1364 Named_object* var_init_fn;
1365 if (is_static_initializer)
1366 var_init_fn = NULL;
1367 else
1369 if (init_fndecl == NULL)
1371 init_fndecl = this->initialization_function_decl();
1372 Function* func = init_fndecl->func_value();
1373 init_bfn = func->get_or_make_decl(this, init_fndecl);
1375 var_init_fn = init_fndecl;
1377 Bexpression* var_binit = var->get_init(this, var_init_fn);
1379 if (var_binit == NULL)
1381 else if (is_static_initializer)
1383 if (expression_requires(var->init(), NULL,
1384 this->var_depends_on(var), no))
1385 go_error_at(no->location(),
1386 "initialization expression for %qs depends "
1387 "upon itself",
1388 no->message_name().c_str());
1389 this->backend()->global_variable_set_init(bvar, var_binit);
1391 else if (is_sink)
1392 var_init_stmt =
1393 this->backend()->expression_statement(init_bfn, var_binit);
1394 else
1396 Location loc = var->location();
1397 Bexpression* var_expr =
1398 this->backend()->var_expression(bvar, loc);
1399 var_init_stmt =
1400 this->backend()->assignment_statement(init_bfn, var_expr,
1401 var_binit, loc);
1404 else
1406 // We are going to create temporary variables which
1407 // means that we need an fndecl.
1408 if (init_fndecl == NULL)
1409 init_fndecl = this->initialization_function_decl();
1411 Bvariable* var_decl = is_sink ? NULL : bvar;
1412 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1415 if (var_init_stmt != NULL)
1417 if (var->init() == NULL && !var->has_pre_init())
1418 var_init_stmts.push_back(var_init_stmt);
1419 else
1420 var_inits.push_back(Var_init(no, var_init_stmt));
1422 else if (this->var_depends_on(var) != NULL)
1424 // This variable is initialized from something that is
1425 // not in its init or preinit. This variable needs to
1426 // participate in dependency analysis sorting, in case
1427 // some other variable depends on this one.
1428 Btype* btype = no->var_value()->type()->get_backend(this);
1429 Bexpression* zero = this->backend()->zero_expression(btype);
1430 Bstatement* zero_stmt =
1431 this->backend()->expression_statement(init_bfn, zero);
1432 var_inits.push_back(Var_init(no, zero_stmt));
1435 // Collect a list of all global variables with pointers,
1436 // to register them for the garbage collector.
1437 if (!is_sink && var->type()->has_pointer())
1439 // Avoid putting runtime.gcRoots itself on the list.
1440 if (this->compiling_runtime()
1441 && this->package_name() == "runtime"
1442 && Gogo::unpack_hidden_name(no->name()) == "gcRoots")
1444 else
1445 var_gc.push_back(no);
1450 // Register global variables with the garbage collector.
1451 this->register_gc_vars(var_gc, init_stmts, init_bfn);
1453 // Simple variable initializations, after all variables are
1454 // registered.
1455 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1457 // Complete variable initializations, first sorting them into a
1458 // workable order.
1459 if (!var_inits.empty())
1461 sort_var_inits(this, &var_inits);
1462 for (Var_inits::const_iterator p = var_inits.begin();
1463 p != var_inits.end();
1464 ++p)
1465 init_stmts.push_back(p->init());
1468 // After all the variables are initialized, call the init
1469 // functions if there are any. Init functions take no arguments, so
1470 // we pass in EMPTY_ARGS to call them.
1471 std::vector<Bexpression*> empty_args;
1472 for (std::vector<Named_object*>::const_iterator p =
1473 this->init_functions_.begin();
1474 p != this->init_functions_.end();
1475 ++p)
1477 Location func_loc = (*p)->location();
1478 Function* func = (*p)->func_value();
1479 Bfunction* initfn = func->get_or_make_decl(this, *p);
1480 Bexpression* func_code =
1481 this->backend()->function_code_expression(initfn, func_loc);
1482 Bexpression* call = this->backend()->call_expression(init_bfn, func_code,
1483 empty_args,
1484 NULL, func_loc);
1485 Bstatement* ist = this->backend()->expression_statement(init_bfn, call);
1486 init_stmts.push_back(ist);
1489 // Set up a magic function to do all the initialization actions.
1490 // This will be called if this package is imported.
1491 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1492 if (this->need_init_fn_ || this->is_main_package())
1494 init_fndecl =
1495 this->create_initialization_function(init_fndecl, init_fncode);
1496 if (init_fndecl != NULL)
1497 func_decls.push_back(init_fndecl->func_value()->get_decl());
1500 // We should not have seen any new bindings created during the conversion.
1501 go_assert(count_definitions == this->current_bindings()->size_definitions());
1503 // Define all globally declared values.
1504 if (!saw_errors())
1505 this->backend()->write_global_definitions(type_decls, const_decls,
1506 func_decls, var_decls);
1509 // Return the current block.
1511 Block*
1512 Gogo::current_block()
1514 if (this->functions_.empty())
1515 return NULL;
1516 else
1517 return this->functions_.back().blocks.back();
1520 // Look up a name in the current binding contour. If PFUNCTION is not
1521 // NULL, set it to the function in which the name is defined, or NULL
1522 // if the name is defined in global scope.
1524 Named_object*
1525 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1527 if (pfunction != NULL)
1528 *pfunction = NULL;
1530 if (Gogo::is_sink_name(name))
1531 return Named_object::make_sink();
1533 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1534 p != this->functions_.rend();
1535 ++p)
1537 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1538 if (ret != NULL)
1540 if (pfunction != NULL)
1541 *pfunction = p->function;
1542 return ret;
1546 if (this->package_ != NULL)
1548 Named_object* ret = this->package_->bindings()->lookup(name);
1549 if (ret != NULL)
1551 if (ret->package() != NULL)
1553 std::string dot_alias = "." + ret->package()->package_name();
1554 ret->package()->note_usage(dot_alias);
1556 return ret;
1560 // We do not look in the global namespace. If we did, the global
1561 // namespace would effectively hide names which were defined in
1562 // package scope which we have not yet seen. Instead,
1563 // define_global_names is called after parsing is over to connect
1564 // undefined names at package scope with names defined at global
1565 // scope.
1567 return NULL;
1570 // Look up a name in the current block, without searching enclosing
1571 // blocks.
1573 Named_object*
1574 Gogo::lookup_in_block(const std::string& name) const
1576 go_assert(!this->functions_.empty());
1577 go_assert(!this->functions_.back().blocks.empty());
1578 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1581 // Look up a name in the global namespace.
1583 Named_object*
1584 Gogo::lookup_global(const char* name) const
1586 return this->globals_->lookup(name);
1589 // Add an imported package.
1591 Package*
1592 Gogo::add_imported_package(const std::string& real_name,
1593 const std::string& alias_arg,
1594 bool is_alias_exported,
1595 const std::string& pkgpath,
1596 const std::string& pkgpath_symbol,
1597 Location location,
1598 bool* padd_to_globals)
1600 Package* ret = this->register_package(pkgpath, pkgpath_symbol, location);
1601 ret->set_package_name(real_name, location);
1603 *padd_to_globals = false;
1605 if (alias_arg == "_")
1607 else if (alias_arg == ".")
1609 *padd_to_globals = true;
1610 std::string dot_alias = "." + real_name;
1611 ret->add_alias(dot_alias, location);
1613 else
1615 std::string alias = alias_arg;
1616 if (alias.empty())
1618 alias = real_name;
1619 is_alias_exported = Lex::is_exported_name(alias);
1621 ret->add_alias(alias, location);
1622 alias = this->pack_hidden_name(alias, is_alias_exported);
1623 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1624 if (!no->is_package())
1625 return NULL;
1628 return ret;
1631 // Register a package. This package may or may not be imported. This
1632 // returns the Package structure for the package, creating if it
1633 // necessary. LOCATION is the location of the import statement that
1634 // led us to see this package. PKGPATH_SYMBOL is the symbol to use
1635 // for names in the package; it may be the empty string, in which case
1636 // we either get it later or make a guess when we need it.
1638 Package*
1639 Gogo::register_package(const std::string& pkgpath,
1640 const std::string& pkgpath_symbol, Location location)
1642 Package* package = NULL;
1643 std::pair<Packages::iterator, bool> ins =
1644 this->packages_.insert(std::make_pair(pkgpath, package));
1645 if (!ins.second)
1647 // We have seen this package name before.
1648 package = ins.first->second;
1649 go_assert(package != NULL && package->pkgpath() == pkgpath);
1650 if (!pkgpath_symbol.empty())
1651 package->set_pkgpath_symbol(pkgpath_symbol);
1652 if (Linemap::is_unknown_location(package->location()))
1653 package->set_location(location);
1655 else
1657 // First time we have seen this package name.
1658 package = new Package(pkgpath, pkgpath_symbol, location);
1659 go_assert(ins.first->second == NULL);
1660 ins.first->second = package;
1663 return package;
1666 // Return the pkgpath symbol for a package, given the pkgpath.
1668 std::string
1669 Gogo::pkgpath_symbol_for_package(const std::string& pkgpath)
1671 Packages::iterator p = this->packages_.find(pkgpath);
1672 go_assert(p != this->packages_.end());
1673 return p->second->pkgpath_symbol();
1676 // Start compiling a function.
1678 Named_object*
1679 Gogo::start_function(const std::string& name, Function_type* type,
1680 bool add_method_to_type, Location location)
1682 bool at_top_level = this->functions_.empty();
1684 Block* block = new Block(NULL, location);
1686 Named_object* enclosing = (at_top_level
1687 ? NULL
1688 : this->functions_.back().function);
1690 Function* function = new Function(type, enclosing, block, location);
1692 if (type->is_method())
1694 const Typed_identifier* receiver = type->receiver();
1695 Variable* this_param = new Variable(receiver->type(), NULL, false,
1696 true, true, location);
1697 std::string rname = receiver->name();
1698 if (rname.empty() || Gogo::is_sink_name(rname))
1700 // We need to give receivers a name since they wind up in
1701 // DECL_ARGUMENTS. FIXME.
1702 static unsigned int count;
1703 char buf[50];
1704 snprintf(buf, sizeof buf, "r.%u", count);
1705 ++count;
1706 rname = buf;
1708 block->bindings()->add_variable(rname, NULL, this_param);
1711 const Typed_identifier_list* parameters = type->parameters();
1712 bool is_varargs = type->is_varargs();
1713 if (parameters != NULL)
1715 for (Typed_identifier_list::const_iterator p = parameters->begin();
1716 p != parameters->end();
1717 ++p)
1719 Variable* param = new Variable(p->type(), NULL, false, true, false,
1720 p->location());
1721 if (is_varargs && p + 1 == parameters->end())
1722 param->set_is_varargs_parameter();
1724 std::string pname = p->name();
1725 if (pname.empty() || Gogo::is_sink_name(pname))
1727 // We need to give parameters a name since they wind up
1728 // in DECL_ARGUMENTS. FIXME.
1729 static unsigned int count;
1730 char buf[50];
1731 snprintf(buf, sizeof buf, "p.%u", count);
1732 ++count;
1733 pname = buf;
1735 block->bindings()->add_variable(pname, NULL, param);
1739 function->create_result_variables(this);
1741 const std::string* pname;
1742 std::string nested_name;
1743 bool is_init = false;
1744 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1746 if ((type->parameters() != NULL && !type->parameters()->empty())
1747 || (type->results() != NULL && !type->results()->empty()))
1748 go_error_at(location,
1749 "func init must have no arguments and no return values");
1750 // There can be multiple "init" functions, so give them each a
1751 // different name.
1752 nested_name = this->init_function_name();
1753 pname = &nested_name;
1754 is_init = true;
1756 else if (!name.empty())
1757 pname = &name;
1758 else
1760 // Invent a name for a nested function.
1761 nested_name = this->nested_function_name();
1762 pname = &nested_name;
1765 Named_object* ret;
1766 if (Gogo::is_sink_name(*pname))
1768 std::string sname(this->sink_function_name());
1769 ret = Named_object::make_function(sname, NULL, function);
1770 ret->func_value()->set_is_sink();
1772 if (!type->is_method())
1773 ret = this->package_->bindings()->add_named_object(ret);
1774 else if (add_method_to_type)
1776 // We should report errors even for sink methods.
1777 Type* rtype = type->receiver()->type();
1778 // Avoid points_to and deref to avoid getting an error if
1779 // the type is not yet defined.
1780 if (rtype->classification() == Type::TYPE_POINTER)
1781 rtype = rtype->points_to();
1782 while (rtype->named_type() != NULL
1783 && rtype->named_type()->is_alias())
1784 rtype = rtype->named_type()->real_type()->forwarded();
1785 if (rtype->is_error_type())
1787 else if (rtype->named_type() != NULL)
1789 if (rtype->named_type()->named_object()->package() != NULL)
1790 go_error_at(type->receiver()->location(),
1791 "may not define methods on non-local type");
1793 else if (rtype->forward_declaration_type() != NULL)
1795 // Go ahead and add the method in case we need to report
1796 // an error when we see the definition.
1797 rtype->forward_declaration_type()->add_existing_method(ret);
1799 else
1800 go_error_at(type->receiver()->location(),
1801 ("invalid receiver type "
1802 "(receiver must be a named type)"));
1805 else if (!type->is_method())
1807 ret = this->package_->bindings()->add_function(*pname, NULL, function);
1808 if (!ret->is_function() || ret->func_value() != function)
1810 // Redefinition error. Invent a name to avoid knockon
1811 // errors.
1812 std::string rname(this->redefined_function_name());
1813 ret = this->package_->bindings()->add_function(rname, NULL, function);
1816 else
1818 if (!add_method_to_type)
1819 ret = Named_object::make_function(name, NULL, function);
1820 else
1822 go_assert(at_top_level);
1823 Type* rtype = type->receiver()->type();
1825 // We want to look through the pointer created by the
1826 // parser, without getting an error if the type is not yet
1827 // defined.
1828 if (rtype->classification() == Type::TYPE_POINTER)
1829 rtype = rtype->points_to();
1831 while (rtype->named_type() != NULL
1832 && rtype->named_type()->is_alias())
1833 rtype = rtype->named_type()->real_type()->forwarded();
1835 if (rtype->is_error_type())
1836 ret = Named_object::make_function(name, NULL, function);
1837 else if (rtype->named_type() != NULL)
1839 if (rtype->named_type()->named_object()->package() != NULL)
1841 go_error_at(type->receiver()->location(),
1842 "may not define methods on non-local type");
1843 ret = Named_object::make_function(name, NULL, function);
1845 else
1847 ret = rtype->named_type()->add_method(name, function);
1848 if (!ret->is_function())
1850 // Redefinition error.
1851 ret = Named_object::make_function(name, NULL, function);
1855 else if (rtype->forward_declaration_type() != NULL)
1857 Named_object* type_no =
1858 rtype->forward_declaration_type()->named_object();
1859 if (type_no->is_unknown())
1861 // If we are seeing methods it really must be a
1862 // type. Declare it as such. An alternative would
1863 // be to support lists of methods for unknown
1864 // expressions. Either way the error messages if
1865 // this is not a type are going to get confusing.
1866 Named_object* declared =
1867 this->declare_package_type(type_no->name(),
1868 type_no->location());
1869 go_assert(declared
1870 == type_no->unknown_value()->real_named_object());
1872 ret = rtype->forward_declaration_type()->add_method(name,
1873 function);
1875 else
1877 go_error_at(type->receiver()->location(),
1878 ("invalid receiver type (receiver must "
1879 "be a named type)"));
1880 ret = Named_object::make_function(name, NULL, function);
1883 this->package_->bindings()->add_method(ret);
1886 this->functions_.resize(this->functions_.size() + 1);
1887 Open_function& of(this->functions_.back());
1888 of.function = ret;
1889 of.blocks.push_back(block);
1891 if (is_init)
1893 this->init_functions_.push_back(ret);
1894 this->need_init_fn_ = true;
1897 return ret;
1900 // Finish compiling a function.
1902 void
1903 Gogo::finish_function(Location location)
1905 this->finish_block(location);
1906 go_assert(this->functions_.back().blocks.empty());
1907 this->functions_.pop_back();
1910 // Return the current function.
1912 Named_object*
1913 Gogo::current_function() const
1915 go_assert(!this->functions_.empty());
1916 return this->functions_.back().function;
1919 // Start a new block.
1921 void
1922 Gogo::start_block(Location location)
1924 go_assert(!this->functions_.empty());
1925 Block* block = new Block(this->current_block(), location);
1926 this->functions_.back().blocks.push_back(block);
1929 // Finish a block.
1931 Block*
1932 Gogo::finish_block(Location location)
1934 go_assert(!this->functions_.empty());
1935 go_assert(!this->functions_.back().blocks.empty());
1936 Block* block = this->functions_.back().blocks.back();
1937 this->functions_.back().blocks.pop_back();
1938 block->set_end_location(location);
1939 return block;
1942 // Add an erroneous name.
1944 Named_object*
1945 Gogo::add_erroneous_name(const std::string& name)
1947 return this->package_->bindings()->add_erroneous_name(name);
1950 // Add an unknown name.
1952 Named_object*
1953 Gogo::add_unknown_name(const std::string& name, Location location)
1955 return this->package_->bindings()->add_unknown_name(name, location);
1958 // Declare a function.
1960 Named_object*
1961 Gogo::declare_function(const std::string& name, Function_type* type,
1962 Location location)
1964 if (!type->is_method())
1965 return this->current_bindings()->add_function_declaration(name, NULL, type,
1966 location);
1967 else
1969 // We don't bother to add this to the list of global
1970 // declarations.
1971 Type* rtype = type->receiver()->type();
1973 // We want to look through the pointer created by the
1974 // parser, without getting an error if the type is not yet
1975 // defined.
1976 if (rtype->classification() == Type::TYPE_POINTER)
1977 rtype = rtype->points_to();
1979 if (rtype->is_error_type())
1980 return NULL;
1981 else if (rtype->named_type() != NULL)
1982 return rtype->named_type()->add_method_declaration(name, NULL, type,
1983 location);
1984 else if (rtype->forward_declaration_type() != NULL)
1986 Forward_declaration_type* ftype = rtype->forward_declaration_type();
1987 return ftype->add_method_declaration(name, NULL, type, location);
1989 else
1991 go_error_at(type->receiver()->location(),
1992 "invalid receiver type (receiver must be a named type)");
1993 return Named_object::make_erroneous_name(name);
1998 // Add a label definition.
2000 Label*
2001 Gogo::add_label_definition(const std::string& label_name,
2002 Location location)
2004 go_assert(!this->functions_.empty());
2005 Function* func = this->functions_.back().function->func_value();
2006 Label* label = func->add_label_definition(this, label_name, location);
2007 this->add_statement(Statement::make_label_statement(label, location));
2008 return label;
2011 // Add a label reference.
2013 Label*
2014 Gogo::add_label_reference(const std::string& label_name,
2015 Location location, bool issue_goto_errors)
2017 go_assert(!this->functions_.empty());
2018 Function* func = this->functions_.back().function->func_value();
2019 return func->add_label_reference(this, label_name, location,
2020 issue_goto_errors);
2023 // Return the current binding state.
2025 Bindings_snapshot*
2026 Gogo::bindings_snapshot(Location location)
2028 return new Bindings_snapshot(this->current_block(), location);
2031 // Add a statement.
2033 void
2034 Gogo::add_statement(Statement* statement)
2036 go_assert(!this->functions_.empty()
2037 && !this->functions_.back().blocks.empty());
2038 this->functions_.back().blocks.back()->add_statement(statement);
2041 // Add a block.
2043 void
2044 Gogo::add_block(Block* block, Location location)
2046 go_assert(!this->functions_.empty()
2047 && !this->functions_.back().blocks.empty());
2048 Statement* statement = Statement::make_block_statement(block, location);
2049 this->functions_.back().blocks.back()->add_statement(statement);
2052 // Add a constant.
2054 Named_object*
2055 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
2056 int iota_value)
2058 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
2061 // Add a type.
2063 void
2064 Gogo::add_type(const std::string& name, Type* type, Location location)
2066 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
2067 location);
2068 if (!this->in_global_scope() && no->is_type())
2070 Named_object* f = this->functions_.back().function;
2071 unsigned int index;
2072 if (f->is_function())
2073 index = f->func_value()->new_local_type_index();
2074 else
2075 index = 0;
2076 no->type_value()->set_in_function(f, index);
2080 // Add a named type.
2082 void
2083 Gogo::add_named_type(Named_type* type)
2085 go_assert(this->in_global_scope());
2086 this->current_bindings()->add_named_type(type);
2089 // Declare a type.
2091 Named_object*
2092 Gogo::declare_type(const std::string& name, Location location)
2094 Bindings* bindings = this->current_bindings();
2095 Named_object* no = bindings->add_type_declaration(name, NULL, location);
2096 if (!this->in_global_scope() && no->is_type_declaration())
2098 Named_object* f = this->functions_.back().function;
2099 unsigned int index;
2100 if (f->is_function())
2101 index = f->func_value()->new_local_type_index();
2102 else
2103 index = 0;
2104 no->type_declaration_value()->set_in_function(f, index);
2106 return no;
2109 // Declare a type at the package level.
2111 Named_object*
2112 Gogo::declare_package_type(const std::string& name, Location location)
2114 return this->package_->bindings()->add_type_declaration(name, NULL, location);
2117 // Declare a function at the package level.
2119 Named_object*
2120 Gogo::declare_package_function(const std::string& name, Function_type* type,
2121 Location location)
2123 return this->package_->bindings()->add_function_declaration(name, NULL, type,
2124 location);
2127 // Define a type which was already declared.
2129 void
2130 Gogo::define_type(Named_object* no, Named_type* type)
2132 this->current_bindings()->define_type(no, type);
2135 // Add a variable.
2137 Named_object*
2138 Gogo::add_variable(const std::string& name, Variable* variable)
2140 Named_object* no = this->current_bindings()->add_variable(name, NULL,
2141 variable);
2143 // In a function the middle-end wants to see a DECL_EXPR node.
2144 if (no != NULL
2145 && no->is_variable()
2146 && !no->var_value()->is_parameter()
2147 && !this->functions_.empty())
2148 this->add_statement(Statement::make_variable_declaration(no));
2150 return no;
2153 // Add a sink--a reference to the blank identifier _.
2155 Named_object*
2156 Gogo::add_sink()
2158 return Named_object::make_sink();
2161 // Add a named object for a dot import.
2163 void
2164 Gogo::add_dot_import_object(Named_object* no)
2166 // If the name already exists, then it was defined in some file seen
2167 // earlier. If the earlier name is just a declaration, don't add
2168 // this name, because that will cause the previous declaration to
2169 // merge to this imported name, which should not happen. Just add
2170 // this name to the list of file block names to get appropriate
2171 // errors if we see a later definition.
2172 Named_object* e = this->package_->bindings()->lookup(no->name());
2173 if (e != NULL && e->package() == NULL)
2175 if (e->is_unknown())
2176 e = e->resolve();
2177 if (e->package() == NULL
2178 && (e->is_type_declaration()
2179 || e->is_function_declaration()
2180 || e->is_unknown()))
2182 this->add_file_block_name(no->name(), no->location());
2183 return;
2187 this->current_bindings()->add_named_object(no);
2190 // Add a linkname. This implements the go:linkname compiler directive.
2191 // We only support this for functions and function declarations.
2193 void
2194 Gogo::add_linkname(const std::string& go_name, bool is_exported,
2195 const std::string& ext_name, Location loc)
2197 Named_object* no =
2198 this->package_->bindings()->lookup(this->pack_hidden_name(go_name,
2199 is_exported));
2200 if (no == NULL)
2201 go_error_at(loc, "%s is not defined", go_name.c_str());
2202 else if (no->is_function())
2203 no->func_value()->set_asm_name(ext_name);
2204 else if (no->is_function_declaration())
2205 no->func_declaration_value()->set_asm_name(ext_name);
2206 else
2207 go_error_at(loc,
2208 ("%s is not a function; "
2209 "//go:linkname is only supported for functions"),
2210 go_name.c_str());
2213 // Mark all local variables used. This is used when some types of
2214 // parse error occur.
2216 void
2217 Gogo::mark_locals_used()
2219 for (Open_functions::iterator pf = this->functions_.begin();
2220 pf != this->functions_.end();
2221 ++pf)
2223 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2224 pb != pf->blocks.end();
2225 ++pb)
2226 (*pb)->bindings()->mark_locals_used();
2230 // Record that we've seen an interface type.
2232 void
2233 Gogo::record_interface_type(Interface_type* itype)
2235 this->interface_types_.push_back(itype);
2238 // Define the global names. We do this only after parsing all the
2239 // input files, because the program might define the global names
2240 // itself.
2242 void
2243 Gogo::define_global_names()
2245 if (this->is_main_package())
2247 // Every Go program has to import the runtime package, so that
2248 // it is properly initialized.
2249 this->import_package("runtime", "_", false, false,
2250 Linemap::predeclared_location());
2253 for (Bindings::const_declarations_iterator p =
2254 this->globals_->begin_declarations();
2255 p != this->globals_->end_declarations();
2256 ++p)
2258 Named_object* global_no = p->second;
2259 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2260 Named_object* no = this->package_->bindings()->lookup(name);
2261 if (no == NULL)
2262 continue;
2263 no = no->resolve();
2264 if (no->is_type_declaration())
2266 if (global_no->is_type())
2268 if (no->type_declaration_value()->has_methods())
2270 for (std::vector<Named_object*>::const_iterator p =
2271 no->type_declaration_value()->methods()->begin();
2272 p != no->type_declaration_value()->methods()->end();
2273 p++)
2274 go_error_at((*p)->location(),
2275 "may not define methods on non-local type");
2277 no->set_type_value(global_no->type_value());
2279 else
2281 go_error_at(no->location(), "expected type");
2282 Type* errtype = Type::make_error_type();
2283 Named_object* err =
2284 Named_object::make_type("erroneous_type", NULL, errtype,
2285 Linemap::predeclared_location());
2286 no->set_type_value(err->type_value());
2289 else if (no->is_unknown())
2290 no->unknown_value()->set_real_named_object(global_no);
2293 // Give an error if any name is defined in both the package block
2294 // and the file block. For example, this can happen if one file
2295 // imports "fmt" and another file defines a global variable fmt.
2296 for (Bindings::const_declarations_iterator p =
2297 this->package_->bindings()->begin_declarations();
2298 p != this->package_->bindings()->end_declarations();
2299 ++p)
2301 if (p->second->is_unknown()
2302 && p->second->unknown_value()->real_named_object() == NULL)
2304 // No point in warning about an undefined name, as we will
2305 // get other errors later anyhow.
2306 continue;
2308 File_block_names::const_iterator pf =
2309 this->file_block_names_.find(p->second->name());
2310 if (pf != this->file_block_names_.end())
2312 std::string n = p->second->message_name();
2313 go_error_at(p->second->location(),
2314 "%qs defined as both imported name and global name",
2315 n.c_str());
2316 go_inform(pf->second, "%qs imported here", n.c_str());
2319 // No package scope identifier may be named "init".
2320 if (!p->second->is_function()
2321 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2323 go_error_at(p->second->location(),
2324 "cannot declare init - must be func");
2329 // Clear out names in file scope.
2331 void
2332 Gogo::clear_file_scope()
2334 this->package_->bindings()->clear_file_scope(this);
2336 // Warn about packages which were imported but not used.
2337 bool quiet = saw_errors();
2338 for (Packages::iterator p = this->packages_.begin();
2339 p != this->packages_.end();
2340 ++p)
2342 Package* package = p->second;
2343 if (package != this->package_ && !quiet)
2345 for (Package::Aliases::const_iterator p1 = package->aliases().begin();
2346 p1 != package->aliases().end();
2347 ++p1)
2349 if (!p1->second->used())
2351 // Give a more refined error message if the alias name is known.
2352 std::string pkg_name = package->package_name();
2353 if (p1->first != pkg_name && p1->first[0] != '.')
2355 go_error_at(p1->second->location(),
2356 "imported and not used: %s as %s",
2357 Gogo::message_name(pkg_name).c_str(),
2358 Gogo::message_name(p1->first).c_str());
2360 else
2361 go_error_at(p1->second->location(),
2362 "imported and not used: %s",
2363 Gogo::message_name(pkg_name).c_str());
2367 package->clear_used();
2370 this->current_file_imported_unsafe_ = false;
2373 // Queue up a type specific function for later writing. These are
2374 // written out in write_specific_type_functions, called after the
2375 // parse tree is lowered.
2377 void
2378 Gogo::queue_specific_type_function(Type* type, Named_type* name, int64_t size,
2379 const std::string& hash_name,
2380 Function_type* hash_fntype,
2381 const std::string& equal_name,
2382 Function_type* equal_fntype)
2384 go_assert(!this->specific_type_functions_are_written_);
2385 go_assert(!this->in_global_scope());
2386 Specific_type_function* tsf = new Specific_type_function(type, name, size,
2387 hash_name,
2388 hash_fntype,
2389 equal_name,
2390 equal_fntype);
2391 this->specific_type_functions_.push_back(tsf);
2394 // Look for types which need specific hash or equality functions.
2396 class Specific_type_functions : public Traverse
2398 public:
2399 Specific_type_functions(Gogo* gogo)
2400 : Traverse(traverse_types),
2401 gogo_(gogo)
2405 type(Type*);
2407 private:
2408 Gogo* gogo_;
2412 Specific_type_functions::type(Type* t)
2414 Named_object* hash_fn;
2415 Named_object* equal_fn;
2416 switch (t->classification())
2418 case Type::TYPE_NAMED:
2420 Named_type* nt = t->named_type();
2421 if (nt->is_alias())
2422 return TRAVERSE_CONTINUE;
2423 if (t->needs_specific_type_functions(this->gogo_))
2424 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2426 // If this is a struct type, we don't want to make functions
2427 // for the unnamed struct.
2428 Type* rt = nt->real_type();
2429 if (rt->struct_type() == NULL)
2431 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2432 return TRAVERSE_EXIT;
2434 else
2436 // If this type is defined in another package, then we don't
2437 // need to worry about the unexported fields.
2438 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2439 const Struct_field_list* fields = rt->struct_type()->fields();
2440 for (Struct_field_list::const_iterator p = fields->begin();
2441 p != fields->end();
2442 ++p)
2444 if (is_defined_elsewhere
2445 && Gogo::is_hidden_name(p->field_name()))
2446 continue;
2447 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2448 return TRAVERSE_EXIT;
2452 return TRAVERSE_SKIP_COMPONENTS;
2455 case Type::TYPE_STRUCT:
2456 case Type::TYPE_ARRAY:
2457 if (t->needs_specific_type_functions(this->gogo_))
2458 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2459 break;
2461 default:
2462 break;
2465 return TRAVERSE_CONTINUE;
2468 // Write out type specific functions.
2470 void
2471 Gogo::write_specific_type_functions()
2473 Specific_type_functions stf(this);
2474 this->traverse(&stf);
2476 while (!this->specific_type_functions_.empty())
2478 Specific_type_function* tsf = this->specific_type_functions_.back();
2479 this->specific_type_functions_.pop_back();
2480 tsf->type->write_specific_type_functions(this, tsf->name, tsf->size,
2481 tsf->hash_name,
2482 tsf->hash_fntype,
2483 tsf->equal_name,
2484 tsf->equal_fntype);
2485 delete tsf;
2487 this->specific_type_functions_are_written_ = true;
2490 // Traverse the tree.
2492 void
2493 Gogo::traverse(Traverse* traverse)
2495 // Traverse the current package first for consistency. The other
2496 // packages will only contain imported types, constants, and
2497 // declarations.
2498 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2499 return;
2500 for (Packages::const_iterator p = this->packages_.begin();
2501 p != this->packages_.end();
2502 ++p)
2504 if (p->second != this->package_)
2506 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2507 break;
2512 // Add a type to verify. This is used for types of sink variables, in
2513 // order to give appropriate error messages.
2515 void
2516 Gogo::add_type_to_verify(Type* type)
2518 this->verify_types_.push_back(type);
2521 // Traversal class used to verify types.
2523 class Verify_types : public Traverse
2525 public:
2526 Verify_types()
2527 : Traverse(traverse_types)
2531 type(Type*);
2534 // Verify that a type is correct.
2537 Verify_types::type(Type* t)
2539 if (!t->verify())
2540 return TRAVERSE_SKIP_COMPONENTS;
2541 return TRAVERSE_CONTINUE;
2544 // Verify that all types are correct.
2546 void
2547 Gogo::verify_types()
2549 Verify_types traverse;
2550 this->traverse(&traverse);
2552 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2553 p != this->verify_types_.end();
2554 ++p)
2555 (*p)->verify();
2556 this->verify_types_.clear();
2559 // Traversal class used to lower parse tree.
2561 class Lower_parse_tree : public Traverse
2563 public:
2564 Lower_parse_tree(Gogo* gogo, Named_object* function)
2565 : Traverse(traverse_variables
2566 | traverse_constants
2567 | traverse_functions
2568 | traverse_statements
2569 | traverse_expressions),
2570 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2573 void
2574 set_inserter(const Statement_inserter* inserter)
2575 { this->inserter_ = *inserter; }
2578 variable(Named_object*);
2581 constant(Named_object*, bool);
2584 function(Named_object*);
2587 statement(Block*, size_t* pindex, Statement*);
2590 expression(Expression**);
2592 private:
2593 // General IR.
2594 Gogo* gogo_;
2595 // The function we are traversing.
2596 Named_object* function_;
2597 // Value to use for the predeclared constant iota.
2598 int iota_value_;
2599 // Current statement inserter for use by expressions.
2600 Statement_inserter inserter_;
2603 // Lower variables.
2606 Lower_parse_tree::variable(Named_object* no)
2608 if (!no->is_variable())
2609 return TRAVERSE_CONTINUE;
2611 if (no->is_variable() && no->var_value()->is_global())
2613 // Global variables can have loops in their initialization
2614 // expressions. This is handled in lower_init_expression.
2615 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2616 &this->inserter_);
2617 return TRAVERSE_CONTINUE;
2620 // This is a local variable. We are going to return
2621 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2622 // initialization expression when we reach the variable declaration
2623 // statement. However, that means that we need to traverse the type
2624 // ourselves.
2625 if (no->var_value()->has_type())
2627 Type* type = no->var_value()->type();
2628 if (type != NULL)
2630 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2631 return TRAVERSE_EXIT;
2634 go_assert(!no->var_value()->has_pre_init());
2636 return TRAVERSE_SKIP_COMPONENTS;
2639 // Lower constants. We handle constants specially so that we can set
2640 // the right value for the predeclared constant iota. This works in
2641 // conjunction with the way we lower Const_expression objects.
2644 Lower_parse_tree::constant(Named_object* no, bool)
2646 Named_constant* nc = no->const_value();
2648 // Don't get into trouble if the constant's initializer expression
2649 // refers to the constant itself.
2650 if (nc->lowering())
2651 return TRAVERSE_CONTINUE;
2652 nc->set_lowering();
2654 go_assert(this->iota_value_ == -1);
2655 this->iota_value_ = nc->iota_value();
2656 nc->traverse_expression(this);
2657 this->iota_value_ = -1;
2659 nc->clear_lowering();
2661 // We will traverse the expression a second time, but that will be
2662 // fast.
2664 return TRAVERSE_CONTINUE;
2667 // Lower the body of a function, and set the closure type. Record the
2668 // function while lowering it, so that we can pass it down when
2669 // lowering an expression.
2672 Lower_parse_tree::function(Named_object* no)
2674 no->func_value()->set_closure_type();
2676 go_assert(this->function_ == NULL);
2677 this->function_ = no;
2678 int t = no->func_value()->traverse(this);
2679 this->function_ = NULL;
2681 if (t == TRAVERSE_EXIT)
2682 return t;
2683 return TRAVERSE_SKIP_COMPONENTS;
2686 // Lower statement parse trees.
2689 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2691 // Because we explicitly traverse the statement's contents
2692 // ourselves, we want to skip block statements here. There is
2693 // nothing to lower in a block statement.
2694 if (sorig->is_block_statement())
2695 return TRAVERSE_CONTINUE;
2697 Statement_inserter hold_inserter(this->inserter_);
2698 this->inserter_ = Statement_inserter(block, pindex);
2700 // Lower the expressions first.
2701 int t = sorig->traverse_contents(this);
2702 if (t == TRAVERSE_EXIT)
2704 this->inserter_ = hold_inserter;
2705 return t;
2708 // Keep lowering until nothing changes.
2709 Statement* s = sorig;
2710 while (true)
2712 Statement* snew = s->lower(this->gogo_, this->function_, block,
2713 &this->inserter_);
2714 if (snew == s)
2715 break;
2716 s = snew;
2717 t = s->traverse_contents(this);
2718 if (t == TRAVERSE_EXIT)
2720 this->inserter_ = hold_inserter;
2721 return t;
2725 if (s != sorig)
2726 block->replace_statement(*pindex, s);
2728 this->inserter_ = hold_inserter;
2729 return TRAVERSE_SKIP_COMPONENTS;
2732 // Lower expression parse trees.
2735 Lower_parse_tree::expression(Expression** pexpr)
2737 // We have to lower all subexpressions first, so that we can get
2738 // their type if necessary. This is awkward, because we don't have
2739 // a postorder traversal pass.
2740 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2741 return TRAVERSE_EXIT;
2742 // Keep lowering until nothing changes.
2743 while (true)
2745 Expression* e = *pexpr;
2746 Expression* enew = e->lower(this->gogo_, this->function_,
2747 &this->inserter_, this->iota_value_);
2748 if (enew == e)
2749 break;
2750 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2751 return TRAVERSE_EXIT;
2752 *pexpr = enew;
2754 return TRAVERSE_SKIP_COMPONENTS;
2757 // Lower the parse tree. This is called after the parse is complete,
2758 // when all names should be resolved.
2760 void
2761 Gogo::lower_parse_tree()
2763 Lower_parse_tree lower_parse_tree(this, NULL);
2764 this->traverse(&lower_parse_tree);
2766 // There might be type definitions that involve expressions such as the
2767 // array length. Make sure to lower these expressions as well. Otherwise,
2768 // errors hidden within a type can introduce unexpected errors into later
2769 // passes.
2770 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2771 p != this->verify_types_.end();
2772 ++p)
2773 Type::traverse(*p, &lower_parse_tree);
2776 // Lower a block.
2778 void
2779 Gogo::lower_block(Named_object* function, Block* block)
2781 Lower_parse_tree lower_parse_tree(this, function);
2782 block->traverse(&lower_parse_tree);
2785 // Lower an expression. INSERTER may be NULL, in which case the
2786 // expression had better not need to create any temporaries.
2788 void
2789 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2790 Expression** pexpr)
2792 Lower_parse_tree lower_parse_tree(this, function);
2793 if (inserter != NULL)
2794 lower_parse_tree.set_inserter(inserter);
2795 lower_parse_tree.expression(pexpr);
2798 // Lower a constant. This is called when lowering a reference to a
2799 // constant. We have to make sure that the constant has already been
2800 // lowered.
2802 void
2803 Gogo::lower_constant(Named_object* no)
2805 go_assert(no->is_const());
2806 Lower_parse_tree lower(this, NULL);
2807 lower.constant(no, false);
2810 // Traverse the tree to create function descriptors as needed.
2812 class Create_function_descriptors : public Traverse
2814 public:
2815 Create_function_descriptors(Gogo* gogo)
2816 : Traverse(traverse_functions | traverse_expressions),
2817 gogo_(gogo)
2821 function(Named_object*);
2824 expression(Expression**);
2826 private:
2827 Gogo* gogo_;
2830 // Create a descriptor for every top-level exported function.
2833 Create_function_descriptors::function(Named_object* no)
2835 if (no->is_function()
2836 && no->func_value()->enclosing() == NULL
2837 && !no->func_value()->is_method()
2838 && !Gogo::is_hidden_name(no->name())
2839 && !Gogo::is_thunk(no))
2840 no->func_value()->descriptor(this->gogo_, no);
2842 return TRAVERSE_CONTINUE;
2845 // If we see a function referenced in any way other than calling it,
2846 // create a descriptor for it.
2849 Create_function_descriptors::expression(Expression** pexpr)
2851 Expression* expr = *pexpr;
2853 Func_expression* fe = expr->func_expression();
2854 if (fe != NULL)
2856 // We would not get here for a call to this function, so this is
2857 // a reference to a function other than calling it. We need a
2858 // descriptor.
2859 if (fe->closure() != NULL)
2860 return TRAVERSE_CONTINUE;
2861 Named_object* no = fe->named_object();
2862 if (no->is_function() && !no->func_value()->is_method())
2863 no->func_value()->descriptor(this->gogo_, no);
2864 else if (no->is_function_declaration()
2865 && !no->func_declaration_value()->type()->is_method()
2866 && !Linemap::is_predeclared_location(no->location()))
2867 no->func_declaration_value()->descriptor(this->gogo_, no);
2868 return TRAVERSE_CONTINUE;
2871 Bound_method_expression* bme = expr->bound_method_expression();
2872 if (bme != NULL)
2874 // We would not get here for a call to this method, so this is a
2875 // method value. We need to create a thunk.
2876 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
2877 bme->function());
2878 return TRAVERSE_CONTINUE;
2881 Interface_field_reference_expression* ifre =
2882 expr->interface_field_reference_expression();
2883 if (ifre != NULL)
2885 // We would not get here for a call to this interface method, so
2886 // this is a method value. We need to create a thunk.
2887 Interface_type* type = ifre->expr()->type()->interface_type();
2888 if (type != NULL)
2889 Interface_field_reference_expression::create_thunk(this->gogo_, type,
2890 ifre->name());
2891 return TRAVERSE_CONTINUE;
2894 Call_expression* ce = expr->call_expression();
2895 if (ce != NULL)
2897 Expression* fn = ce->fn();
2898 if (fn->func_expression() != NULL
2899 || fn->bound_method_expression() != NULL
2900 || fn->interface_field_reference_expression() != NULL)
2902 // Traverse the arguments but not the function.
2903 Expression_list* args = ce->args();
2904 if (args != NULL)
2906 if (args->traverse(this) == TRAVERSE_EXIT)
2907 return TRAVERSE_EXIT;
2909 return TRAVERSE_SKIP_COMPONENTS;
2913 return TRAVERSE_CONTINUE;
2916 // Create function descriptors as needed. We need a function
2917 // descriptor for all exported functions and for all functions that
2918 // are referenced without being called.
2920 void
2921 Gogo::create_function_descriptors()
2923 // Create a function descriptor for any exported function that is
2924 // declared in this package. This is so that we have a descriptor
2925 // for functions written in assembly. Gather the descriptors first
2926 // so that we don't add declarations while looping over them.
2927 std::vector<Named_object*> fndecls;
2928 Bindings* b = this->package_->bindings();
2929 for (Bindings::const_declarations_iterator p = b->begin_declarations();
2930 p != b->end_declarations();
2931 ++p)
2933 Named_object* no = p->second;
2934 if (no->is_function_declaration()
2935 && !no->func_declaration_value()->type()->is_method()
2936 && !Linemap::is_predeclared_location(no->location())
2937 && !Gogo::is_hidden_name(no->name()))
2938 fndecls.push_back(no);
2940 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
2941 p != fndecls.end();
2942 ++p)
2943 (*p)->func_declaration_value()->descriptor(this, *p);
2944 fndecls.clear();
2946 Create_function_descriptors cfd(this);
2947 this->traverse(&cfd);
2950 // Look for interface types to finalize methods of inherited
2951 // interfaces.
2953 class Finalize_methods : public Traverse
2955 public:
2956 Finalize_methods(Gogo* gogo)
2957 : Traverse(traverse_types),
2958 gogo_(gogo)
2962 type(Type*);
2964 private:
2965 Gogo* gogo_;
2968 // Finalize the methods of an interface type.
2971 Finalize_methods::type(Type* t)
2973 // Check the classification so that we don't finalize the methods
2974 // twice for a named interface type.
2975 switch (t->classification())
2977 case Type::TYPE_INTERFACE:
2978 t->interface_type()->finalize_methods();
2979 break;
2981 case Type::TYPE_NAMED:
2983 Named_type* nt = t->named_type();
2984 Type* rt = nt->real_type();
2985 if (rt->classification() != Type::TYPE_STRUCT)
2987 // Finalize the methods of the real type first.
2988 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2989 return TRAVERSE_EXIT;
2991 // Finalize the methods of this type.
2992 nt->finalize_methods(this->gogo_);
2994 else
2996 // We don't want to finalize the methods of a named struct
2997 // type, as the methods should be attached to the named
2998 // type, not the struct type. We just want to finalize
2999 // the field types.
3001 // It is possible that a field type refers indirectly to
3002 // this type, such as via a field with function type with
3003 // an argument or result whose type is this type. To
3004 // avoid the cycle, first finalize the methods of any
3005 // embedded types, which are the only types we need to
3006 // know to finalize the methods of this type.
3007 const Struct_field_list* fields = rt->struct_type()->fields();
3008 if (fields != NULL)
3010 for (Struct_field_list::const_iterator pf = fields->begin();
3011 pf != fields->end();
3012 ++pf)
3014 if (pf->is_anonymous())
3016 if (Type::traverse(pf->type(), this) == TRAVERSE_EXIT)
3017 return TRAVERSE_EXIT;
3022 // Finalize the methods of this type.
3023 nt->finalize_methods(this->gogo_);
3025 // Finalize all the struct fields.
3026 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3027 return TRAVERSE_EXIT;
3030 // If this type is defined in a different package, then finalize the
3031 // types of all the methods, since we won't see them otherwise.
3032 if (nt->named_object()->package() != NULL && nt->has_any_methods())
3034 const Methods* methods = nt->methods();
3035 for (Methods::const_iterator p = methods->begin();
3036 p != methods->end();
3037 ++p)
3039 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
3040 return TRAVERSE_EXIT;
3044 // Finalize the types of all methods that are declared but not
3045 // defined, since we won't see the declarations otherwise.
3046 if (nt->named_object()->package() == NULL
3047 && nt->local_methods() != NULL)
3049 const Bindings* methods = nt->local_methods();
3050 for (Bindings::const_declarations_iterator p =
3051 methods->begin_declarations();
3052 p != methods->end_declarations();
3053 p++)
3055 if (p->second->is_function_declaration())
3057 Type* mt = p->second->func_declaration_value()->type();
3058 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
3059 return TRAVERSE_EXIT;
3064 return TRAVERSE_SKIP_COMPONENTS;
3067 case Type::TYPE_STRUCT:
3068 // Traverse the field types first in case there is an embedded
3069 // field with methods that the struct should inherit.
3070 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
3071 return TRAVERSE_EXIT;
3072 t->struct_type()->finalize_methods(this->gogo_);
3073 return TRAVERSE_SKIP_COMPONENTS;
3075 default:
3076 break;
3079 return TRAVERSE_CONTINUE;
3082 // Finalize method lists and build stub methods for types.
3084 void
3085 Gogo::finalize_methods()
3087 Finalize_methods finalize(this);
3088 this->traverse(&finalize);
3091 // Set types for unspecified variables and constants.
3093 void
3094 Gogo::determine_types()
3096 Bindings* bindings = this->current_bindings();
3097 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
3098 p != bindings->end_definitions();
3099 ++p)
3101 if ((*p)->is_function())
3102 (*p)->func_value()->determine_types();
3103 else if ((*p)->is_variable())
3104 (*p)->var_value()->determine_type();
3105 else if ((*p)->is_const())
3106 (*p)->const_value()->determine_type();
3108 // See if a variable requires us to build an initialization
3109 // function. We know that we will see all global variables
3110 // here.
3111 if (!this->need_init_fn_ && (*p)->is_variable())
3113 Variable* variable = (*p)->var_value();
3115 // If this is a global variable which requires runtime
3116 // initialization, we need an initialization function.
3117 if (!variable->is_global())
3119 else if (variable->init() == NULL)
3121 else if (variable->type()->interface_type() != NULL)
3122 this->need_init_fn_ = true;
3123 else if (variable->init()->is_constant())
3125 else if (!variable->init()->is_composite_literal())
3126 this->need_init_fn_ = true;
3127 else if (variable->init()->is_nonconstant_composite_literal())
3128 this->need_init_fn_ = true;
3130 // If this is a global variable which holds a pointer value,
3131 // then we need an initialization function to register it as a
3132 // GC root.
3133 if (variable->is_global() && variable->type()->has_pointer())
3134 this->need_init_fn_ = true;
3138 // Determine the types of constants in packages.
3139 for (Packages::const_iterator p = this->packages_.begin();
3140 p != this->packages_.end();
3141 ++p)
3142 p->second->determine_types();
3145 // Traversal class used for type checking.
3147 class Check_types_traverse : public Traverse
3149 public:
3150 Check_types_traverse(Gogo* gogo)
3151 : Traverse(traverse_variables
3152 | traverse_constants
3153 | traverse_functions
3154 | traverse_statements
3155 | traverse_expressions),
3156 gogo_(gogo)
3160 variable(Named_object*);
3163 constant(Named_object*, bool);
3166 function(Named_object*);
3169 statement(Block*, size_t* pindex, Statement*);
3172 expression(Expression**);
3174 private:
3175 // General IR.
3176 Gogo* gogo_;
3179 // Check that a variable initializer has the right type.
3182 Check_types_traverse::variable(Named_object* named_object)
3184 if (named_object->is_variable())
3186 Variable* var = named_object->var_value();
3188 // Give error if variable type is not defined.
3189 var->type()->base();
3191 Expression* init = var->init();
3192 std::string reason;
3193 if (init != NULL
3194 && !Type::are_assignable(var->type(), init->type(), &reason))
3196 if (reason.empty())
3197 go_error_at(var->location(), "incompatible type in initialization");
3198 else
3199 go_error_at(var->location(),
3200 "incompatible type in initialization (%s)",
3201 reason.c_str());
3202 init = Expression::make_error(named_object->location());
3203 var->clear_init();
3205 else if (init != NULL
3206 && init->func_expression() != NULL)
3208 Named_object* no = init->func_expression()->named_object();
3209 Function_type* fntype;
3210 if (no->is_function())
3211 fntype = no->func_value()->type();
3212 else if (no->is_function_declaration())
3213 fntype = no->func_declaration_value()->type();
3214 else
3215 go_unreachable();
3217 // Builtin functions cannot be used as function values for variable
3218 // initialization.
3219 if (fntype->is_builtin())
3221 go_error_at(init->location(),
3222 "invalid use of special builtin function %qs; "
3223 "must be called",
3224 no->message_name().c_str());
3227 if (!var->is_used()
3228 && !var->is_global()
3229 && !var->is_parameter()
3230 && !var->is_receiver()
3231 && !var->type()->is_error()
3232 && (init == NULL || !init->is_error_expression())
3233 && !Lex::is_invalid_identifier(named_object->name()))
3234 go_error_at(var->location(), "%qs declared and not used",
3235 named_object->message_name().c_str());
3237 return TRAVERSE_CONTINUE;
3240 // Check that a constant initializer has the right type.
3243 Check_types_traverse::constant(Named_object* named_object, bool)
3245 Named_constant* constant = named_object->const_value();
3246 Type* ctype = constant->type();
3247 if (ctype->integer_type() == NULL
3248 && ctype->float_type() == NULL
3249 && ctype->complex_type() == NULL
3250 && !ctype->is_boolean_type()
3251 && !ctype->is_string_type())
3253 if (ctype->is_nil_type())
3254 go_error_at(constant->location(), "const initializer cannot be nil");
3255 else if (!ctype->is_error())
3256 go_error_at(constant->location(), "invalid constant type");
3257 constant->set_error();
3259 else if (!constant->expr()->is_constant())
3261 go_error_at(constant->expr()->location(), "expression is not constant");
3262 constant->set_error();
3264 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3265 NULL))
3267 go_error_at(constant->location(),
3268 "initialization expression has wrong type");
3269 constant->set_error();
3271 return TRAVERSE_CONTINUE;
3274 // There are no types to check in a function, but this is where we
3275 // issue warnings about labels which are defined but not referenced.
3278 Check_types_traverse::function(Named_object* no)
3280 no->func_value()->check_labels();
3281 return TRAVERSE_CONTINUE;
3284 // Check that types are valid in a statement.
3287 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3289 s->check_types(this->gogo_);
3290 return TRAVERSE_CONTINUE;
3293 // Check that types are valid in an expression.
3296 Check_types_traverse::expression(Expression** expr)
3298 (*expr)->check_types(this->gogo_);
3299 return TRAVERSE_CONTINUE;
3302 // Check that types are valid.
3304 void
3305 Gogo::check_types()
3307 Check_types_traverse traverse(this);
3308 this->traverse(&traverse);
3310 Bindings* bindings = this->current_bindings();
3311 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
3312 p != bindings->end_declarations();
3313 ++p)
3315 // Also check the types in a function declaration's signature.
3316 Named_object* no = p->second;
3317 if (no->is_function_declaration())
3318 no->func_declaration_value()->check_types();
3322 // Check the types in a single block.
3324 void
3325 Gogo::check_types_in_block(Block* block)
3327 Check_types_traverse traverse(this);
3328 block->traverse(&traverse);
3331 // A traversal class used to find a single shortcut operator within an
3332 // expression.
3334 class Find_shortcut : public Traverse
3336 public:
3337 Find_shortcut()
3338 : Traverse(traverse_blocks
3339 | traverse_statements
3340 | traverse_expressions),
3341 found_(NULL)
3344 // A pointer to the expression which was found, or NULL if none was
3345 // found.
3346 Expression**
3347 found() const
3348 { return this->found_; }
3350 protected:
3352 block(Block*)
3353 { return TRAVERSE_SKIP_COMPONENTS; }
3356 statement(Block*, size_t*, Statement*)
3357 { return TRAVERSE_SKIP_COMPONENTS; }
3360 expression(Expression**);
3362 private:
3363 Expression** found_;
3366 // Find a shortcut expression.
3369 Find_shortcut::expression(Expression** pexpr)
3371 Expression* expr = *pexpr;
3372 Binary_expression* be = expr->binary_expression();
3373 if (be == NULL)
3374 return TRAVERSE_CONTINUE;
3375 Operator op = be->op();
3376 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3377 return TRAVERSE_CONTINUE;
3378 go_assert(this->found_ == NULL);
3379 this->found_ = pexpr;
3380 return TRAVERSE_EXIT;
3383 // A traversal class used to turn shortcut operators into explicit if
3384 // statements.
3386 class Shortcuts : public Traverse
3388 public:
3389 Shortcuts(Gogo* gogo)
3390 : Traverse(traverse_variables
3391 | traverse_statements),
3392 gogo_(gogo)
3395 protected:
3397 variable(Named_object*);
3400 statement(Block*, size_t*, Statement*);
3402 private:
3403 // Convert a shortcut operator.
3404 Statement*
3405 convert_shortcut(Block* enclosing, Expression** pshortcut);
3407 // The IR.
3408 Gogo* gogo_;
3411 // Remove shortcut operators in a single statement.
3414 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3416 // FIXME: This approach doesn't work for switch statements, because
3417 // we add the new statements before the whole switch when we need to
3418 // instead add them just before the switch expression. The right
3419 // fix is probably to lower switch statements with nonconstant cases
3420 // to a series of conditionals.
3421 if (s->switch_statement() != NULL)
3422 return TRAVERSE_CONTINUE;
3424 while (true)
3426 Find_shortcut find_shortcut;
3428 // If S is a variable declaration, then ordinary traversal won't
3429 // do anything. We want to explicitly traverse the
3430 // initialization expression if there is one.
3431 Variable_declaration_statement* vds = s->variable_declaration_statement();
3432 Expression* init = NULL;
3433 if (vds == NULL)
3434 s->traverse_contents(&find_shortcut);
3435 else
3437 init = vds->var()->var_value()->init();
3438 if (init == NULL)
3439 return TRAVERSE_CONTINUE;
3440 init->traverse(&init, &find_shortcut);
3442 Expression** pshortcut = find_shortcut.found();
3443 if (pshortcut == NULL)
3444 return TRAVERSE_CONTINUE;
3446 Statement* snew = this->convert_shortcut(block, pshortcut);
3447 block->insert_statement_before(*pindex, snew);
3448 ++*pindex;
3450 if (pshortcut == &init)
3451 vds->var()->var_value()->set_init(init);
3455 // Remove shortcut operators in the initializer of a global variable.
3458 Shortcuts::variable(Named_object* no)
3460 if (no->is_result_variable())
3461 return TRAVERSE_CONTINUE;
3462 Variable* var = no->var_value();
3463 Expression* init = var->init();
3464 if (!var->is_global() || init == NULL)
3465 return TRAVERSE_CONTINUE;
3467 while (true)
3469 Find_shortcut find_shortcut;
3470 init->traverse(&init, &find_shortcut);
3471 Expression** pshortcut = find_shortcut.found();
3472 if (pshortcut == NULL)
3473 return TRAVERSE_CONTINUE;
3475 Statement* snew = this->convert_shortcut(NULL, pshortcut);
3476 var->add_preinit_statement(this->gogo_, snew);
3477 if (pshortcut == &init)
3478 var->set_init(init);
3482 // Given an expression which uses a shortcut operator, return a
3483 // statement which implements it, and update *PSHORTCUT accordingly.
3485 Statement*
3486 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3488 Binary_expression* shortcut = (*pshortcut)->binary_expression();
3489 Expression* left = shortcut->left();
3490 Expression* right = shortcut->right();
3491 Location loc = shortcut->location();
3493 Block* retblock = new Block(enclosing, loc);
3494 retblock->set_end_location(loc);
3496 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3497 left, loc);
3498 retblock->add_statement(ts);
3500 Block* block = new Block(retblock, loc);
3501 block->set_end_location(loc);
3502 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
3503 Statement* assign = Statement::make_assignment(tmpref, right, loc);
3504 block->add_statement(assign);
3506 Expression* cond = Expression::make_temporary_reference(ts, loc);
3507 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
3508 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3510 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
3511 loc);
3512 retblock->add_statement(if_statement);
3514 *pshortcut = Expression::make_temporary_reference(ts, loc);
3516 delete shortcut;
3518 // Now convert any shortcut operators in LEFT and RIGHT.
3519 Shortcuts shortcuts(this->gogo_);
3520 retblock->traverse(&shortcuts);
3522 return Statement::make_block_statement(retblock, loc);
3525 // Turn shortcut operators into explicit if statements. Doing this
3526 // considerably simplifies the order of evaluation rules.
3528 void
3529 Gogo::remove_shortcuts()
3531 Shortcuts shortcuts(this);
3532 this->traverse(&shortcuts);
3535 // A traversal class which finds all the expressions which must be
3536 // evaluated in order within a statement or larger expression. This
3537 // is used to implement the rules about order of evaluation.
3539 class Find_eval_ordering : public Traverse
3541 private:
3542 typedef std::vector<Expression**> Expression_pointers;
3544 public:
3545 Find_eval_ordering()
3546 : Traverse(traverse_blocks
3547 | traverse_statements
3548 | traverse_expressions),
3549 exprs_()
3552 size_t
3553 size() const
3554 { return this->exprs_.size(); }
3556 typedef Expression_pointers::const_iterator const_iterator;
3558 const_iterator
3559 begin() const
3560 { return this->exprs_.begin(); }
3562 const_iterator
3563 end() const
3564 { return this->exprs_.end(); }
3566 protected:
3568 block(Block*)
3569 { return TRAVERSE_SKIP_COMPONENTS; }
3572 statement(Block*, size_t*, Statement*)
3573 { return TRAVERSE_SKIP_COMPONENTS; }
3576 expression(Expression**);
3578 private:
3579 // A list of pointers to expressions with side-effects.
3580 Expression_pointers exprs_;
3583 // If an expression must be evaluated in order, put it on the list.
3586 Find_eval_ordering::expression(Expression** expression_pointer)
3588 // We have to look at subexpressions before this one.
3589 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3590 return TRAVERSE_EXIT;
3591 if ((*expression_pointer)->must_eval_in_order())
3592 this->exprs_.push_back(expression_pointer);
3593 return TRAVERSE_SKIP_COMPONENTS;
3596 // A traversal class for ordering evaluations.
3598 class Order_eval : public Traverse
3600 public:
3601 Order_eval(Gogo* gogo)
3602 : Traverse(traverse_variables
3603 | traverse_statements),
3604 gogo_(gogo)
3608 variable(Named_object*);
3611 statement(Block*, size_t*, Statement*);
3613 private:
3614 // The IR.
3615 Gogo* gogo_;
3618 // Implement the order of evaluation rules for a statement.
3621 Order_eval::statement(Block* block, size_t* pindex, Statement* stmt)
3623 // FIXME: This approach doesn't work for switch statements, because
3624 // we add the new statements before the whole switch when we need to
3625 // instead add them just before the switch expression. The right
3626 // fix is probably to lower switch statements with nonconstant cases
3627 // to a series of conditionals.
3628 if (stmt->switch_statement() != NULL)
3629 return TRAVERSE_CONTINUE;
3631 Find_eval_ordering find_eval_ordering;
3633 // If S is a variable declaration, then ordinary traversal won't do
3634 // anything. We want to explicitly traverse the initialization
3635 // expression if there is one.
3636 Variable_declaration_statement* vds = stmt->variable_declaration_statement();
3637 Expression* init = NULL;
3638 Expression* orig_init = NULL;
3639 if (vds == NULL)
3640 stmt->traverse_contents(&find_eval_ordering);
3641 else
3643 init = vds->var()->var_value()->init();
3644 if (init == NULL)
3645 return TRAVERSE_CONTINUE;
3646 orig_init = init;
3648 // It might seem that this could be
3649 // init->traverse_subexpressions. Unfortunately that can fail
3650 // in a case like
3651 // var err os.Error
3652 // newvar, err := call(arg())
3653 // Here newvar will have an init of call result 0 of
3654 // call(arg()). If we only traverse subexpressions, we will
3655 // only find arg(), and we won't bother to move anything out.
3656 // Then we get to the assignment to err, we will traverse the
3657 // whole statement, and this time we will find both call() and
3658 // arg(), and so we will move them out. This will cause them to
3659 // be put into temporary variables before the assignment to err
3660 // but after the declaration of newvar. To avoid that problem,
3661 // we traverse the entire expression here.
3662 Expression::traverse(&init, &find_eval_ordering);
3665 size_t c = find_eval_ordering.size();
3666 if (c == 0)
3667 return TRAVERSE_CONTINUE;
3669 // If there is only one expression with a side-effect, we can
3670 // usually leave it in place.
3671 if (c == 1)
3673 switch (stmt->classification())
3675 case Statement::STATEMENT_ASSIGNMENT:
3676 // For an assignment statement, we need to evaluate an
3677 // expression on the right hand side before we evaluate any
3678 // index expression on the left hand side, so for that case
3679 // we always move the expression. Otherwise we mishandle
3680 // m[0] = len(m) where m is a map.
3681 break;
3683 case Statement::STATEMENT_EXPRESSION:
3685 // If this is a call statement that doesn't return any
3686 // values, it will not have been counted as a value to
3687 // move. We need to move any subexpressions in case they
3688 // are themselves call statements that require passing a
3689 // closure.
3690 Expression* expr = stmt->expression_statement()->expr();
3691 if (expr->call_expression() != NULL
3692 && expr->call_expression()->result_count() == 0)
3693 break;
3694 return TRAVERSE_CONTINUE;
3697 default:
3698 // We can leave the expression in place.
3699 return TRAVERSE_CONTINUE;
3703 bool is_thunk = stmt->thunk_statement() != NULL;
3704 Expression_statement* es = stmt->expression_statement();
3705 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3706 p != find_eval_ordering.end();
3707 ++p)
3709 Expression** pexpr = *p;
3711 // The last expression in a thunk will be the call passed to go
3712 // or defer, which we must not evaluate early.
3713 if (is_thunk && p + 1 == find_eval_ordering.end())
3714 break;
3716 Location loc = (*pexpr)->location();
3717 Statement* s;
3718 if ((*pexpr)->call_expression() == NULL
3719 || (*pexpr)->call_expression()->result_count() < 2)
3721 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3722 loc);
3723 s = ts;
3724 *pexpr = Expression::make_temporary_reference(ts, loc);
3726 else
3728 // A call expression which returns multiple results needs to
3729 // be handled specially. We can't create a temporary
3730 // because there is no type to give it. Any actual uses of
3731 // the values will be done via Call_result_expressions.
3733 // Since a given call expression can be shared by multiple
3734 // Call_result_expressions, avoid hoisting the call the
3735 // second time we see it here. In addition, don't try to
3736 // hoist the top-level multi-return call in the statement,
3737 // since doing this would result a tree with more than one copy
3738 // of the call.
3739 if (this->remember_expression(*pexpr))
3740 s = NULL;
3741 else if (es != NULL && *pexpr == es->expr())
3742 s = NULL;
3743 else
3744 s = Statement::make_statement(*pexpr, true);
3747 if (s != NULL)
3749 block->insert_statement_before(*pindex, s);
3750 ++*pindex;
3754 if (init != orig_init)
3755 vds->var()->var_value()->set_init(init);
3757 return TRAVERSE_CONTINUE;
3760 // Implement the order of evaluation rules for the initializer of a
3761 // global variable.
3764 Order_eval::variable(Named_object* no)
3766 if (no->is_result_variable())
3767 return TRAVERSE_CONTINUE;
3768 Variable* var = no->var_value();
3769 Expression* init = var->init();
3770 if (!var->is_global() || init == NULL)
3771 return TRAVERSE_CONTINUE;
3773 Find_eval_ordering find_eval_ordering;
3774 Expression::traverse(&init, &find_eval_ordering);
3776 if (find_eval_ordering.size() <= 1)
3778 // If there is only one expression with a side-effect, we can
3779 // leave it in place.
3780 return TRAVERSE_SKIP_COMPONENTS;
3783 Expression* orig_init = init;
3785 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3786 p != find_eval_ordering.end();
3787 ++p)
3789 Expression** pexpr = *p;
3790 Location loc = (*pexpr)->location();
3791 Statement* s;
3792 if ((*pexpr)->call_expression() == NULL
3793 || (*pexpr)->call_expression()->result_count() < 2)
3795 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3796 loc);
3797 s = ts;
3798 *pexpr = Expression::make_temporary_reference(ts, loc);
3800 else
3802 // A call expression which returns multiple results needs to
3803 // be handled specially.
3804 s = Statement::make_statement(*pexpr, true);
3806 var->add_preinit_statement(this->gogo_, s);
3809 if (init != orig_init)
3810 var->set_init(init);
3812 return TRAVERSE_SKIP_COMPONENTS;
3815 // Use temporary variables to implement the order of evaluation rules.
3817 void
3818 Gogo::order_evaluations()
3820 Order_eval order_eval(this);
3821 this->traverse(&order_eval);
3824 // Traversal to flatten parse tree after order of evaluation rules are applied.
3826 class Flatten : public Traverse
3828 public:
3829 Flatten(Gogo* gogo, Named_object* function)
3830 : Traverse(traverse_variables
3831 | traverse_functions
3832 | traverse_statements
3833 | traverse_expressions),
3834 gogo_(gogo), function_(function), inserter_()
3837 void
3838 set_inserter(const Statement_inserter* inserter)
3839 { this->inserter_ = *inserter; }
3842 variable(Named_object*);
3845 function(Named_object*);
3848 statement(Block*, size_t* pindex, Statement*);
3851 expression(Expression**);
3853 private:
3854 // General IR.
3855 Gogo* gogo_;
3856 // The function we are traversing.
3857 Named_object* function_;
3858 // Current statement inserter for use by expressions.
3859 Statement_inserter inserter_;
3862 // Flatten variables.
3865 Flatten::variable(Named_object* no)
3867 if (!no->is_variable())
3868 return TRAVERSE_CONTINUE;
3870 if (no->is_variable() && no->var_value()->is_global())
3872 // Global variables can have loops in their initialization
3873 // expressions. This is handled in flatten_init_expression.
3874 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
3875 &this->inserter_);
3876 return TRAVERSE_CONTINUE;
3879 go_assert(!no->var_value()->has_pre_init());
3881 return TRAVERSE_SKIP_COMPONENTS;
3884 // Flatten the body of a function. Record the function while flattening it,
3885 // so that we can pass it down when flattening an expression.
3888 Flatten::function(Named_object* no)
3890 go_assert(this->function_ == NULL);
3891 this->function_ = no;
3892 int t = no->func_value()->traverse(this);
3893 this->function_ = NULL;
3895 if (t == TRAVERSE_EXIT)
3896 return t;
3897 return TRAVERSE_SKIP_COMPONENTS;
3900 // Flatten statement parse trees.
3903 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
3905 // Because we explicitly traverse the statement's contents
3906 // ourselves, we want to skip block statements here. There is
3907 // nothing to flatten in a block statement.
3908 if (sorig->is_block_statement())
3909 return TRAVERSE_CONTINUE;
3911 Statement_inserter hold_inserter(this->inserter_);
3912 this->inserter_ = Statement_inserter(block, pindex);
3914 // Flatten the expressions first.
3915 int t = sorig->traverse_contents(this);
3916 if (t == TRAVERSE_EXIT)
3918 this->inserter_ = hold_inserter;
3919 return t;
3922 // Keep flattening until nothing changes.
3923 Statement* s = sorig;
3924 while (true)
3926 Statement* snew = s->flatten(this->gogo_, this->function_, block,
3927 &this->inserter_);
3928 if (snew == s)
3929 break;
3930 s = snew;
3931 t = s->traverse_contents(this);
3932 if (t == TRAVERSE_EXIT)
3934 this->inserter_ = hold_inserter;
3935 return t;
3939 if (s != sorig)
3940 block->replace_statement(*pindex, s);
3942 this->inserter_ = hold_inserter;
3943 return TRAVERSE_SKIP_COMPONENTS;
3946 // Flatten expression parse trees.
3949 Flatten::expression(Expression** pexpr)
3951 // Keep flattening until nothing changes.
3952 while (true)
3954 Expression* e = *pexpr;
3955 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
3956 return TRAVERSE_EXIT;
3958 Expression* enew = e->flatten(this->gogo_, this->function_,
3959 &this->inserter_);
3960 if (enew == e)
3961 break;
3962 *pexpr = enew;
3964 return TRAVERSE_SKIP_COMPONENTS;
3967 // Flatten a block.
3969 void
3970 Gogo::flatten_block(Named_object* function, Block* block)
3972 Flatten flatten(this, function);
3973 block->traverse(&flatten);
3976 // Flatten an expression. INSERTER may be NULL, in which case the
3977 // expression had better not need to create any temporaries.
3979 void
3980 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
3981 Expression** pexpr)
3983 Flatten flatten(this, function);
3984 if (inserter != NULL)
3985 flatten.set_inserter(inserter);
3986 flatten.expression(pexpr);
3989 void
3990 Gogo::flatten()
3992 Flatten flatten(this, NULL);
3993 this->traverse(&flatten);
3996 // Traversal to convert calls to the predeclared recover function to
3997 // pass in an argument indicating whether it can recover from a panic
3998 // or not.
4000 class Convert_recover : public Traverse
4002 public:
4003 Convert_recover(Named_object* arg)
4004 : Traverse(traverse_expressions),
4005 arg_(arg)
4008 protected:
4010 expression(Expression**);
4012 private:
4013 // The argument to pass to the function.
4014 Named_object* arg_;
4017 // Convert calls to recover.
4020 Convert_recover::expression(Expression** pp)
4022 Call_expression* ce = (*pp)->call_expression();
4023 if (ce != NULL && ce->is_recover_call())
4024 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
4025 ce->location()));
4026 return TRAVERSE_CONTINUE;
4029 // Traversal for build_recover_thunks.
4031 class Build_recover_thunks : public Traverse
4033 public:
4034 Build_recover_thunks(Gogo* gogo)
4035 : Traverse(traverse_functions),
4036 gogo_(gogo)
4040 function(Named_object*);
4042 private:
4043 Expression*
4044 can_recover_arg(Location);
4046 // General IR.
4047 Gogo* gogo_;
4050 // If this function calls recover, turn it into a thunk.
4053 Build_recover_thunks::function(Named_object* orig_no)
4055 Function* orig_func = orig_no->func_value();
4056 if (!orig_func->calls_recover()
4057 || orig_func->is_recover_thunk()
4058 || orig_func->has_recover_thunk())
4059 return TRAVERSE_CONTINUE;
4061 Gogo* gogo = this->gogo_;
4062 Location location = orig_func->location();
4064 static int count;
4065 char buf[50];
4067 Function_type* orig_fntype = orig_func->type();
4068 Typed_identifier_list* new_params = new Typed_identifier_list();
4069 std::string receiver_name;
4070 if (orig_fntype->is_method())
4072 const Typed_identifier* receiver = orig_fntype->receiver();
4073 snprintf(buf, sizeof buf, "rt.%u", count);
4074 ++count;
4075 receiver_name = buf;
4076 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
4077 receiver->location()));
4079 const Typed_identifier_list* orig_params = orig_fntype->parameters();
4080 if (orig_params != NULL && !orig_params->empty())
4082 for (Typed_identifier_list::const_iterator p = orig_params->begin();
4083 p != orig_params->end();
4084 ++p)
4086 snprintf(buf, sizeof buf, "pt.%u", count);
4087 ++count;
4088 new_params->push_back(Typed_identifier(buf, p->type(),
4089 p->location()));
4092 snprintf(buf, sizeof buf, "pr.%u", count);
4093 ++count;
4094 std::string can_recover_name = buf;
4095 new_params->push_back(Typed_identifier(can_recover_name,
4096 Type::lookup_bool_type(),
4097 orig_fntype->location()));
4099 const Typed_identifier_list* orig_results = orig_fntype->results();
4100 Typed_identifier_list* new_results;
4101 if (orig_results == NULL || orig_results->empty())
4102 new_results = NULL;
4103 else
4105 new_results = new Typed_identifier_list();
4106 for (Typed_identifier_list::const_iterator p = orig_results->begin();
4107 p != orig_results->end();
4108 ++p)
4109 new_results->push_back(Typed_identifier("", p->type(), p->location()));
4112 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
4113 new_results,
4114 orig_fntype->location());
4115 if (orig_fntype->is_varargs())
4116 new_fntype->set_is_varargs();
4118 Type* rtype = NULL;
4119 if (orig_fntype->is_method())
4120 rtype = orig_fntype->receiver()->type();
4121 std::string name(gogo->recover_thunk_name(orig_no->name(), rtype));
4122 Named_object *new_no = gogo->start_function(name, new_fntype, false,
4123 location);
4124 Function *new_func = new_no->func_value();
4125 if (orig_func->enclosing() != NULL)
4126 new_func->set_enclosing(orig_func->enclosing());
4128 // We build the code for the original function attached to the new
4129 // function, and then swap the original and new function bodies.
4130 // This means that existing references to the original function will
4131 // then refer to the new function. That makes this code a little
4132 // confusing, in that the reference to NEW_NO really refers to the
4133 // other function, not the one we are building.
4135 Expression* closure = NULL;
4136 if (orig_func->needs_closure())
4138 // For the new function we are creating, declare a new parameter
4139 // variable NEW_CLOSURE_NO and set it to be the closure variable
4140 // of the function. This will be set to the closure value
4141 // passed in by the caller. Then pass a reference to this
4142 // variable as the closure value when calling the original
4143 // function. In other words, simply pass the closure value
4144 // through the thunk we are creating.
4145 Named_object* orig_closure_no = orig_func->closure_var();
4146 Variable* orig_closure_var = orig_closure_no->var_value();
4147 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
4148 false, false, location);
4149 new_var->set_is_closure();
4150 snprintf(buf, sizeof buf, "closure.%u", count);
4151 ++count;
4152 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
4153 new_var);
4154 new_func->set_closure_var(new_closure_no);
4155 closure = Expression::make_var_reference(new_closure_no, location);
4158 Expression* fn = Expression::make_func_reference(new_no, closure, location);
4160 Expression_list* args = new Expression_list();
4161 if (new_params != NULL)
4163 // Note that we skip the last parameter, which is the boolean
4164 // indicating whether recover can succed.
4165 for (Typed_identifier_list::const_iterator p = new_params->begin();
4166 p + 1 != new_params->end();
4167 ++p)
4169 Named_object* p_no = gogo->lookup(p->name(), NULL);
4170 go_assert(p_no != NULL
4171 && p_no->is_variable()
4172 && p_no->var_value()->is_parameter());
4173 args->push_back(Expression::make_var_reference(p_no, location));
4176 args->push_back(this->can_recover_arg(location));
4178 gogo->start_block(location);
4180 Call_expression* call = Expression::make_call(fn, args, false, location);
4182 // Any varargs call has already been lowered.
4183 call->set_varargs_are_lowered();
4185 Statement* s = Statement::make_return_from_call(call, location);
4186 s->determine_types();
4187 gogo->add_statement(s);
4189 Block* b = gogo->finish_block(location);
4191 gogo->add_block(b, location);
4193 // Lower the call in case it returns multiple results.
4194 gogo->lower_block(new_no, b);
4196 gogo->finish_function(location);
4198 // Swap the function bodies and types.
4199 new_func->swap_for_recover(orig_func);
4200 orig_func->set_is_recover_thunk();
4201 new_func->set_calls_recover();
4202 new_func->set_has_recover_thunk();
4204 Bindings* orig_bindings = orig_func->block()->bindings();
4205 Bindings* new_bindings = new_func->block()->bindings();
4206 if (orig_fntype->is_method())
4208 // We changed the receiver to be a regular parameter. We have
4209 // to update the binding accordingly in both functions.
4210 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
4211 go_assert(orig_rec_no != NULL
4212 && orig_rec_no->is_variable()
4213 && !orig_rec_no->var_value()->is_receiver());
4214 orig_rec_no->var_value()->set_is_receiver();
4216 std::string new_receiver_name(orig_fntype->receiver()->name());
4217 if (new_receiver_name.empty())
4219 // Find the receiver. It was named "r.NNN" in
4220 // Gogo::start_function.
4221 for (Bindings::const_definitions_iterator p =
4222 new_bindings->begin_definitions();
4223 p != new_bindings->end_definitions();
4224 ++p)
4226 const std::string& pname((*p)->name());
4227 if (pname[0] == 'r' && pname[1] == '.')
4229 new_receiver_name = pname;
4230 break;
4233 go_assert(!new_receiver_name.empty());
4235 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
4236 if (new_rec_no == NULL)
4237 go_assert(saw_errors());
4238 else
4240 go_assert(new_rec_no->is_variable()
4241 && new_rec_no->var_value()->is_receiver());
4242 new_rec_no->var_value()->set_is_not_receiver();
4246 // Because we flipped blocks but not types, the can_recover
4247 // parameter appears in the (now) old bindings as a parameter.
4248 // Change it to a local variable, whereupon it will be discarded.
4249 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
4250 go_assert(can_recover_no != NULL
4251 && can_recover_no->is_variable()
4252 && can_recover_no->var_value()->is_parameter());
4253 orig_bindings->remove_binding(can_recover_no);
4255 // Add the can_recover argument to the (now) new bindings, and
4256 // attach it to any recover statements.
4257 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
4258 false, true, false, location);
4259 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
4260 can_recover_var);
4261 Convert_recover convert_recover(can_recover_no);
4262 new_func->traverse(&convert_recover);
4264 // Update the function pointers in any named results.
4265 new_func->update_result_variables();
4266 orig_func->update_result_variables();
4268 return TRAVERSE_CONTINUE;
4271 // Return the expression to pass for the .can_recover parameter to the
4272 // new function. This indicates whether a call to recover may return
4273 // non-nil. The expression is runtime.canrecover(__builtin_return_address()).
4275 Expression*
4276 Build_recover_thunks::can_recover_arg(Location location)
4278 static Named_object* builtin_return_address;
4279 if (builtin_return_address == NULL)
4280 builtin_return_address =
4281 Gogo::declare_builtin_rf_address("__builtin_return_address");
4283 static Named_object* can_recover;
4284 if (can_recover == NULL)
4286 const Location bloc = Linemap::predeclared_location();
4287 Typed_identifier_list* param_types = new Typed_identifier_list();
4288 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4289 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
4290 Type* boolean_type = Type::lookup_bool_type();
4291 Typed_identifier_list* results = new Typed_identifier_list();
4292 results->push_back(Typed_identifier("", boolean_type, bloc));
4293 Function_type* fntype = Type::make_function_type(NULL, param_types,
4294 results, bloc);
4295 can_recover =
4296 Named_object::make_function_declaration("runtime_canrecover",
4297 NULL, fntype, bloc);
4298 can_recover->func_declaration_value()->set_asm_name("runtime.canrecover");
4301 Expression* fn = Expression::make_func_reference(builtin_return_address,
4302 NULL, location);
4304 Expression* zexpr = Expression::make_integer_ul(0, NULL, location);
4305 Expression_list *args = new Expression_list();
4306 args->push_back(zexpr);
4308 Expression* call = Expression::make_call(fn, args, false, location);
4310 args = new Expression_list();
4311 args->push_back(call);
4313 fn = Expression::make_func_reference(can_recover, NULL, location);
4314 return Expression::make_call(fn, args, false, location);
4317 // Build thunks for functions which call recover. We build a new
4318 // function with an extra parameter, which is whether a call to
4319 // recover can succeed. We then move the body of this function to
4320 // that one. We then turn this function into a thunk which calls the
4321 // new one, passing the value of runtime.canrecover(__builtin_return_address()).
4322 // The function will be marked as not splitting the stack. This will
4323 // cooperate with the implementation of defer to make recover do the
4324 // right thing.
4326 void
4327 Gogo::build_recover_thunks()
4329 Build_recover_thunks build_recover_thunks(this);
4330 this->traverse(&build_recover_thunks);
4333 // Return a declaration for __builtin_return_address or
4334 // __builtin_frame_address.
4336 Named_object*
4337 Gogo::declare_builtin_rf_address(const char* name)
4339 const Location bloc = Linemap::predeclared_location();
4341 Typed_identifier_list* param_types = new Typed_identifier_list();
4342 Type* uint32_type = Type::lookup_integer_type("uint32");
4343 param_types->push_back(Typed_identifier("l", uint32_type, bloc));
4345 Typed_identifier_list* return_types = new Typed_identifier_list();
4346 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4347 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4349 Function_type* fntype = Type::make_function_type(NULL, param_types,
4350 return_types, bloc);
4351 Named_object* ret = Named_object::make_function_declaration(name, NULL,
4352 fntype, bloc);
4353 ret->func_declaration_value()->set_asm_name(name);
4354 return ret;
4357 // Build a call to the runtime error function.
4359 Expression*
4360 Gogo::runtime_error(int code, Location location)
4362 Type* int32_type = Type::lookup_integer_type("int32");
4363 Expression* code_expr = Expression::make_integer_ul(code, int32_type,
4364 location);
4365 return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4368 // Look for named types to see whether we need to create an interface
4369 // method table.
4371 class Build_method_tables : public Traverse
4373 public:
4374 Build_method_tables(Gogo* gogo,
4375 const std::vector<Interface_type*>& interfaces)
4376 : Traverse(traverse_types),
4377 gogo_(gogo), interfaces_(interfaces)
4381 type(Type*);
4383 private:
4384 // The IR.
4385 Gogo* gogo_;
4386 // A list of locally defined interfaces which have hidden methods.
4387 const std::vector<Interface_type*>& interfaces_;
4390 // Build all required interface method tables for types. We need to
4391 // ensure that we have an interface method table for every interface
4392 // which has a hidden method, for every named type which implements
4393 // that interface. Normally we can just build interface method tables
4394 // as we need them. However, in some cases we can require an
4395 // interface method table for an interface defined in a different
4396 // package for a type defined in that package. If that interface and
4397 // type both use a hidden method, that is OK. However, we will not be
4398 // able to build that interface method table when we need it, because
4399 // the type's hidden method will be static. So we have to build it
4400 // here, and just refer it from other packages as needed.
4402 void
4403 Gogo::build_interface_method_tables()
4405 if (saw_errors())
4406 return;
4408 std::vector<Interface_type*> hidden_interfaces;
4409 hidden_interfaces.reserve(this->interface_types_.size());
4410 for (std::vector<Interface_type*>::const_iterator pi =
4411 this->interface_types_.begin();
4412 pi != this->interface_types_.end();
4413 ++pi)
4415 const Typed_identifier_list* methods = (*pi)->methods();
4416 if (methods == NULL)
4417 continue;
4418 for (Typed_identifier_list::const_iterator pm = methods->begin();
4419 pm != methods->end();
4420 ++pm)
4422 if (Gogo::is_hidden_name(pm->name()))
4424 hidden_interfaces.push_back(*pi);
4425 break;
4430 if (!hidden_interfaces.empty())
4432 // Now traverse the tree looking for all named types.
4433 Build_method_tables bmt(this, hidden_interfaces);
4434 this->traverse(&bmt);
4437 // We no longer need the list of interfaces.
4439 this->interface_types_.clear();
4442 // This is called for each type. For a named type, for each of the
4443 // interfaces with hidden methods that it implements, create the
4444 // method table.
4447 Build_method_tables::type(Type* type)
4449 Named_type* nt = type->named_type();
4450 Struct_type* st = type->struct_type();
4451 if (nt != NULL || st != NULL)
4453 Translate_context context(this->gogo_, NULL, NULL, NULL);
4454 for (std::vector<Interface_type*>::const_iterator p =
4455 this->interfaces_.begin();
4456 p != this->interfaces_.end();
4457 ++p)
4459 // We ask whether a pointer to the named type implements the
4460 // interface, because a pointer can implement more methods
4461 // than a value.
4462 if (nt != NULL)
4464 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4465 NULL))
4467 nt->interface_method_table(*p, false)->get_backend(&context);
4468 nt->interface_method_table(*p, true)->get_backend(&context);
4471 else
4473 if ((*p)->implements_interface(Type::make_pointer_type(st),
4474 NULL))
4476 st->interface_method_table(*p, false)->get_backend(&context);
4477 st->interface_method_table(*p, true)->get_backend(&context);
4482 return TRAVERSE_CONTINUE;
4485 // Return an expression which allocates memory to hold values of type TYPE.
4487 Expression*
4488 Gogo::allocate_memory(Type* type, Location location)
4490 Expression* td = Expression::make_type_descriptor(type, location);
4491 return Runtime::make_call(Runtime::NEW, location, 1, td);
4494 // Traversal class used to check for return statements.
4496 class Check_return_statements_traverse : public Traverse
4498 public:
4499 Check_return_statements_traverse()
4500 : Traverse(traverse_functions)
4504 function(Named_object*);
4507 // Check that a function has a return statement if it needs one.
4510 Check_return_statements_traverse::function(Named_object* no)
4512 Function* func = no->func_value();
4513 const Function_type* fntype = func->type();
4514 const Typed_identifier_list* results = fntype->results();
4516 // We only need a return statement if there is a return value.
4517 if (results == NULL || results->empty())
4518 return TRAVERSE_CONTINUE;
4520 if (func->block()->may_fall_through())
4521 go_error_at(func->block()->end_location(),
4522 "missing return at end of function");
4524 return TRAVERSE_CONTINUE;
4527 // Check return statements.
4529 void
4530 Gogo::check_return_statements()
4532 Check_return_statements_traverse traverse;
4533 this->traverse(&traverse);
4536 // Export identifiers as requested.
4538 void
4539 Gogo::do_exports()
4541 // For now we always stream to a section. Later we may want to
4542 // support streaming to a separate file.
4543 Stream_to_section stream(this->backend());
4545 // Write out either the prefix or pkgpath depending on how we were
4546 // invoked.
4547 std::string prefix;
4548 std::string pkgpath;
4549 if (this->pkgpath_from_option_)
4550 pkgpath = this->pkgpath_;
4551 else if (this->prefix_from_option_)
4552 prefix = this->prefix_;
4553 else if (this->is_main_package())
4554 pkgpath = "main";
4555 else
4556 prefix = "go";
4558 Export exp(&stream);
4559 exp.register_builtin_types(this);
4560 exp.export_globals(this->package_name(),
4561 prefix,
4562 pkgpath,
4563 this->packages_,
4564 this->imports_,
4565 (this->need_init_fn_ && !this->is_main_package()
4566 ? this->get_init_fn_name()
4567 : ""),
4568 this->imported_init_fns_,
4569 this->package_->bindings());
4571 if (!this->c_header_.empty() && !saw_errors())
4572 this->write_c_header();
4575 // Write the top level named struct types in C format to a C header
4576 // file. This is used when building the runtime package, to share
4577 // struct definitions between C and Go.
4579 void
4580 Gogo::write_c_header()
4582 std::ofstream out;
4583 out.open(this->c_header_.c_str());
4584 if (out.fail())
4586 go_error_at(Linemap::unknown_location(),
4587 "cannot open %s: %m", this->c_header_.c_str());
4588 return;
4591 std::list<Named_object*> types;
4592 Bindings* top = this->package_->bindings();
4593 for (Bindings::const_definitions_iterator p = top->begin_definitions();
4594 p != top->end_definitions();
4595 ++p)
4597 Named_object* no = *p;
4599 // Skip names that start with underscore followed by something
4600 // other than an uppercase letter, as when compiling the runtime
4601 // package they are mostly types defined by mkrsysinfo.sh based
4602 // on the C system header files. We don't need to translate
4603 // types to C and back to Go. But do accept the special cases
4604 // _defer and _panic.
4605 std::string name = Gogo::unpack_hidden_name(no->name());
4606 if (name[0] == '_'
4607 && (name[1] < 'A' || name[1] > 'Z')
4608 && (name != "_defer" && name != "_panic"))
4609 continue;
4611 if (no->is_type() && no->type_value()->struct_type() != NULL)
4612 types.push_back(no);
4613 if (no->is_const() && no->const_value()->type()->integer_type() != NULL)
4615 Numeric_constant nc;
4616 unsigned long val;
4617 if (no->const_value()->expr()->numeric_constant_value(&nc)
4618 && nc.to_unsigned_long(&val) == Numeric_constant::NC_UL_VALID)
4620 out << "#define " << no->message_name() << ' ' << val
4621 << std::endl;
4626 std::vector<const Named_object*> written;
4627 int loop = 0;
4628 while (!types.empty())
4630 Named_object* no = types.front();
4631 types.pop_front();
4633 std::vector<const Named_object*> requires;
4634 std::vector<const Named_object*> declare;
4635 if (!no->type_value()->struct_type()->can_write_to_c_header(&requires,
4636 &declare))
4637 continue;
4639 bool ok = true;
4640 for (std::vector<const Named_object*>::const_iterator pr
4641 = requires.begin();
4642 pr != requires.end() && ok;
4643 ++pr)
4645 for (std::list<Named_object*>::const_iterator pt = types.begin();
4646 pt != types.end() && ok;
4647 ++pt)
4648 if (*pr == *pt)
4649 ok = false;
4651 if (!ok)
4653 ++loop;
4654 if (loop > 10000)
4656 // This should be impossible since the code parsed and
4657 // type checked.
4658 go_unreachable();
4661 types.push_back(no);
4662 continue;
4665 for (std::vector<const Named_object*>::const_iterator pd
4666 = declare.begin();
4667 pd != declare.end();
4668 ++pd)
4670 if (*pd == no)
4671 continue;
4673 std::vector<const Named_object*> drequires;
4674 std::vector<const Named_object*> ddeclare;
4675 if (!(*pd)->type_value()->struct_type()->
4676 can_write_to_c_header(&drequires, &ddeclare))
4677 continue;
4679 bool done = false;
4680 for (std::vector<const Named_object*>::const_iterator pw
4681 = written.begin();
4682 pw != written.end();
4683 ++pw)
4685 if (*pw == *pd)
4687 done = true;
4688 break;
4691 if (!done)
4693 out << std::endl;
4694 out << "struct " << (*pd)->message_name() << ";" << std::endl;
4695 written.push_back(*pd);
4699 out << std::endl;
4700 out << "struct " << no->message_name() << " {" << std::endl;
4701 no->type_value()->struct_type()->write_to_c_header(out);
4702 out << "};" << std::endl;
4703 written.push_back(no);
4706 out.close();
4707 if (out.fail())
4708 go_error_at(Linemap::unknown_location(),
4709 "error writing to %s: %m", this->c_header_.c_str());
4712 // Find the blocks in order to convert named types defined in blocks.
4714 class Convert_named_types : public Traverse
4716 public:
4717 Convert_named_types(Gogo* gogo)
4718 : Traverse(traverse_blocks),
4719 gogo_(gogo)
4722 protected:
4724 block(Block* block);
4726 private:
4727 Gogo* gogo_;
4731 Convert_named_types::block(Block* block)
4733 this->gogo_->convert_named_types_in_bindings(block->bindings());
4734 return TRAVERSE_CONTINUE;
4737 // Convert all named types to the backend representation. Since named
4738 // types can refer to other types, this needs to be done in the right
4739 // sequence, which is handled by Named_type::convert. Here we arrange
4740 // to call that for each named type.
4742 void
4743 Gogo::convert_named_types()
4745 this->convert_named_types_in_bindings(this->globals_);
4746 for (Packages::iterator p = this->packages_.begin();
4747 p != this->packages_.end();
4748 ++p)
4750 Package* package = p->second;
4751 this->convert_named_types_in_bindings(package->bindings());
4754 Convert_named_types cnt(this);
4755 this->traverse(&cnt);
4757 // Make all the builtin named types used for type descriptors, and
4758 // then convert them. They will only be written out if they are
4759 // needed.
4760 Type::make_type_descriptor_type();
4761 Type::make_type_descriptor_ptr_type();
4762 Function_type::make_function_type_descriptor_type();
4763 Pointer_type::make_pointer_type_descriptor_type();
4764 Struct_type::make_struct_type_descriptor_type();
4765 Array_type::make_array_type_descriptor_type();
4766 Array_type::make_slice_type_descriptor_type();
4767 Map_type::make_map_type_descriptor_type();
4768 Channel_type::make_chan_type_descriptor_type();
4769 Interface_type::make_interface_type_descriptor_type();
4770 Expression::make_func_descriptor_type();
4771 Type::convert_builtin_named_types(this);
4773 Runtime::convert_types(this);
4775 this->named_types_are_converted_ = true;
4777 Type::finish_pointer_types(this);
4780 // Convert all names types in a set of bindings.
4782 void
4783 Gogo::convert_named_types_in_bindings(Bindings* bindings)
4785 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4786 p != bindings->end_definitions();
4787 ++p)
4789 if ((*p)->is_type())
4790 (*p)->type_value()->convert(this);
4794 // Class Function.
4796 Function::Function(Function_type* type, Named_object* enclosing, Block* block,
4797 Location location)
4798 : type_(type), enclosing_(enclosing), results_(NULL),
4799 closure_var_(NULL), block_(block), location_(location), labels_(),
4800 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
4801 pragmas_(0), is_sink_(false), results_are_named_(false),
4802 is_unnamed_type_stub_method_(false), calls_recover_(false),
4803 is_recover_thunk_(false), has_recover_thunk_(false),
4804 calls_defer_retaddr_(false), is_type_specific_function_(false),
4805 in_unique_section_(false)
4809 // Create the named result variables.
4811 void
4812 Function::create_result_variables(Gogo* gogo)
4814 const Typed_identifier_list* results = this->type_->results();
4815 if (results == NULL || results->empty())
4816 return;
4818 if (!results->front().name().empty())
4819 this->results_are_named_ = true;
4821 this->results_ = new Results();
4822 this->results_->reserve(results->size());
4824 Block* block = this->block_;
4825 int index = 0;
4826 for (Typed_identifier_list::const_iterator p = results->begin();
4827 p != results->end();
4828 ++p, ++index)
4830 std::string name = p->name();
4831 if (name.empty() || Gogo::is_sink_name(name))
4833 static int result_counter;
4834 char buf[100];
4835 snprintf(buf, sizeof buf, "$ret%d", result_counter);
4836 ++result_counter;
4837 name = gogo->pack_hidden_name(buf, false);
4839 Result_variable* result = new Result_variable(p->type(), this, index,
4840 p->location());
4841 Named_object* no = block->bindings()->add_result_variable(name, result);
4842 if (no->is_result_variable())
4843 this->results_->push_back(no);
4844 else
4846 static int dummy_result_count;
4847 char buf[100];
4848 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
4849 ++dummy_result_count;
4850 name = gogo->pack_hidden_name(buf, false);
4851 no = block->bindings()->add_result_variable(name, result);
4852 go_assert(no->is_result_variable());
4853 this->results_->push_back(no);
4858 // Update the named result variables when cloning a function which
4859 // calls recover.
4861 void
4862 Function::update_result_variables()
4864 if (this->results_ == NULL)
4865 return;
4867 for (Results::iterator p = this->results_->begin();
4868 p != this->results_->end();
4869 ++p)
4870 (*p)->result_var_value()->set_function(this);
4873 // Whether this method should not be included in the type descriptor.
4875 bool
4876 Function::nointerface() const
4878 go_assert(this->is_method());
4879 return (this->pragmas_ & GOPRAGMA_NOINTERFACE) != 0;
4882 // Record that this method should not be included in the type
4883 // descriptor.
4885 void
4886 Function::set_nointerface()
4888 this->pragmas_ |= GOPRAGMA_NOINTERFACE;
4891 // Return the closure variable, creating it if necessary.
4893 Named_object*
4894 Function::closure_var()
4896 if (this->closure_var_ == NULL)
4898 go_assert(this->descriptor_ == NULL);
4899 // We don't know the type of the variable yet. We add fields as
4900 // we find them.
4901 Location loc = this->type_->location();
4902 Struct_field_list* sfl = new Struct_field_list;
4903 Struct_type* struct_type = Type::make_struct_type(sfl, loc);
4904 struct_type->set_is_struct_incomparable();
4905 Variable* var = new Variable(Type::make_pointer_type(struct_type),
4906 NULL, false, false, false, loc);
4907 var->set_is_used();
4908 var->set_is_closure();
4909 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
4910 // Note that the new variable is not in any binding contour.
4912 return this->closure_var_;
4915 // Set the type of the closure variable.
4917 void
4918 Function::set_closure_type()
4920 if (this->closure_var_ == NULL)
4921 return;
4922 Named_object* closure = this->closure_var_;
4923 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
4925 // The first field of a closure is always a pointer to the function
4926 // code.
4927 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4928 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
4929 this->location_)));
4931 unsigned int index = 1;
4932 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
4933 p != this->closure_fields_.end();
4934 ++p, ++index)
4936 Named_object* no = p->first;
4937 char buf[20];
4938 snprintf(buf, sizeof buf, "%u", index);
4939 std::string n = no->name() + buf;
4940 Type* var_type;
4941 if (no->is_variable())
4942 var_type = no->var_value()->type();
4943 else
4944 var_type = no->result_var_value()->type();
4945 Type* field_type = Type::make_pointer_type(var_type);
4946 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
4950 // Return whether this function is a method.
4952 bool
4953 Function::is_method() const
4955 return this->type_->is_method();
4958 // Add a label definition.
4960 Label*
4961 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
4962 Location location)
4964 Label* lnull = NULL;
4965 std::pair<Labels::iterator, bool> ins =
4966 this->labels_.insert(std::make_pair(label_name, lnull));
4967 Label* label;
4968 if (label_name == "_")
4970 label = Label::create_dummy_label();
4971 if (ins.second)
4972 ins.first->second = label;
4974 else if (ins.second)
4976 // This is a new label.
4977 label = new Label(label_name);
4978 ins.first->second = label;
4980 else
4982 // The label was already in the hash table.
4983 label = ins.first->second;
4984 if (label->is_defined())
4986 go_error_at(location, "label %qs already defined",
4987 Gogo::message_name(label_name).c_str());
4988 go_inform(label->location(), "previous definition of %qs was here",
4989 Gogo::message_name(label_name).c_str());
4990 return new Label(label_name);
4994 label->define(location, gogo->bindings_snapshot(location));
4996 // Issue any errors appropriate for any previous goto's to this
4997 // label.
4998 const std::vector<Bindings_snapshot*>& refs(label->refs());
4999 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
5000 p != refs.end();
5001 ++p)
5002 (*p)->check_goto_to(gogo->current_block());
5003 label->clear_refs();
5005 return label;
5008 // Add a reference to a label.
5010 Label*
5011 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
5012 Location location, bool issue_goto_errors)
5014 Label* lnull = NULL;
5015 std::pair<Labels::iterator, bool> ins =
5016 this->labels_.insert(std::make_pair(label_name, lnull));
5017 Label* label;
5018 if (!ins.second)
5020 // The label was already in the hash table.
5021 label = ins.first->second;
5023 else
5025 go_assert(ins.first->second == NULL);
5026 label = new Label(label_name);
5027 ins.first->second = label;
5030 label->set_is_used();
5032 if (issue_goto_errors)
5034 Bindings_snapshot* snapshot = label->snapshot();
5035 if (snapshot != NULL)
5036 snapshot->check_goto_from(gogo->current_block(), location);
5037 else
5038 label->add_snapshot_ref(gogo->bindings_snapshot(location));
5041 return label;
5044 // Warn about labels that are defined but not used.
5046 void
5047 Function::check_labels() const
5049 for (Labels::const_iterator p = this->labels_.begin();
5050 p != this->labels_.end();
5051 p++)
5053 Label* label = p->second;
5054 if (!label->is_used())
5055 go_error_at(label->location(), "label %qs defined and not used",
5056 Gogo::message_name(label->name()).c_str());
5060 // Swap one function with another. This is used when building the
5061 // thunk we use to call a function which calls recover. It may not
5062 // work for any other case.
5064 void
5065 Function::swap_for_recover(Function *x)
5067 go_assert(this->enclosing_ == x->enclosing_);
5068 std::swap(this->results_, x->results_);
5069 std::swap(this->closure_var_, x->closure_var_);
5070 std::swap(this->block_, x->block_);
5071 go_assert(this->location_ == x->location_);
5072 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
5073 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
5076 // Traverse the tree.
5079 Function::traverse(Traverse* traverse)
5081 unsigned int traverse_mask = traverse->traverse_mask();
5083 if ((traverse_mask
5084 & (Traverse::traverse_types | Traverse::traverse_expressions))
5085 != 0)
5087 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
5088 return TRAVERSE_EXIT;
5091 // FIXME: We should check traverse_functions here if nested
5092 // functions are stored in block bindings.
5093 if (this->block_ != NULL
5094 && (traverse_mask
5095 & (Traverse::traverse_variables
5096 | Traverse::traverse_constants
5097 | Traverse::traverse_blocks
5098 | Traverse::traverse_statements
5099 | Traverse::traverse_expressions
5100 | Traverse::traverse_types)) != 0)
5102 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
5103 return TRAVERSE_EXIT;
5106 return TRAVERSE_CONTINUE;
5109 // Work out types for unspecified variables and constants.
5111 void
5112 Function::determine_types()
5114 if (this->block_ != NULL)
5115 this->block_->determine_types();
5118 // Return the function descriptor, the value you get when you refer to
5119 // the function in Go code without calling it.
5121 Expression*
5122 Function::descriptor(Gogo*, Named_object* no)
5124 go_assert(!this->is_method());
5125 go_assert(this->closure_var_ == NULL);
5126 if (this->descriptor_ == NULL)
5127 this->descriptor_ = Expression::make_func_descriptor(no);
5128 return this->descriptor_;
5131 // Get a pointer to the variable representing the defer stack for this
5132 // function, making it if necessary. The value of the variable is set
5133 // by the runtime routines to true if the function is returning,
5134 // rather than panicing through. A pointer to this variable is used
5135 // as a marker for the functions on the defer stack associated with
5136 // this function. A function-specific variable permits inlining a
5137 // function which uses defer.
5139 Expression*
5140 Function::defer_stack(Location location)
5142 if (this->defer_stack_ == NULL)
5144 Type* t = Type::lookup_bool_type();
5145 Expression* n = Expression::make_boolean(false, location);
5146 this->defer_stack_ = Statement::make_temporary(t, n, location);
5147 this->defer_stack_->set_is_address_taken();
5149 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
5150 location);
5151 return Expression::make_unary(OPERATOR_AND, ref, location);
5154 // Export the function.
5156 void
5157 Function::export_func(Export* exp, const std::string& name) const
5159 Function::export_func_with_type(exp, name, this->type_);
5162 // Export a function with a type.
5164 void
5165 Function::export_func_with_type(Export* exp, const std::string& name,
5166 const Function_type* fntype)
5168 exp->write_c_string("func ");
5170 if (fntype->is_method())
5172 exp->write_c_string("(");
5173 const Typed_identifier* receiver = fntype->receiver();
5174 exp->write_name(receiver->name());
5175 exp->write_escape(receiver->note());
5176 exp->write_c_string(" ");
5177 exp->write_type(receiver->type());
5178 exp->write_c_string(") ");
5181 exp->write_string(name);
5183 exp->write_c_string(" (");
5184 const Typed_identifier_list* parameters = fntype->parameters();
5185 if (parameters != NULL)
5187 size_t i = 0;
5188 bool is_varargs = fntype->is_varargs();
5189 bool first = true;
5190 for (Typed_identifier_list::const_iterator p = parameters->begin();
5191 p != parameters->end();
5192 ++p, ++i)
5194 if (first)
5195 first = false;
5196 else
5197 exp->write_c_string(", ");
5198 exp->write_name(p->name());
5199 exp->write_escape(p->note());
5200 exp->write_c_string(" ");
5201 if (!is_varargs || p + 1 != parameters->end())
5202 exp->write_type(p->type());
5203 else
5205 exp->write_c_string("...");
5206 exp->write_type(p->type()->array_type()->element_type());
5210 exp->write_c_string(")");
5212 const Typed_identifier_list* results = fntype->results();
5213 if (results != NULL)
5215 if (results->size() == 1 && results->begin()->name().empty())
5217 exp->write_c_string(" ");
5218 exp->write_type(results->begin()->type());
5220 else
5222 exp->write_c_string(" (");
5223 bool first = true;
5224 for (Typed_identifier_list::const_iterator p = results->begin();
5225 p != results->end();
5226 ++p)
5228 if (first)
5229 first = false;
5230 else
5231 exp->write_c_string(", ");
5232 exp->write_name(p->name());
5233 exp->write_escape(p->note());
5234 exp->write_c_string(" ");
5235 exp->write_type(p->type());
5237 exp->write_c_string(")");
5240 exp->write_c_string(";\n");
5243 // Import a function.
5245 void
5246 Function::import_func(Import* imp, std::string* pname,
5247 Typed_identifier** preceiver,
5248 Typed_identifier_list** pparameters,
5249 Typed_identifier_list** presults,
5250 bool* is_varargs)
5252 imp->require_c_string("func ");
5254 *preceiver = NULL;
5255 if (imp->peek_char() == '(')
5257 imp->require_c_string("(");
5258 std::string name = imp->read_name();
5259 std::string escape_note = imp->read_escape();
5260 imp->require_c_string(" ");
5261 Type* rtype = imp->read_type();
5262 *preceiver = new Typed_identifier(name, rtype, imp->location());
5263 (*preceiver)->set_note(escape_note);
5264 imp->require_c_string(") ");
5267 *pname = imp->read_identifier();
5269 Typed_identifier_list* parameters;
5270 *is_varargs = false;
5271 imp->require_c_string(" (");
5272 if (imp->peek_char() == ')')
5273 parameters = NULL;
5274 else
5276 parameters = new Typed_identifier_list();
5277 while (true)
5279 std::string name = imp->read_name();
5280 std::string escape_note = imp->read_escape();
5281 imp->require_c_string(" ");
5283 if (imp->match_c_string("..."))
5285 imp->advance(3);
5286 *is_varargs = true;
5289 Type* ptype = imp->read_type();
5290 if (*is_varargs)
5291 ptype = Type::make_array_type(ptype, NULL);
5292 Typed_identifier t = Typed_identifier(name, ptype, imp->location());
5293 t.set_note(escape_note);
5294 parameters->push_back(t);
5295 if (imp->peek_char() != ',')
5296 break;
5297 go_assert(!*is_varargs);
5298 imp->require_c_string(", ");
5301 imp->require_c_string(")");
5302 *pparameters = parameters;
5304 Typed_identifier_list* results;
5305 if (imp->peek_char() != ' ')
5306 results = NULL;
5307 else
5309 results = new Typed_identifier_list();
5310 imp->require_c_string(" ");
5311 if (imp->peek_char() != '(')
5313 Type* rtype = imp->read_type();
5314 results->push_back(Typed_identifier("", rtype, imp->location()));
5316 else
5318 imp->require_c_string("(");
5319 while (true)
5321 std::string name = imp->read_name();
5322 std::string note = imp->read_escape();
5323 imp->require_c_string(" ");
5324 Type* rtype = imp->read_type();
5325 Typed_identifier t = Typed_identifier(name, rtype,
5326 imp->location());
5327 t.set_note(note);
5328 results->push_back(t);
5329 if (imp->peek_char() != ',')
5330 break;
5331 imp->require_c_string(", ");
5333 imp->require_c_string(")");
5336 imp->require_c_string(";\n");
5337 *presults = results;
5340 // Get the backend representation.
5342 Bfunction*
5343 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
5345 if (this->fndecl_ == NULL)
5347 bool is_visible = false;
5348 bool is_init_fn = false;
5349 Type* rtype = NULL;
5350 if (no->package() != NULL)
5352 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
5354 else if (Gogo::unpack_hidden_name(no->name()) == "init"
5355 && !this->type_->is_method())
5357 else if (no->name() == gogo->get_init_fn_name())
5359 is_visible = true;
5360 is_init_fn = true;
5362 else if (Gogo::unpack_hidden_name(no->name()) == "main"
5363 && gogo->is_main_package())
5364 is_visible = true;
5365 // Methods have to be public even if they are hidden because
5366 // they can be pulled into type descriptors when using
5367 // anonymous fields.
5368 else if (!Gogo::is_hidden_name(no->name())
5369 || this->type_->is_method())
5371 if (!this->is_unnamed_type_stub_method_)
5372 is_visible = true;
5373 if (this->type_->is_method())
5374 rtype = this->type_->receiver()->type();
5377 std::string asm_name;
5378 if (!this->asm_name_.empty())
5380 asm_name = this->asm_name_;
5382 // If an assembler name is explicitly specified, there must
5383 // be some reason to refer to the symbol from a different
5384 // object file.
5385 is_visible = true;
5387 else if (is_init_fn)
5389 // These names appear in the export data and are used
5390 // directly in the assembler code. If we change this here
5391 // we need to change Gogo::init_imports.
5392 asm_name = no->name();
5394 else
5395 asm_name = gogo->function_asm_name(no->name(), NULL, rtype);
5397 // If a function calls the predeclared recover function, we
5398 // can't inline it, because recover behaves differently in a
5399 // function passed directly to defer. If this is a recover
5400 // thunk that we built to test whether a function can be
5401 // recovered, we can't inline it, because that will mess up
5402 // our return address comparison.
5403 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
5405 // If a function calls __go_set_defer_retaddr, then mark it as
5406 // uninlinable. This prevents the GCC backend from splitting
5407 // the function; splitting the function is a bad idea because we
5408 // want the return address label to be in the same function as
5409 // the call.
5410 if (this->calls_defer_retaddr_)
5411 is_inlinable = false;
5413 // Check the //go:noinline compiler directive.
5414 if ((this->pragmas_ & GOPRAGMA_NOINLINE) != 0)
5415 is_inlinable = false;
5417 // If this is a thunk created to call a function which calls
5418 // the predeclared recover function, we need to disable
5419 // stack splitting for the thunk.
5420 bool disable_split_stack = this->is_recover_thunk_;
5422 // Check the //go:nosplit compiler directive.
5423 if ((this->pragmas_ & GOPRAGMA_NOSPLIT) != 0)
5424 disable_split_stack = true;
5426 // This should go into a unique section if that has been
5427 // requested elsewhere, or if this is a nointerface function.
5428 // We want to put a nointerface function into a unique section
5429 // because there is a good chance that the linker garbage
5430 // collection can discard it.
5431 bool in_unique_section = (this->in_unique_section_
5432 || (this->is_method() && this->nointerface()));
5434 Btype* functype = this->type_->get_backend_fntype(gogo);
5435 this->fndecl_ =
5436 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5437 is_visible, false, is_inlinable,
5438 disable_split_stack, false,
5439 in_unique_section, this->location());
5441 return this->fndecl_;
5444 // Get the backend representation.
5446 Bfunction*
5447 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
5449 if (this->fndecl_ == NULL)
5451 bool does_not_return = false;
5453 // Let Go code use an asm declaration to pick up a builtin
5454 // function.
5455 if (!this->asm_name_.empty())
5457 Bfunction* builtin_decl =
5458 gogo->backend()->lookup_builtin(this->asm_name_);
5459 if (builtin_decl != NULL)
5461 this->fndecl_ = builtin_decl;
5462 return this->fndecl_;
5465 if (this->asm_name_ == "runtime.gopanic"
5466 || this->asm_name_ == "__go_runtime_error")
5467 does_not_return = true;
5470 std::string asm_name;
5471 if (this->asm_name_.empty())
5473 Type* rtype = NULL;
5474 if (this->fntype_->is_method())
5475 rtype = this->fntype_->receiver()->type();
5476 asm_name = gogo->function_asm_name(no->name(), no->package(), rtype);
5478 else if (go_id_needs_encoding(no->get_id(gogo)))
5479 asm_name = go_encode_id(no->get_id(gogo));
5481 Btype* functype = this->fntype_->get_backend_fntype(gogo);
5482 this->fndecl_ =
5483 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5484 true, true, true, false, does_not_return,
5485 false, this->location());
5488 return this->fndecl_;
5491 // Build the descriptor for a function declaration. This won't
5492 // necessarily happen if the package has just a declaration for the
5493 // function and no other reference to it, but we may still need the
5494 // descriptor for references from other packages.
5495 void
5496 Function_declaration::build_backend_descriptor(Gogo* gogo)
5498 if (this->descriptor_ != NULL)
5500 Translate_context context(gogo, NULL, NULL, NULL);
5501 this->descriptor_->get_backend(&context);
5505 // Check that the types used in this declaration's signature are defined.
5506 // Reports errors for any undefined type.
5508 void
5509 Function_declaration::check_types() const
5511 // Calling Type::base will give errors for any undefined types.
5512 Function_type* fntype = this->type();
5513 if (fntype->receiver() != NULL)
5514 fntype->receiver()->type()->base();
5515 if (fntype->parameters() != NULL)
5517 const Typed_identifier_list* params = fntype->parameters();
5518 for (Typed_identifier_list::const_iterator p = params->begin();
5519 p != params->end();
5520 ++p)
5521 p->type()->base();
5525 // Return the function's decl after it has been built.
5527 Bfunction*
5528 Function::get_decl() const
5530 go_assert(this->fndecl_ != NULL);
5531 return this->fndecl_;
5534 // Build the backend representation for the function code.
5536 void
5537 Function::build(Gogo* gogo, Named_object* named_function)
5539 Translate_context context(gogo, named_function, NULL, NULL);
5541 // A list of parameter variables for this function.
5542 std::vector<Bvariable*> param_vars;
5544 // Variables that need to be declared for this function and their
5545 // initial values.
5546 std::vector<Bvariable*> vars;
5547 std::vector<Bexpression*> var_inits;
5548 for (Bindings::const_definitions_iterator p =
5549 this->block_->bindings()->begin_definitions();
5550 p != this->block_->bindings()->end_definitions();
5551 ++p)
5553 Location loc = (*p)->location();
5554 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
5556 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5557 Bvariable* parm_bvar = bvar;
5559 // We always pass the receiver to a method as a pointer. If
5560 // the receiver is declared as a non-pointer type, then we
5561 // copy the value into a local variable.
5562 if ((*p)->var_value()->is_receiver()
5563 && (*p)->var_value()->type()->points_to() == NULL)
5565 std::string name = (*p)->name() + ".pointer";
5566 Type* var_type = (*p)->var_value()->type();
5567 Variable* parm_var =
5568 new Variable(Type::make_pointer_type(var_type), NULL, false,
5569 true, false, loc);
5570 Named_object* parm_no =
5571 Named_object::make_variable(name, NULL, parm_var);
5572 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5574 vars.push_back(bvar);
5575 Expression* parm_ref =
5576 Expression::make_var_reference(parm_no, loc);
5577 parm_ref =
5578 Expression::make_dereference(parm_ref,
5579 Expression::NIL_CHECK_DEFAULT,
5580 loc);
5581 if ((*p)->var_value()->is_in_heap())
5582 parm_ref = Expression::make_heap_expression(parm_ref, loc);
5583 var_inits.push_back(parm_ref->get_backend(&context));
5585 else if ((*p)->var_value()->is_in_heap())
5587 // If we take the address of a parameter, then we need
5588 // to copy it into the heap.
5589 std::string parm_name = (*p)->name() + ".param";
5590 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
5591 false, true, false, loc);
5592 Named_object* parm_no =
5593 Named_object::make_variable(parm_name, NULL, parm_var);
5594 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5596 vars.push_back(bvar);
5597 Expression* var_ref =
5598 Expression::make_var_reference(parm_no, loc);
5599 var_ref = Expression::make_heap_expression(var_ref, loc);
5600 var_inits.push_back(var_ref->get_backend(&context));
5602 param_vars.push_back(parm_bvar);
5604 else if ((*p)->is_result_variable())
5606 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5608 Type* type = (*p)->result_var_value()->type();
5609 Bexpression* init;
5610 if (!(*p)->result_var_value()->is_in_heap())
5612 Btype* btype = type->get_backend(gogo);
5613 init = gogo->backend()->zero_expression(btype);
5615 else
5616 init = Expression::make_allocation(type,
5617 loc)->get_backend(&context);
5619 vars.push_back(bvar);
5620 var_inits.push_back(init);
5623 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
5625 go_assert(saw_errors());
5626 return;
5629 // If we need a closure variable, make sure to create it.
5630 // It gets installed in the function as a side effect of creation.
5631 if (this->closure_var_ != NULL)
5633 go_assert(this->closure_var_->var_value()->is_closure());
5634 this->closure_var_->get_backend_variable(gogo, named_function);
5637 if (this->block_ != NULL)
5639 // Declare variables if necessary.
5640 Bblock* var_decls = NULL;
5642 Bstatement* defer_init = NULL;
5643 if (!vars.empty() || this->defer_stack_ != NULL)
5645 var_decls =
5646 gogo->backend()->block(this->fndecl_, NULL, vars,
5647 this->block_->start_location(),
5648 this->block_->end_location());
5650 if (this->defer_stack_ != NULL)
5652 Translate_context dcontext(gogo, named_function, this->block_,
5653 var_decls);
5654 defer_init = this->defer_stack_->get_backend(&dcontext);
5658 // Build the backend representation for all the statements in the
5659 // function.
5660 Translate_context context(gogo, named_function, NULL, NULL);
5661 Bblock* code_block = this->block_->get_backend(&context);
5663 // Initialize variables if necessary.
5664 std::vector<Bstatement*> init;
5665 go_assert(vars.size() == var_inits.size());
5666 for (size_t i = 0; i < vars.size(); ++i)
5668 Bstatement* init_stmt =
5669 gogo->backend()->init_statement(this->fndecl_, vars[i],
5670 var_inits[i]);
5671 init.push_back(init_stmt);
5673 if (defer_init != NULL)
5674 init.push_back(defer_init);
5675 Bstatement* var_init = gogo->backend()->statement_list(init);
5677 // Initialize all variables before executing this code block.
5678 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
5679 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
5681 // If we have a defer stack, initialize it at the start of a
5682 // function.
5683 Bstatement* except = NULL;
5684 Bstatement* fini = NULL;
5685 if (defer_init != NULL)
5687 // Clean up the defer stack when we leave the function.
5688 this->build_defer_wrapper(gogo, named_function, &except, &fini);
5690 // Wrap the code for this function in an exception handler to handle
5691 // defer calls.
5692 code_stmt =
5693 gogo->backend()->exception_handler_statement(code_stmt,
5694 except, fini,
5695 this->location_);
5698 // Stick the code into the block we built for the receiver, if
5699 // we built one.
5700 if (var_decls != NULL)
5702 std::vector<Bstatement*> code_stmt_list(1, code_stmt);
5703 gogo->backend()->block_add_statements(var_decls, code_stmt_list);
5704 code_stmt = gogo->backend()->block_statement(var_decls);
5707 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
5709 go_assert(saw_errors());
5710 return;
5714 // If we created a descriptor for the function, make sure we emit it.
5715 if (this->descriptor_ != NULL)
5717 Translate_context context(gogo, NULL, NULL, NULL);
5718 this->descriptor_->get_backend(&context);
5722 // Build the wrappers around function code needed if the function has
5723 // any defer statements. This sets *EXCEPT to an exception handler
5724 // and *FINI to a finally handler.
5726 void
5727 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
5728 Bstatement** except, Bstatement** fini)
5730 Location end_loc = this->block_->end_location();
5732 // Add an exception handler. This is used if a panic occurs. Its
5733 // purpose is to stop the stack unwinding if a deferred function
5734 // calls recover. There are more details in
5735 // libgo/runtime/go-unwind.c.
5737 std::vector<Bstatement*> stmts;
5738 Expression* call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5739 this->defer_stack(end_loc));
5740 Translate_context context(gogo, named_function, NULL, NULL);
5741 Bexpression* defer = call->get_backend(&context);
5742 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, defer));
5744 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
5745 if (ret_bstmt != NULL)
5746 stmts.push_back(ret_bstmt);
5748 go_assert(*except == NULL);
5749 *except = gogo->backend()->statement_list(stmts);
5751 call = Runtime::make_call(Runtime::CHECKDEFER, end_loc, 1,
5752 this->defer_stack(end_loc));
5753 defer = call->get_backend(&context);
5755 call = Runtime::make_call(Runtime::DEFERRETURN, end_loc, 1,
5756 this->defer_stack(end_loc));
5757 Bexpression* undefer = call->get_backend(&context);
5758 Bstatement* function_defer =
5759 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
5760 end_loc);
5761 stmts = std::vector<Bstatement*>(1, function_defer);
5762 if (this->type_->results() != NULL
5763 && !this->type_->results()->empty()
5764 && !this->type_->results()->front().name().empty())
5766 // If the result variables are named, and we are returning from
5767 // this function rather than panicing through it, we need to
5768 // return them again, because they might have been changed by a
5769 // defer function. The runtime routines set the defer_stack
5770 // variable to true if we are returning from this function.
5772 ret_bstmt = this->return_value(gogo, named_function, end_loc);
5773 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
5774 Bexpression* ret =
5775 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
5776 Expression* ref =
5777 Expression::make_temporary_reference(this->defer_stack_, end_loc);
5778 Bexpression* bref = ref->get_backend(&context);
5779 ret = gogo->backend()->conditional_expression(this->fndecl_,
5780 NULL, bref, ret, NULL,
5781 end_loc);
5782 stmts.push_back(gogo->backend()->expression_statement(this->fndecl_, ret));
5785 go_assert(*fini == NULL);
5786 *fini = gogo->backend()->statement_list(stmts);
5789 // Return the statement that assigns values to this function's result struct.
5791 Bstatement*
5792 Function::return_value(Gogo* gogo, Named_object* named_function,
5793 Location location) const
5795 const Typed_identifier_list* results = this->type_->results();
5796 if (results == NULL || results->empty())
5797 return NULL;
5799 go_assert(this->results_ != NULL);
5800 if (this->results_->size() != results->size())
5802 go_assert(saw_errors());
5803 return gogo->backend()->error_statement();
5806 std::vector<Bexpression*> vals(results->size());
5807 for (size_t i = 0; i < vals.size(); ++i)
5809 Named_object* no = (*this->results_)[i];
5810 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
5811 Bexpression* val = gogo->backend()->var_expression(bvar, location);
5812 if (no->result_var_value()->is_in_heap())
5814 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
5815 val = gogo->backend()->indirect_expression(bt, val, true, location);
5817 vals[i] = val;
5819 return gogo->backend()->return_statement(this->fndecl_, vals, location);
5822 // Class Block.
5824 Block::Block(Block* enclosing, Location location)
5825 : enclosing_(enclosing), statements_(),
5826 bindings_(new Bindings(enclosing == NULL
5827 ? NULL
5828 : enclosing->bindings())),
5829 start_location_(location),
5830 end_location_(Linemap::unknown_location())
5834 // Add a statement to a block.
5836 void
5837 Block::add_statement(Statement* statement)
5839 this->statements_.push_back(statement);
5842 // Add a statement to the front of a block. This is slow but is only
5843 // used for reference counts of parameters.
5845 void
5846 Block::add_statement_at_front(Statement* statement)
5848 this->statements_.insert(this->statements_.begin(), statement);
5851 // Replace a statement in a block.
5853 void
5854 Block::replace_statement(size_t index, Statement* s)
5856 go_assert(index < this->statements_.size());
5857 this->statements_[index] = s;
5860 // Add a statement before another statement.
5862 void
5863 Block::insert_statement_before(size_t index, Statement* s)
5865 go_assert(index < this->statements_.size());
5866 this->statements_.insert(this->statements_.begin() + index, s);
5869 // Add a statement after another statement.
5871 void
5872 Block::insert_statement_after(size_t index, Statement* s)
5874 go_assert(index < this->statements_.size());
5875 this->statements_.insert(this->statements_.begin() + index + 1, s);
5878 // Traverse the tree.
5881 Block::traverse(Traverse* traverse)
5883 unsigned int traverse_mask = traverse->traverse_mask();
5885 if ((traverse_mask & Traverse::traverse_blocks) != 0)
5887 int t = traverse->block(this);
5888 if (t == TRAVERSE_EXIT)
5889 return TRAVERSE_EXIT;
5890 else if (t == TRAVERSE_SKIP_COMPONENTS)
5891 return TRAVERSE_CONTINUE;
5894 if ((traverse_mask
5895 & (Traverse::traverse_variables
5896 | Traverse::traverse_constants
5897 | Traverse::traverse_expressions
5898 | Traverse::traverse_types)) != 0)
5900 const unsigned int e_or_t = (Traverse::traverse_expressions
5901 | Traverse::traverse_types);
5902 const unsigned int e_or_t_or_s = (e_or_t
5903 | Traverse::traverse_statements);
5904 for (Bindings::const_definitions_iterator pb =
5905 this->bindings_->begin_definitions();
5906 pb != this->bindings_->end_definitions();
5907 ++pb)
5909 int t = TRAVERSE_CONTINUE;
5910 switch ((*pb)->classification())
5912 case Named_object::NAMED_OBJECT_CONST:
5913 if ((traverse_mask & Traverse::traverse_constants) != 0)
5914 t = traverse->constant(*pb, false);
5915 if (t == TRAVERSE_CONTINUE
5916 && (traverse_mask & e_or_t) != 0)
5918 Type* tc = (*pb)->const_value()->type();
5919 if (tc != NULL
5920 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5921 return TRAVERSE_EXIT;
5922 t = (*pb)->const_value()->traverse_expression(traverse);
5924 break;
5926 case Named_object::NAMED_OBJECT_VAR:
5927 case Named_object::NAMED_OBJECT_RESULT_VAR:
5928 if ((traverse_mask & Traverse::traverse_variables) != 0)
5929 t = traverse->variable(*pb);
5930 if (t == TRAVERSE_CONTINUE
5931 && (traverse_mask & e_or_t) != 0)
5933 if ((*pb)->is_result_variable()
5934 || (*pb)->var_value()->has_type())
5936 Type* tv = ((*pb)->is_variable()
5937 ? (*pb)->var_value()->type()
5938 : (*pb)->result_var_value()->type());
5939 if (tv != NULL
5940 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5941 return TRAVERSE_EXIT;
5944 if (t == TRAVERSE_CONTINUE
5945 && (traverse_mask & e_or_t_or_s) != 0
5946 && (*pb)->is_variable())
5947 t = (*pb)->var_value()->traverse_expression(traverse,
5948 traverse_mask);
5949 break;
5951 case Named_object::NAMED_OBJECT_FUNC:
5952 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5953 go_unreachable();
5955 case Named_object::NAMED_OBJECT_TYPE:
5956 if ((traverse_mask & e_or_t) != 0)
5957 t = Type::traverse((*pb)->type_value(), traverse);
5958 break;
5960 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5961 case Named_object::NAMED_OBJECT_UNKNOWN:
5962 case Named_object::NAMED_OBJECT_ERRONEOUS:
5963 break;
5965 case Named_object::NAMED_OBJECT_PACKAGE:
5966 case Named_object::NAMED_OBJECT_SINK:
5967 go_unreachable();
5969 default:
5970 go_unreachable();
5973 if (t == TRAVERSE_EXIT)
5974 return TRAVERSE_EXIT;
5978 // No point in checking traverse_mask here--if we got here we always
5979 // want to walk the statements. The traversal can insert new
5980 // statements before or after the current statement. Inserting
5981 // statements before the current statement requires updating I via
5982 // the pointer; those statements will not be traversed. Any new
5983 // statements inserted after the current statement will be traversed
5984 // in their turn.
5985 for (size_t i = 0; i < this->statements_.size(); ++i)
5987 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
5988 return TRAVERSE_EXIT;
5991 return TRAVERSE_CONTINUE;
5994 // Work out types for unspecified variables and constants.
5996 void
5997 Block::determine_types()
5999 for (Bindings::const_definitions_iterator pb =
6000 this->bindings_->begin_definitions();
6001 pb != this->bindings_->end_definitions();
6002 ++pb)
6004 if ((*pb)->is_variable())
6005 (*pb)->var_value()->determine_type();
6006 else if ((*pb)->is_const())
6007 (*pb)->const_value()->determine_type();
6010 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
6011 ps != this->statements_.end();
6012 ++ps)
6013 (*ps)->determine_types();
6016 // Return true if the statements in this block may fall through.
6018 bool
6019 Block::may_fall_through() const
6021 if (this->statements_.empty())
6022 return true;
6023 return this->statements_.back()->may_fall_through();
6026 // Convert a block to the backend representation.
6028 Bblock*
6029 Block::get_backend(Translate_context* context)
6031 Gogo* gogo = context->gogo();
6032 Named_object* function = context->function();
6033 std::vector<Bvariable*> vars;
6034 vars.reserve(this->bindings_->size_definitions());
6035 for (Bindings::const_definitions_iterator pv =
6036 this->bindings_->begin_definitions();
6037 pv != this->bindings_->end_definitions();
6038 ++pv)
6040 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
6041 vars.push_back((*pv)->get_backend_variable(gogo, function));
6044 go_assert(function != NULL);
6045 Bfunction* bfunction =
6046 function->func_value()->get_or_make_decl(gogo, function);
6047 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
6048 vars, this->start_location_,
6049 this->end_location_);
6051 Translate_context subcontext(gogo, function, this, ret);
6052 std::vector<Bstatement*> bstatements;
6053 bstatements.reserve(this->statements_.size());
6054 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
6055 p != this->statements_.end();
6056 ++p)
6057 bstatements.push_back((*p)->get_backend(&subcontext));
6059 context->backend()->block_add_statements(ret, bstatements);
6061 return ret;
6064 // Class Bindings_snapshot.
6066 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
6067 : block_(b), counts_(), location_(location)
6069 while (b != NULL)
6071 this->counts_.push_back(b->bindings()->size_definitions());
6072 b = b->enclosing();
6076 // Report errors appropriate for a goto from B to this.
6078 void
6079 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
6081 size_t dummy;
6082 if (!this->check_goto_block(loc, b, this->block_, &dummy))
6083 return;
6084 this->check_goto_defs(loc, this->block_,
6085 this->block_->bindings()->size_definitions(),
6086 this->counts_[0]);
6089 // Report errors appropriate for a goto from this to B.
6091 void
6092 Bindings_snapshot::check_goto_to(const Block* b)
6094 size_t index;
6095 if (!this->check_goto_block(this->location_, this->block_, b, &index))
6096 return;
6097 this->check_goto_defs(this->location_, b, this->counts_[index],
6098 b->bindings()->size_definitions());
6101 // Report errors appropriate for a goto at LOC from BFROM to BTO.
6102 // Return true if all is well, false if we reported an error. If this
6103 // returns true, it sets *PINDEX to the number of blocks BTO is above
6104 // BFROM.
6106 bool
6107 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
6108 const Block* bto, size_t* pindex)
6110 // It is an error if BTO is not either BFROM or above BFROM.
6111 size_t index = 0;
6112 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
6114 if (pb == NULL)
6116 go_error_at(loc, "goto jumps into block");
6117 go_inform(bto->start_location(), "goto target block starts here");
6118 return false;
6121 *pindex = index;
6122 return true;
6125 // Report errors appropriate for a goto at LOC ending at BLOCK, where
6126 // CFROM is the number of names defined at the point of the goto and
6127 // CTO is the number of names defined at the point of the label.
6129 void
6130 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
6131 size_t cfrom, size_t cto)
6133 if (cfrom < cto)
6135 Bindings::const_definitions_iterator p =
6136 block->bindings()->begin_definitions();
6137 for (size_t i = 0; i < cfrom; ++i)
6139 go_assert(p != block->bindings()->end_definitions());
6140 ++p;
6142 go_assert(p != block->bindings()->end_definitions());
6144 std::string n = (*p)->message_name();
6145 go_error_at(loc, "goto jumps over declaration of %qs", n.c_str());
6146 go_inform((*p)->location(), "%qs defined here", n.c_str());
6150 // Class Function_declaration.
6152 // Return the function descriptor.
6154 Expression*
6155 Function_declaration::descriptor(Gogo*, Named_object* no)
6157 go_assert(!this->fntype_->is_method());
6158 if (this->descriptor_ == NULL)
6159 this->descriptor_ = Expression::make_func_descriptor(no);
6160 return this->descriptor_;
6163 // Class Variable.
6165 Variable::Variable(Type* type, Expression* init, bool is_global,
6166 bool is_parameter, bool is_receiver,
6167 Location location)
6168 : type_(type), init_(init), preinit_(NULL), location_(location),
6169 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
6170 is_closure_(false), is_receiver_(is_receiver),
6171 is_varargs_parameter_(false), is_used_(false),
6172 is_address_taken_(false), is_non_escaping_address_taken_(false),
6173 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
6174 type_from_init_tuple_(false), type_from_range_index_(false),
6175 type_from_range_value_(false), type_from_chan_element_(false),
6176 is_type_switch_var_(false), determined_type_(false),
6177 in_unique_section_(false), escapes_(true)
6179 go_assert(type != NULL || init != NULL);
6180 go_assert(!is_parameter || init == NULL);
6183 // Traverse the initializer expression.
6186 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
6188 if (this->preinit_ != NULL)
6190 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
6191 return TRAVERSE_EXIT;
6193 if (this->init_ != NULL
6194 && ((traverse_mask
6195 & (Traverse::traverse_expressions | Traverse::traverse_types))
6196 != 0))
6198 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
6199 return TRAVERSE_EXIT;
6201 return TRAVERSE_CONTINUE;
6204 // Lower the initialization expression after parsing is complete.
6206 void
6207 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
6208 Statement_inserter* inserter)
6210 Named_object* dep = gogo->var_depends_on(this);
6211 if (dep != NULL && dep->is_variable())
6212 dep->var_value()->lower_init_expression(gogo, function, inserter);
6214 if (this->init_ != NULL && !this->init_is_lowered_)
6216 if (this->seen_)
6218 // We will give an error elsewhere, this is just to prevent
6219 // an infinite loop.
6220 return;
6222 this->seen_ = true;
6224 Statement_inserter global_inserter;
6225 if (this->is_global_)
6227 global_inserter = Statement_inserter(gogo, this);
6228 inserter = &global_inserter;
6231 gogo->lower_expression(function, inserter, &this->init_);
6233 this->seen_ = false;
6235 this->init_is_lowered_ = true;
6239 // Flatten the initialization expression after ordering evaluations.
6241 void
6242 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
6243 Statement_inserter* inserter)
6245 Named_object* dep = gogo->var_depends_on(this);
6246 if (dep != NULL && dep->is_variable())
6247 dep->var_value()->flatten_init_expression(gogo, function, inserter);
6249 if (this->init_ != NULL && !this->init_is_flattened_)
6251 if (this->seen_)
6253 // We will give an error elsewhere, this is just to prevent
6254 // an infinite loop.
6255 return;
6257 this->seen_ = true;
6259 Statement_inserter global_inserter;
6260 if (this->is_global_)
6262 global_inserter = Statement_inserter(gogo, this);
6263 inserter = &global_inserter;
6266 gogo->flatten_expression(function, inserter, &this->init_);
6268 // If an interface conversion is needed, we need a temporary
6269 // variable.
6270 if (this->type_ != NULL
6271 && !Type::are_identical(this->type_, this->init_->type(), false,
6272 NULL)
6273 && this->init_->type()->interface_type() != NULL
6274 && !this->init_->is_variable())
6276 Temporary_statement* temp =
6277 Statement::make_temporary(NULL, this->init_, this->location_);
6278 inserter->insert(temp);
6279 this->init_ = Expression::make_temporary_reference(temp,
6280 this->location_);
6283 this->seen_ = false;
6284 this->init_is_flattened_ = true;
6288 // Get the preinit block.
6290 Block*
6291 Variable::preinit_block(Gogo* gogo)
6293 go_assert(this->is_global_);
6294 if (this->preinit_ == NULL)
6295 this->preinit_ = new Block(NULL, this->location());
6297 // If a global variable has a preinitialization statement, then we
6298 // need to have an initialization function.
6299 gogo->set_need_init_fn();
6301 return this->preinit_;
6304 // Add a statement to be run before the initialization expression.
6306 void
6307 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
6309 Block* b = this->preinit_block(gogo);
6310 b->add_statement(s);
6311 b->set_end_location(s->location());
6314 // Whether this variable has a type.
6316 bool
6317 Variable::has_type() const
6319 if (this->type_ == NULL)
6320 return false;
6322 // A variable created in a type switch case nil does not actually
6323 // have a type yet. It will be changed to use the initializer's
6324 // type in determine_type.
6325 if (this->is_type_switch_var_
6326 && this->type_->is_nil_constant_as_type())
6327 return false;
6329 return true;
6332 // In an assignment which sets a variable to a tuple of EXPR, return
6333 // the type of the first element of the tuple.
6335 Type*
6336 Variable::type_from_tuple(Expression* expr, bool report_error) const
6338 if (expr->map_index_expression() != NULL)
6340 Map_type* mt = expr->map_index_expression()->get_map_type();
6341 if (mt == NULL)
6342 return Type::make_error_type();
6343 return mt->val_type();
6345 else if (expr->receive_expression() != NULL)
6347 Expression* channel = expr->receive_expression()->channel();
6348 Type* channel_type = channel->type();
6349 if (channel_type->channel_type() == NULL)
6350 return Type::make_error_type();
6351 return channel_type->channel_type()->element_type();
6353 else
6355 if (report_error)
6356 go_error_at(this->location(), "invalid tuple definition");
6357 return Type::make_error_type();
6361 // Given EXPR used in a range clause, return either the index type or
6362 // the value type of the range, depending upon GET_INDEX_TYPE.
6364 Type*
6365 Variable::type_from_range(Expression* expr, bool get_index_type,
6366 bool report_error) const
6368 Type* t = expr->type();
6369 if (t->array_type() != NULL
6370 || (t->points_to() != NULL
6371 && t->points_to()->array_type() != NULL
6372 && !t->points_to()->is_slice_type()))
6374 if (get_index_type)
6375 return Type::lookup_integer_type("int");
6376 else
6377 return t->deref()->array_type()->element_type();
6379 else if (t->is_string_type())
6381 if (get_index_type)
6382 return Type::lookup_integer_type("int");
6383 else
6384 return Type::lookup_integer_type("int32");
6386 else if (t->map_type() != NULL)
6388 if (get_index_type)
6389 return t->map_type()->key_type();
6390 else
6391 return t->map_type()->val_type();
6393 else if (t->channel_type() != NULL)
6395 if (get_index_type)
6396 return t->channel_type()->element_type();
6397 else
6399 if (report_error)
6400 go_error_at(this->location(),
6401 ("invalid definition of value variable "
6402 "for channel range"));
6403 return Type::make_error_type();
6406 else
6408 if (report_error)
6409 go_error_at(this->location(), "invalid type for range clause");
6410 return Type::make_error_type();
6414 // EXPR should be a channel. Return the channel's element type.
6416 Type*
6417 Variable::type_from_chan_element(Expression* expr, bool report_error) const
6419 Type* t = expr->type();
6420 if (t->channel_type() != NULL)
6421 return t->channel_type()->element_type();
6422 else
6424 if (report_error)
6425 go_error_at(this->location(), "expected channel");
6426 return Type::make_error_type();
6430 // Return the type of the Variable. This may be called before
6431 // Variable::determine_type is called, which means that we may need to
6432 // get the type from the initializer. FIXME: If we combine lowering
6433 // with type determination, then this should be unnecessary.
6435 Type*
6436 Variable::type()
6438 // A variable in a type switch with a nil case will have the wrong
6439 // type here. This gets fixed up in determine_type, below.
6440 Type* type = this->type_;
6441 Expression* init = this->init_;
6442 if (this->is_type_switch_var_
6443 && type != NULL
6444 && this->type_->is_nil_constant_as_type())
6446 Type_guard_expression* tge = this->init_->type_guard_expression();
6447 go_assert(tge != NULL);
6448 init = tge->expr();
6449 type = NULL;
6452 if (this->seen_)
6454 if (this->type_ == NULL || !this->type_->is_error_type())
6456 go_error_at(this->location_, "variable initializer refers to itself");
6457 this->type_ = Type::make_error_type();
6459 return this->type_;
6462 this->seen_ = true;
6464 if (type != NULL)
6466 else if (this->type_from_init_tuple_)
6467 type = this->type_from_tuple(init, false);
6468 else if (this->type_from_range_index_ || this->type_from_range_value_)
6469 type = this->type_from_range(init, this->type_from_range_index_, false);
6470 else if (this->type_from_chan_element_)
6471 type = this->type_from_chan_element(init, false);
6472 else
6474 go_assert(init != NULL);
6475 type = init->type();
6476 go_assert(type != NULL);
6478 // Variables should not have abstract types.
6479 if (type->is_abstract())
6480 type = type->make_non_abstract_type();
6482 if (type->is_void_type())
6483 type = Type::make_error_type();
6486 this->seen_ = false;
6488 return type;
6491 // Fetch the type from a const pointer, in which case it should have
6492 // been set already.
6494 Type*
6495 Variable::type() const
6497 go_assert(this->type_ != NULL);
6498 return this->type_;
6501 // Set the type if necessary.
6503 void
6504 Variable::determine_type()
6506 if (this->determined_type_)
6507 return;
6508 this->determined_type_ = true;
6510 if (this->preinit_ != NULL)
6511 this->preinit_->determine_types();
6513 // A variable in a type switch with a nil case will have the wrong
6514 // type here. It will have an initializer which is a type guard.
6515 // We want to initialize it to the value without the type guard, and
6516 // use the type of that value as well.
6517 if (this->is_type_switch_var_
6518 && this->type_ != NULL
6519 && this->type_->is_nil_constant_as_type())
6521 Type_guard_expression* tge = this->init_->type_guard_expression();
6522 go_assert(tge != NULL);
6523 this->type_ = NULL;
6524 this->init_ = tge->expr();
6527 if (this->init_ == NULL)
6528 go_assert(this->type_ != NULL && !this->type_->is_abstract());
6529 else if (this->type_from_init_tuple_)
6531 Expression *init = this->init_;
6532 init->determine_type_no_context();
6533 this->type_ = this->type_from_tuple(init, true);
6534 this->init_ = NULL;
6536 else if (this->type_from_range_index_ || this->type_from_range_value_)
6538 Expression* init = this->init_;
6539 init->determine_type_no_context();
6540 this->type_ = this->type_from_range(init, this->type_from_range_index_,
6541 true);
6542 this->init_ = NULL;
6544 else if (this->type_from_chan_element_)
6546 Expression* init = this->init_;
6547 init->determine_type_no_context();
6548 this->type_ = this->type_from_chan_element(init, true);
6549 this->init_ = NULL;
6551 else
6553 Type_context context(this->type_, false);
6554 this->init_->determine_type(&context);
6555 if (this->type_ == NULL)
6557 Type* type = this->init_->type();
6558 go_assert(type != NULL);
6559 if (type->is_abstract())
6560 type = type->make_non_abstract_type();
6562 if (type->is_void_type())
6564 go_error_at(this->location_, "variable has no type");
6565 type = Type::make_error_type();
6567 else if (type->is_nil_type())
6569 go_error_at(this->location_, "variable defined to nil type");
6570 type = Type::make_error_type();
6572 else if (type->is_call_multiple_result_type())
6574 go_error_at(this->location_,
6575 "single variable set to multiple-value function call");
6576 type = Type::make_error_type();
6579 this->type_ = type;
6584 // Get the initial value of a variable. This does not
6585 // consider whether the variable is in the heap--it returns the
6586 // initial value as though it were always stored in the stack.
6588 Bexpression*
6589 Variable::get_init(Gogo* gogo, Named_object* function)
6591 go_assert(this->preinit_ == NULL);
6592 Location loc = this->location();
6593 if (this->init_ == NULL)
6595 go_assert(!this->is_parameter_);
6596 if (this->is_global_ || this->is_in_heap())
6597 return NULL;
6598 Btype* btype = this->type()->get_backend(gogo);
6599 return gogo->backend()->zero_expression(btype);
6601 else
6603 Translate_context context(gogo, function, NULL, NULL);
6604 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
6605 return init->get_backend(&context);
6609 // Get the initial value of a variable when a block is required.
6610 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6612 Bstatement*
6613 Variable::get_init_block(Gogo* gogo, Named_object* function,
6614 Bvariable* var_decl)
6616 go_assert(this->preinit_ != NULL);
6618 // We want to add the variable assignment to the end of the preinit
6619 // block.
6621 Translate_context context(gogo, function, NULL, NULL);
6622 Bblock* bblock = this->preinit_->get_backend(&context);
6623 Bfunction* bfunction =
6624 function->func_value()->get_or_make_decl(gogo, function);
6626 // It's possible to have pre-init statements without an initializer
6627 // if the pre-init statements set the variable.
6628 Bstatement* decl_init = NULL;
6629 if (this->init_ != NULL)
6631 if (var_decl == NULL)
6633 Bexpression* init_bexpr = this->init_->get_backend(&context);
6634 decl_init = gogo->backend()->expression_statement(bfunction,
6635 init_bexpr);
6637 else
6639 Location loc = this->location();
6640 Expression* val_expr =
6641 Expression::make_cast(this->type(), this->init_, loc);
6642 Bexpression* val = val_expr->get_backend(&context);
6643 Bexpression* var_ref =
6644 gogo->backend()->var_expression(var_decl, loc);
6645 decl_init = gogo->backend()->assignment_statement(bfunction, var_ref,
6646 val, loc);
6649 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
6650 if (decl_init != NULL)
6651 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
6652 return block_stmt;
6655 // Export the variable
6657 void
6658 Variable::export_var(Export* exp, const std::string& name) const
6660 go_assert(this->is_global_);
6661 exp->write_c_string("var ");
6662 exp->write_string(name);
6663 exp->write_c_string(" ");
6664 exp->write_type(this->type());
6665 exp->write_c_string(";\n");
6668 // Import a variable.
6670 void
6671 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
6673 imp->require_c_string("var ");
6674 *pname = imp->read_identifier();
6675 imp->require_c_string(" ");
6676 *ptype = imp->read_type();
6677 imp->require_c_string(";\n");
6680 // Convert a variable to the backend representation.
6682 Bvariable*
6683 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
6684 const Package* package, const std::string& name)
6686 if (this->backend_ == NULL)
6688 Backend* backend = gogo->backend();
6689 Type* type = this->type_;
6690 if (type->is_error_type()
6691 || (type->is_undefined()
6692 && (!this->is_global_ || package == NULL)))
6693 this->backend_ = backend->error_variable();
6694 else
6696 bool is_parameter = this->is_parameter_;
6697 if (this->is_receiver_ && type->points_to() == NULL)
6698 is_parameter = false;
6699 if (this->is_in_heap())
6701 is_parameter = false;
6702 type = Type::make_pointer_type(type);
6705 const std::string n = Gogo::unpack_hidden_name(name);
6706 Btype* btype = type->get_backend(gogo);
6708 Bvariable* bvar;
6709 if (Map_type::is_zero_value(this))
6710 bvar = Map_type::backend_zero_value(gogo);
6711 else if (this->is_global_)
6713 std::string var_name(package != NULL
6714 ? package->package_name()
6715 : gogo->package_name());
6716 var_name.push_back('.');
6717 var_name.append(n);
6719 std::string asm_name(gogo->global_var_asm_name(name, package));
6721 bool is_hidden = Gogo::is_hidden_name(name);
6722 // Hack to export runtime.writeBarrier. FIXME.
6723 // This is because go:linkname doesn't work on variables.
6724 if (gogo->compiling_runtime()
6725 && var_name == "runtime.writeBarrier")
6726 is_hidden = false;
6728 bvar = backend->global_variable(var_name,
6729 asm_name,
6730 btype,
6731 package != NULL,
6732 is_hidden,
6733 this->in_unique_section_,
6734 this->location_);
6736 else if (function == NULL)
6738 go_assert(saw_errors());
6739 bvar = backend->error_variable();
6741 else
6743 Bfunction* bfunction = function->func_value()->get_decl();
6744 bool is_address_taken = (this->is_non_escaping_address_taken_
6745 && !this->is_in_heap());
6746 if (this->is_closure())
6747 bvar = backend->static_chain_variable(bfunction, n, btype,
6748 this->location_);
6749 else if (is_parameter)
6750 bvar = backend->parameter_variable(bfunction, n, btype,
6751 is_address_taken,
6752 this->location_);
6753 else
6754 bvar = backend->local_variable(bfunction, n, btype,
6755 is_address_taken,
6756 this->location_);
6758 this->backend_ = bvar;
6761 return this->backend_;
6764 // Class Result_variable.
6766 // Convert a result variable to the backend representation.
6768 Bvariable*
6769 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
6770 const std::string& name)
6772 if (this->backend_ == NULL)
6774 Backend* backend = gogo->backend();
6775 Type* type = this->type_;
6776 if (type->is_error())
6777 this->backend_ = backend->error_variable();
6778 else
6780 if (this->is_in_heap())
6781 type = Type::make_pointer_type(type);
6782 Btype* btype = type->get_backend(gogo);
6783 Bfunction* bfunction = function->func_value()->get_decl();
6784 std::string n = Gogo::unpack_hidden_name(name);
6785 bool is_address_taken = (this->is_non_escaping_address_taken_
6786 && !this->is_in_heap());
6787 this->backend_ = backend->local_variable(bfunction, n, btype,
6788 is_address_taken,
6789 this->location_);
6792 return this->backend_;
6795 // Class Named_constant.
6797 // Traverse the initializer expression.
6800 Named_constant::traverse_expression(Traverse* traverse)
6802 return Expression::traverse(&this->expr_, traverse);
6805 // Determine the type of the constant.
6807 void
6808 Named_constant::determine_type()
6810 if (this->type_ != NULL)
6812 Type_context context(this->type_, false);
6813 this->expr_->determine_type(&context);
6815 else
6817 // A constant may have an abstract type.
6818 Type_context context(NULL, true);
6819 this->expr_->determine_type(&context);
6820 this->type_ = this->expr_->type();
6821 go_assert(this->type_ != NULL);
6825 // Indicate that we found and reported an error for this constant.
6827 void
6828 Named_constant::set_error()
6830 this->type_ = Type::make_error_type();
6831 this->expr_ = Expression::make_error(this->location_);
6834 // Export a constant.
6836 void
6837 Named_constant::export_const(Export* exp, const std::string& name) const
6839 exp->write_c_string("const ");
6840 exp->write_string(name);
6841 exp->write_c_string(" ");
6842 if (!this->type_->is_abstract())
6844 exp->write_type(this->type_);
6845 exp->write_c_string(" ");
6847 exp->write_c_string("= ");
6848 this->expr()->export_expression(exp);
6849 exp->write_c_string(";\n");
6852 // Import a constant.
6854 void
6855 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
6856 Expression** pexpr)
6858 imp->require_c_string("const ");
6859 *pname = imp->read_identifier();
6860 imp->require_c_string(" ");
6861 if (imp->peek_char() == '=')
6862 *ptype = NULL;
6863 else
6865 *ptype = imp->read_type();
6866 imp->require_c_string(" ");
6868 imp->require_c_string("= ");
6869 *pexpr = Expression::import_expression(imp);
6870 imp->require_c_string(";\n");
6873 // Get the backend representation.
6875 Bexpression*
6876 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
6878 if (this->bconst_ == NULL)
6880 Translate_context subcontext(gogo, NULL, NULL, NULL);
6881 Type* type = this->type();
6882 Location loc = this->location();
6884 Expression* const_ref = Expression::make_const_reference(const_no, loc);
6885 Bexpression* const_decl = const_ref->get_backend(&subcontext);
6886 if (type != NULL && type->is_numeric_type())
6888 Btype* btype = type->get_backend(gogo);
6889 std::string name = const_no->get_id(gogo);
6890 const_decl =
6891 gogo->backend()->named_constant_expression(btype, name,
6892 const_decl, loc);
6894 this->bconst_ = const_decl;
6896 return this->bconst_;
6899 // Add a method.
6901 Named_object*
6902 Type_declaration::add_method(const std::string& name, Function* function)
6904 Named_object* ret = Named_object::make_function(name, NULL, function);
6905 this->methods_.push_back(ret);
6906 return ret;
6909 // Add a method declaration.
6911 Named_object*
6912 Type_declaration::add_method_declaration(const std::string& name,
6913 Package* package,
6914 Function_type* type,
6915 Location location)
6917 Named_object* ret = Named_object::make_function_declaration(name, package,
6918 type, location);
6919 this->methods_.push_back(ret);
6920 return ret;
6923 // Return whether any methods are defined.
6925 bool
6926 Type_declaration::has_methods() const
6928 return !this->methods_.empty();
6931 // Define methods for the real type.
6933 void
6934 Type_declaration::define_methods(Named_type* nt)
6936 if (this->methods_.empty())
6937 return;
6939 while (nt->is_alias())
6941 Type *t = nt->real_type()->forwarded();
6942 if (t->named_type() != NULL)
6943 nt = t->named_type();
6944 else if (t->forward_declaration_type() != NULL)
6946 Named_object* no = t->forward_declaration_type()->named_object();
6947 Type_declaration* td = no->type_declaration_value();
6948 td->methods_.insert(td->methods_.end(), this->methods_.begin(),
6949 this->methods_.end());
6950 this->methods_.clear();
6951 return;
6953 else
6955 for (std::vector<Named_object*>::const_iterator p =
6956 this->methods_.begin();
6957 p != this->methods_.end();
6958 ++p)
6959 go_error_at((*p)->location(),
6960 ("invalid receiver type "
6961 "(receiver must be a named type"));
6962 return;
6966 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
6967 p != this->methods_.end();
6968 ++p)
6970 if (!(*p)->func_value()->is_sink())
6971 nt->add_existing_method(*p);
6975 // We are using the type. Return true if we should issue a warning.
6977 bool
6978 Type_declaration::using_type()
6980 bool ret = !this->issued_warning_;
6981 this->issued_warning_ = true;
6982 return ret;
6985 // Class Unknown_name.
6987 // Set the real named object.
6989 void
6990 Unknown_name::set_real_named_object(Named_object* no)
6992 go_assert(this->real_named_object_ == NULL);
6993 go_assert(!no->is_unknown());
6994 this->real_named_object_ = no;
6997 // Class Named_object.
6999 Named_object::Named_object(const std::string& name,
7000 const Package* package,
7001 Classification classification)
7002 : name_(name), package_(package), classification_(classification),
7003 is_redefinition_(false)
7005 if (Gogo::is_sink_name(name))
7006 go_assert(classification == NAMED_OBJECT_SINK);
7009 // Make an unknown name. This is used by the parser. The name must
7010 // be resolved later. Unknown names are only added in the current
7011 // package.
7013 Named_object*
7014 Named_object::make_unknown_name(const std::string& name,
7015 Location location)
7017 Named_object* named_object = new Named_object(name, NULL,
7018 NAMED_OBJECT_UNKNOWN);
7019 Unknown_name* value = new Unknown_name(location);
7020 named_object->u_.unknown_value = value;
7021 return named_object;
7024 // Make a constant.
7026 Named_object*
7027 Named_object::make_constant(const Typed_identifier& tid,
7028 const Package* package, Expression* expr,
7029 int iota_value)
7031 Named_object* named_object = new Named_object(tid.name(), package,
7032 NAMED_OBJECT_CONST);
7033 Named_constant* named_constant = new Named_constant(tid.type(), expr,
7034 iota_value,
7035 tid.location());
7036 named_object->u_.const_value = named_constant;
7037 return named_object;
7040 // Make a named type.
7042 Named_object*
7043 Named_object::make_type(const std::string& name, const Package* package,
7044 Type* type, Location location)
7046 Named_object* named_object = new Named_object(name, package,
7047 NAMED_OBJECT_TYPE);
7048 Named_type* named_type = Type::make_named_type(named_object, type, location);
7049 named_object->u_.type_value = named_type;
7050 return named_object;
7053 // Make a type declaration.
7055 Named_object*
7056 Named_object::make_type_declaration(const std::string& name,
7057 const Package* package,
7058 Location location)
7060 Named_object* named_object = new Named_object(name, package,
7061 NAMED_OBJECT_TYPE_DECLARATION);
7062 Type_declaration* type_declaration = new Type_declaration(location);
7063 named_object->u_.type_declaration = type_declaration;
7064 return named_object;
7067 // Make a variable.
7069 Named_object*
7070 Named_object::make_variable(const std::string& name, const Package* package,
7071 Variable* variable)
7073 Named_object* named_object = new Named_object(name, package,
7074 NAMED_OBJECT_VAR);
7075 named_object->u_.var_value = variable;
7076 return named_object;
7079 // Make a result variable.
7081 Named_object*
7082 Named_object::make_result_variable(const std::string& name,
7083 Result_variable* result)
7085 Named_object* named_object = new Named_object(name, NULL,
7086 NAMED_OBJECT_RESULT_VAR);
7087 named_object->u_.result_var_value = result;
7088 return named_object;
7091 // Make a sink. This is used for the special blank identifier _.
7093 Named_object*
7094 Named_object::make_sink()
7096 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
7099 // Make a named function.
7101 Named_object*
7102 Named_object::make_function(const std::string& name, const Package* package,
7103 Function* function)
7105 Named_object* named_object = new Named_object(name, package,
7106 NAMED_OBJECT_FUNC);
7107 named_object->u_.func_value = function;
7108 return named_object;
7111 // Make a function declaration.
7113 Named_object*
7114 Named_object::make_function_declaration(const std::string& name,
7115 const Package* package,
7116 Function_type* fntype,
7117 Location location)
7119 Named_object* named_object = new Named_object(name, package,
7120 NAMED_OBJECT_FUNC_DECLARATION);
7121 Function_declaration *func_decl = new Function_declaration(fntype, location);
7122 named_object->u_.func_declaration_value = func_decl;
7123 return named_object;
7126 // Make a package.
7128 Named_object*
7129 Named_object::make_package(const std::string& alias, Package* package)
7131 Named_object* named_object = new Named_object(alias, NULL,
7132 NAMED_OBJECT_PACKAGE);
7133 named_object->u_.package_value = package;
7134 return named_object;
7137 // Return the name to use in an error message.
7139 std::string
7140 Named_object::message_name() const
7142 if (this->package_ == NULL)
7143 return Gogo::message_name(this->name_);
7144 std::string ret;
7145 if (this->package_->has_package_name())
7146 ret = this->package_->package_name();
7147 else
7148 ret = this->package_->pkgpath();
7149 ret = Gogo::message_name(ret);
7150 ret += '.';
7151 ret += Gogo::message_name(this->name_);
7152 return ret;
7155 // Set the type when a declaration is defined.
7157 void
7158 Named_object::set_type_value(Named_type* named_type)
7160 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
7161 Type_declaration* td = this->u_.type_declaration;
7162 td->define_methods(named_type);
7163 unsigned int index;
7164 Named_object* in_function = td->in_function(&index);
7165 if (in_function != NULL)
7166 named_type->set_in_function(in_function, index);
7167 delete td;
7168 this->classification_ = NAMED_OBJECT_TYPE;
7169 this->u_.type_value = named_type;
7172 // Define a function which was previously declared.
7174 void
7175 Named_object::set_function_value(Function* function)
7177 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
7178 if (this->func_declaration_value()->has_descriptor())
7180 Expression* descriptor =
7181 this->func_declaration_value()->descriptor(NULL, NULL);
7182 function->set_descriptor(descriptor);
7184 this->classification_ = NAMED_OBJECT_FUNC;
7185 // FIXME: We should free the old value.
7186 this->u_.func_value = function;
7189 // Declare an unknown object as a type declaration.
7191 void
7192 Named_object::declare_as_type()
7194 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
7195 Unknown_name* unk = this->u_.unknown_value;
7196 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
7197 this->u_.type_declaration = new Type_declaration(unk->location());
7198 delete unk;
7201 // Return the location of a named object.
7203 Location
7204 Named_object::location() const
7206 switch (this->classification_)
7208 default:
7209 case NAMED_OBJECT_UNINITIALIZED:
7210 go_unreachable();
7212 case NAMED_OBJECT_ERRONEOUS:
7213 return Linemap::unknown_location();
7215 case NAMED_OBJECT_UNKNOWN:
7216 return this->unknown_value()->location();
7218 case NAMED_OBJECT_CONST:
7219 return this->const_value()->location();
7221 case NAMED_OBJECT_TYPE:
7222 return this->type_value()->location();
7224 case NAMED_OBJECT_TYPE_DECLARATION:
7225 return this->type_declaration_value()->location();
7227 case NAMED_OBJECT_VAR:
7228 return this->var_value()->location();
7230 case NAMED_OBJECT_RESULT_VAR:
7231 return this->result_var_value()->location();
7233 case NAMED_OBJECT_SINK:
7234 go_unreachable();
7236 case NAMED_OBJECT_FUNC:
7237 return this->func_value()->location();
7239 case NAMED_OBJECT_FUNC_DECLARATION:
7240 return this->func_declaration_value()->location();
7242 case NAMED_OBJECT_PACKAGE:
7243 return this->package_value()->location();
7247 // Export a named object.
7249 void
7250 Named_object::export_named_object(Export* exp) const
7252 switch (this->classification_)
7254 default:
7255 case NAMED_OBJECT_UNINITIALIZED:
7256 case NAMED_OBJECT_UNKNOWN:
7257 go_unreachable();
7259 case NAMED_OBJECT_ERRONEOUS:
7260 break;
7262 case NAMED_OBJECT_CONST:
7263 this->const_value()->export_const(exp, this->name_);
7264 break;
7266 case NAMED_OBJECT_TYPE:
7267 this->type_value()->export_named_type(exp, this->name_);
7268 break;
7270 case NAMED_OBJECT_TYPE_DECLARATION:
7271 go_error_at(this->type_declaration_value()->location(),
7272 "attempt to export %<%s%> which was declared but not defined",
7273 this->message_name().c_str());
7274 break;
7276 case NAMED_OBJECT_FUNC_DECLARATION:
7277 this->func_declaration_value()->export_func(exp, this->name_);
7278 break;
7280 case NAMED_OBJECT_VAR:
7281 this->var_value()->export_var(exp, this->name_);
7282 break;
7284 case NAMED_OBJECT_RESULT_VAR:
7285 case NAMED_OBJECT_SINK:
7286 go_unreachable();
7288 case NAMED_OBJECT_FUNC:
7289 this->func_value()->export_func(exp, this->name_);
7290 break;
7294 // Convert a variable to the backend representation.
7296 Bvariable*
7297 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
7299 if (this->classification_ == NAMED_OBJECT_VAR)
7300 return this->var_value()->get_backend_variable(gogo, function,
7301 this->package_, this->name_);
7302 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
7303 return this->result_var_value()->get_backend_variable(gogo, function,
7304 this->name_);
7305 else
7306 go_unreachable();
7309 // Return the external identifier for this object.
7311 std::string
7312 Named_object::get_id(Gogo* gogo)
7314 go_assert(!this->is_variable()
7315 && !this->is_result_variable()
7316 && !this->is_type());
7317 std::string decl_name;
7318 if (this->is_function_declaration()
7319 && !this->func_declaration_value()->asm_name().empty())
7320 decl_name = this->func_declaration_value()->asm_name();
7321 else
7323 std::string package_name;
7324 if (this->package_ == NULL)
7325 package_name = gogo->package_name();
7326 else
7327 package_name = this->package_->package_name();
7329 // Note that this will be misleading if this is an unexported
7330 // method generated for an embedded imported type. In that case
7331 // the unexported method should have the package name of the
7332 // package from which it is imported, but we are going to give
7333 // it our package name. Fixing this would require knowing the
7334 // package name, but we only know the package path. It might be
7335 // better to use package paths here anyhow. This doesn't affect
7336 // the assembler code, because we always set that name in
7337 // Function::get_or_make_decl anyhow. FIXME.
7339 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
7341 Function_type* fntype;
7342 if (this->is_function())
7343 fntype = this->func_value()->type();
7344 else if (this->is_function_declaration())
7345 fntype = this->func_declaration_value()->type();
7346 else
7347 fntype = NULL;
7348 if (fntype != NULL && fntype->is_method())
7350 decl_name.push_back('.');
7351 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
7354 return decl_name;
7357 // Get the backend representation for this named object.
7359 void
7360 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
7361 std::vector<Btype*>& type_decls,
7362 std::vector<Bfunction*>& func_decls)
7364 // If this is a definition, avoid trying to get the backend
7365 // representation, as that can crash.
7366 if (this->is_redefinition_)
7368 go_assert(saw_errors());
7369 return;
7372 switch (this->classification_)
7374 case NAMED_OBJECT_CONST:
7375 if (!Gogo::is_erroneous_name(this->name_))
7376 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
7377 break;
7379 case NAMED_OBJECT_TYPE:
7381 Named_type* named_type = this->u_.type_value;
7382 if (!Gogo::is_erroneous_name(this->name_))
7383 type_decls.push_back(named_type->get_backend(gogo));
7385 // We need to produce a type descriptor for every named
7386 // type, and for a pointer to every named type, since
7387 // other files or packages might refer to them. We need
7388 // to do this even for hidden types, because they might
7389 // still be returned by some function. Simply calling the
7390 // type_descriptor method is enough to create the type
7391 // descriptor, even though we don't do anything with it.
7392 if (this->package_ == NULL && !saw_errors())
7394 named_type->
7395 type_descriptor_pointer(gogo, Linemap::predeclared_location());
7396 named_type->gc_symbol_pointer(gogo);
7397 Type* pn = Type::make_pointer_type(named_type);
7398 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
7399 pn->gc_symbol_pointer(gogo);
7402 break;
7404 case NAMED_OBJECT_TYPE_DECLARATION:
7405 go_error_at(Linemap::unknown_location(),
7406 "reference to undefined type %qs",
7407 this->message_name().c_str());
7408 return;
7410 case NAMED_OBJECT_VAR:
7411 case NAMED_OBJECT_RESULT_VAR:
7412 case NAMED_OBJECT_SINK:
7413 go_unreachable();
7415 case NAMED_OBJECT_FUNC:
7417 Function* func = this->u_.func_value;
7418 if (!Gogo::is_erroneous_name(this->name_))
7419 func_decls.push_back(func->get_or_make_decl(gogo, this));
7421 if (func->block() != NULL)
7422 func->build(gogo, this);
7424 break;
7426 case NAMED_OBJECT_ERRONEOUS:
7427 break;
7429 default:
7430 go_unreachable();
7434 // Class Bindings.
7436 Bindings::Bindings(Bindings* enclosing)
7437 : enclosing_(enclosing), named_objects_(), bindings_()
7441 // Clear imports.
7443 void
7444 Bindings::clear_file_scope(Gogo* gogo)
7446 Contour::iterator p = this->bindings_.begin();
7447 while (p != this->bindings_.end())
7449 bool keep;
7450 if (p->second->package() != NULL)
7451 keep = false;
7452 else if (p->second->is_package())
7453 keep = false;
7454 else if (p->second->is_function()
7455 && !p->second->func_value()->type()->is_method()
7456 && Gogo::unpack_hidden_name(p->second->name()) == "init")
7457 keep = false;
7458 else
7459 keep = true;
7461 if (keep)
7462 ++p;
7463 else
7465 gogo->add_file_block_name(p->second->name(), p->second->location());
7466 p = this->bindings_.erase(p);
7471 // Look up a symbol.
7473 Named_object*
7474 Bindings::lookup(const std::string& name) const
7476 Contour::const_iterator p = this->bindings_.find(name);
7477 if (p != this->bindings_.end())
7478 return p->second->resolve();
7479 else if (this->enclosing_ != NULL)
7480 return this->enclosing_->lookup(name);
7481 else
7482 return NULL;
7485 // Look up a symbol locally.
7487 Named_object*
7488 Bindings::lookup_local(const std::string& name) const
7490 Contour::const_iterator p = this->bindings_.find(name);
7491 if (p == this->bindings_.end())
7492 return NULL;
7493 return p->second;
7496 // Remove an object from a set of bindings. This is used for a
7497 // special case in thunks for functions which call recover.
7499 void
7500 Bindings::remove_binding(Named_object* no)
7502 Contour::iterator pb = this->bindings_.find(no->name());
7503 go_assert(pb != this->bindings_.end());
7504 this->bindings_.erase(pb);
7505 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
7506 pn != this->named_objects_.end();
7507 ++pn)
7509 if (*pn == no)
7511 this->named_objects_.erase(pn);
7512 return;
7515 go_unreachable();
7518 // Add a method to the list of objects. This is not added to the
7519 // lookup table. This is so that we have a single list of objects
7520 // declared at the top level, which we walk through when it's time to
7521 // convert to trees.
7523 void
7524 Bindings::add_method(Named_object* method)
7526 this->named_objects_.push_back(method);
7529 // Add a generic Named_object to a Contour.
7531 Named_object*
7532 Bindings::add_named_object_to_contour(Contour* contour,
7533 Named_object* named_object)
7535 go_assert(named_object == named_object->resolve());
7536 const std::string& name(named_object->name());
7537 go_assert(!Gogo::is_sink_name(name));
7539 std::pair<Contour::iterator, bool> ins =
7540 contour->insert(std::make_pair(name, named_object));
7541 if (!ins.second)
7543 // The name was already there.
7544 if (named_object->package() != NULL
7545 && ins.first->second->package() == named_object->package()
7546 && (ins.first->second->classification()
7547 == named_object->classification()))
7549 // This is a second import of the same object.
7550 return ins.first->second;
7552 ins.first->second = this->new_definition(ins.first->second,
7553 named_object);
7554 return ins.first->second;
7556 else
7558 // Don't push declarations on the list. We push them on when
7559 // and if we find the definitions. That way we genericize the
7560 // functions in order.
7561 if (!named_object->is_type_declaration()
7562 && !named_object->is_function_declaration()
7563 && !named_object->is_unknown())
7564 this->named_objects_.push_back(named_object);
7565 return named_object;
7569 // We had an existing named object OLD_OBJECT, and we've seen a new
7570 // one NEW_OBJECT with the same name. FIXME: This does not free the
7571 // new object when we don't need it.
7573 Named_object*
7574 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
7576 if (new_object->is_erroneous() && !old_object->is_erroneous())
7577 return new_object;
7579 std::string reason;
7580 switch (old_object->classification())
7582 default:
7583 case Named_object::NAMED_OBJECT_UNINITIALIZED:
7584 go_unreachable();
7586 case Named_object::NAMED_OBJECT_ERRONEOUS:
7587 return old_object;
7589 case Named_object::NAMED_OBJECT_UNKNOWN:
7591 Named_object* real = old_object->unknown_value()->real_named_object();
7592 if (real != NULL)
7593 return this->new_definition(real, new_object);
7594 go_assert(!new_object->is_unknown());
7595 old_object->unknown_value()->set_real_named_object(new_object);
7596 if (!new_object->is_type_declaration()
7597 && !new_object->is_function_declaration())
7598 this->named_objects_.push_back(new_object);
7599 return new_object;
7602 case Named_object::NAMED_OBJECT_CONST:
7603 break;
7605 case Named_object::NAMED_OBJECT_TYPE:
7606 if (new_object->is_type_declaration())
7607 return old_object;
7608 break;
7610 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7611 if (new_object->is_type_declaration())
7612 return old_object;
7613 if (new_object->is_type())
7615 old_object->set_type_value(new_object->type_value());
7616 new_object->type_value()->set_named_object(old_object);
7617 this->named_objects_.push_back(old_object);
7618 return old_object;
7620 break;
7622 case Named_object::NAMED_OBJECT_VAR:
7623 case Named_object::NAMED_OBJECT_RESULT_VAR:
7624 // We have already given an error in the parser for cases where
7625 // one parameter or result variable redeclares another one.
7626 if ((new_object->is_variable()
7627 && new_object->var_value()->is_parameter())
7628 || new_object->is_result_variable())
7629 return old_object;
7630 break;
7632 case Named_object::NAMED_OBJECT_SINK:
7633 go_unreachable();
7635 case Named_object::NAMED_OBJECT_FUNC:
7636 if (new_object->is_function_declaration())
7638 if (!new_object->func_declaration_value()->asm_name().empty())
7639 go_error_at(Linemap::unknown_location(),
7640 ("sorry, not implemented: "
7641 "__asm__ for function definitions"));
7642 Function_type* old_type = old_object->func_value()->type();
7643 Function_type* new_type =
7644 new_object->func_declaration_value()->type();
7645 if (old_type->is_valid_redeclaration(new_type, &reason))
7646 return old_object;
7648 break;
7650 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7652 if (new_object->is_function())
7654 Function_type* old_type =
7655 old_object->func_declaration_value()->type();
7656 Function_type* new_type = new_object->func_value()->type();
7657 if (old_type->is_valid_redeclaration(new_type, &reason))
7659 if (!old_object->func_declaration_value()->asm_name().empty())
7660 go_error_at(Linemap::unknown_location(),
7661 ("sorry, not implemented: "
7662 "__asm__ for function definitions"));
7663 old_object->set_function_value(new_object->func_value());
7664 this->named_objects_.push_back(old_object);
7665 return old_object;
7669 break;
7671 case Named_object::NAMED_OBJECT_PACKAGE:
7672 break;
7675 std::string n = old_object->message_name();
7676 if (reason.empty())
7677 go_error_at(new_object->location(), "redefinition of %qs", n.c_str());
7678 else
7679 go_error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
7680 reason.c_str());
7681 old_object->set_is_redefinition();
7682 new_object->set_is_redefinition();
7684 go_inform(old_object->location(), "previous definition of %qs was here",
7685 n.c_str());
7687 return old_object;
7690 // Add a named type.
7692 Named_object*
7693 Bindings::add_named_type(Named_type* named_type)
7695 return this->add_named_object(named_type->named_object());
7698 // Add a function.
7700 Named_object*
7701 Bindings::add_function(const std::string& name, const Package* package,
7702 Function* function)
7704 return this->add_named_object(Named_object::make_function(name, package,
7705 function));
7708 // Add a function declaration.
7710 Named_object*
7711 Bindings::add_function_declaration(const std::string& name,
7712 const Package* package,
7713 Function_type* type,
7714 Location location)
7716 Named_object* no = Named_object::make_function_declaration(name, package,
7717 type, location);
7718 return this->add_named_object(no);
7721 // Define a type which was previously declared.
7723 void
7724 Bindings::define_type(Named_object* no, Named_type* type)
7726 no->set_type_value(type);
7727 this->named_objects_.push_back(no);
7730 // Mark all local variables as used. This is used for some types of
7731 // parse error.
7733 void
7734 Bindings::mark_locals_used()
7736 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
7737 p != this->named_objects_.end();
7738 ++p)
7739 if ((*p)->is_variable())
7740 (*p)->var_value()->set_is_used();
7743 // Traverse bindings.
7746 Bindings::traverse(Traverse* traverse, bool is_global)
7748 unsigned int traverse_mask = traverse->traverse_mask();
7750 // We don't use an iterator because we permit the traversal to add
7751 // new global objects.
7752 const unsigned int e_or_t = (Traverse::traverse_expressions
7753 | Traverse::traverse_types);
7754 const unsigned int e_or_t_or_s = (e_or_t
7755 | Traverse::traverse_statements);
7756 for (size_t i = 0; i < this->named_objects_.size(); ++i)
7758 Named_object* p = this->named_objects_[i];
7759 int t = TRAVERSE_CONTINUE;
7760 switch (p->classification())
7762 case Named_object::NAMED_OBJECT_CONST:
7763 if ((traverse_mask & Traverse::traverse_constants) != 0)
7764 t = traverse->constant(p, is_global);
7765 if (t == TRAVERSE_CONTINUE
7766 && (traverse_mask & e_or_t) != 0)
7768 Type* tc = p->const_value()->type();
7769 if (tc != NULL
7770 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
7771 return TRAVERSE_EXIT;
7772 t = p->const_value()->traverse_expression(traverse);
7774 break;
7776 case Named_object::NAMED_OBJECT_VAR:
7777 case Named_object::NAMED_OBJECT_RESULT_VAR:
7778 if ((traverse_mask & Traverse::traverse_variables) != 0)
7779 t = traverse->variable(p);
7780 if (t == TRAVERSE_CONTINUE
7781 && (traverse_mask & e_or_t) != 0)
7783 if (p->is_result_variable()
7784 || p->var_value()->has_type())
7786 Type* tv = (p->is_variable()
7787 ? p->var_value()->type()
7788 : p->result_var_value()->type());
7789 if (tv != NULL
7790 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
7791 return TRAVERSE_EXIT;
7794 if (t == TRAVERSE_CONTINUE
7795 && (traverse_mask & e_or_t_or_s) != 0
7796 && p->is_variable())
7797 t = p->var_value()->traverse_expression(traverse, traverse_mask);
7798 break;
7800 case Named_object::NAMED_OBJECT_FUNC:
7801 if ((traverse_mask & Traverse::traverse_functions) != 0)
7802 t = traverse->function(p);
7804 if (t == TRAVERSE_CONTINUE
7805 && (traverse_mask
7806 & (Traverse::traverse_variables
7807 | Traverse::traverse_constants
7808 | Traverse::traverse_functions
7809 | Traverse::traverse_blocks
7810 | Traverse::traverse_statements
7811 | Traverse::traverse_expressions
7812 | Traverse::traverse_types)) != 0)
7813 t = p->func_value()->traverse(traverse);
7814 break;
7816 case Named_object::NAMED_OBJECT_PACKAGE:
7817 // These are traversed in Gogo::traverse.
7818 go_assert(is_global);
7819 break;
7821 case Named_object::NAMED_OBJECT_TYPE:
7822 if ((traverse_mask & e_or_t) != 0)
7823 t = Type::traverse(p->type_value(), traverse);
7824 break;
7826 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7827 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7828 case Named_object::NAMED_OBJECT_UNKNOWN:
7829 case Named_object::NAMED_OBJECT_ERRONEOUS:
7830 break;
7832 case Named_object::NAMED_OBJECT_SINK:
7833 default:
7834 go_unreachable();
7837 if (t == TRAVERSE_EXIT)
7838 return TRAVERSE_EXIT;
7841 // If we need to traverse types, check the function declarations,
7842 // which have types. Also check any methods of a type declaration.
7843 if ((traverse_mask & e_or_t) != 0)
7845 for (Bindings::const_declarations_iterator p =
7846 this->begin_declarations();
7847 p != this->end_declarations();
7848 ++p)
7850 if (p->second->is_function_declaration())
7852 if (Type::traverse(p->second->func_declaration_value()->type(),
7853 traverse)
7854 == TRAVERSE_EXIT)
7855 return TRAVERSE_EXIT;
7857 else if (p->second->is_type_declaration())
7859 const std::vector<Named_object*>* methods =
7860 p->second->type_declaration_value()->methods();
7861 for (std::vector<Named_object*>::const_iterator pm =
7862 methods->begin();
7863 pm != methods->end();
7864 pm++)
7866 Named_object* no = *pm;
7867 Type *t;
7868 if (no->is_function())
7869 t = no->func_value()->type();
7870 else if (no->is_function_declaration())
7871 t = no->func_declaration_value()->type();
7872 else
7873 continue;
7874 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
7875 return TRAVERSE_EXIT;
7881 return TRAVERSE_CONTINUE;
7884 // Class Label.
7886 // Clear any references to this label.
7888 void
7889 Label::clear_refs()
7891 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
7892 p != this->refs_.end();
7893 ++p)
7894 delete *p;
7895 this->refs_.clear();
7898 // Get the backend representation for a label.
7900 Blabel*
7901 Label::get_backend_label(Translate_context* context)
7903 if (this->blabel_ == NULL)
7905 Function* function = context->function()->func_value();
7906 Bfunction* bfunction = function->get_decl();
7907 this->blabel_ = context->backend()->label(bfunction, this->name_,
7908 this->location_);
7910 return this->blabel_;
7913 // Return an expression for the address of this label.
7915 Bexpression*
7916 Label::get_addr(Translate_context* context, Location location)
7918 Blabel* label = this->get_backend_label(context);
7919 return context->backend()->label_address(label, location);
7922 // Return the dummy label that represents any instance of the blank label.
7924 Label*
7925 Label::create_dummy_label()
7927 static Label* dummy_label;
7928 if (dummy_label == NULL)
7930 dummy_label = new Label("_");
7931 dummy_label->set_is_used();
7933 return dummy_label;
7936 // Class Unnamed_label.
7938 // Get the backend representation for an unnamed label.
7940 Blabel*
7941 Unnamed_label::get_blabel(Translate_context* context)
7943 if (this->blabel_ == NULL)
7945 Function* function = context->function()->func_value();
7946 Bfunction* bfunction = function->get_decl();
7947 this->blabel_ = context->backend()->label(bfunction, "",
7948 this->location_);
7950 return this->blabel_;
7953 // Return a statement which defines this unnamed label.
7955 Bstatement*
7956 Unnamed_label::get_definition(Translate_context* context)
7958 Blabel* blabel = this->get_blabel(context);
7959 return context->backend()->label_definition_statement(blabel);
7962 // Return a goto statement to this unnamed label.
7964 Bstatement*
7965 Unnamed_label::get_goto(Translate_context* context, Location location)
7967 Blabel* blabel = this->get_blabel(context);
7968 return context->backend()->goto_statement(blabel, location);
7971 // Class Package.
7973 Package::Package(const std::string& pkgpath,
7974 const std::string& pkgpath_symbol, Location location)
7975 : pkgpath_(pkgpath), pkgpath_symbol_(pkgpath_symbol),
7976 package_name_(), bindings_(new Bindings(NULL)),
7977 location_(location)
7979 go_assert(!pkgpath.empty());
7982 // Set the package name.
7984 void
7985 Package::set_package_name(const std::string& package_name, Location location)
7987 go_assert(!package_name.empty());
7988 if (this->package_name_.empty())
7989 this->package_name_ = package_name;
7990 else if (this->package_name_ != package_name)
7991 go_error_at(location,
7992 ("saw two different packages with "
7993 "the same package path %s: %s, %s"),
7994 this->pkgpath_.c_str(), this->package_name_.c_str(),
7995 package_name.c_str());
7998 // Return the pkgpath symbol, which is a prefix for symbols defined in
7999 // this package.
8001 std::string
8002 Package::pkgpath_symbol() const
8004 if (this->pkgpath_symbol_.empty())
8005 return Gogo::pkgpath_for_symbol(this->pkgpath_);
8006 return this->pkgpath_symbol_;
8009 // Set the package path symbol.
8011 void
8012 Package::set_pkgpath_symbol(const std::string& pkgpath_symbol)
8014 go_assert(!pkgpath_symbol.empty());
8015 if (this->pkgpath_symbol_.empty())
8016 this->pkgpath_symbol_ = pkgpath_symbol;
8017 else
8018 go_assert(this->pkgpath_symbol_ == pkgpath_symbol);
8021 // Note that symbol from this package was and qualified by ALIAS.
8023 void
8024 Package::note_usage(const std::string& alias) const
8026 Aliases::const_iterator p = this->aliases_.find(alias);
8027 go_assert(p != this->aliases_.end());
8028 p->second->note_usage();
8031 // Forget a given usage. If forgetting this usage means this package becomes
8032 // unused, report that error.
8034 void
8035 Package::forget_usage(Expression* usage) const
8037 if (this->fake_uses_.empty())
8038 return;
8040 std::set<Expression*>::iterator p = this->fake_uses_.find(usage);
8041 go_assert(p != this->fake_uses_.end());
8042 this->fake_uses_.erase(p);
8044 if (this->fake_uses_.empty())
8045 go_error_at(this->location(), "imported and not used: %s",
8046 Gogo::message_name(this->package_name()).c_str());
8049 // Clear the used field for the next file. If the only usages of this package
8050 // are possibly fake, keep the fake usages for lowering.
8052 void
8053 Package::clear_used()
8055 std::string dot_alias = "." + this->package_name();
8056 Aliases::const_iterator p = this->aliases_.find(dot_alias);
8057 if (p != this->aliases_.end() && p->second->used() > this->fake_uses_.size())
8058 this->fake_uses_.clear();
8060 this->aliases_.clear();
8063 Package_alias*
8064 Package::add_alias(const std::string& alias, Location location)
8066 Aliases::const_iterator p = this->aliases_.find(alias);
8067 if (p == this->aliases_.end())
8069 std::pair<Aliases::iterator, bool> ret;
8070 ret = this->aliases_.insert(std::make_pair(alias,
8071 new Package_alias(location)));
8072 p = ret.first;
8074 return p->second;
8077 // Determine types of constants. Everything else in a package
8078 // (variables, function declarations) should already have a fixed
8079 // type. Constants may have abstract types.
8081 void
8082 Package::determine_types()
8084 Bindings* bindings = this->bindings_;
8085 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
8086 p != bindings->end_definitions();
8087 ++p)
8089 if ((*p)->is_const())
8090 (*p)->const_value()->determine_type();
8094 // Class Traverse.
8096 // Destructor.
8098 Traverse::~Traverse()
8100 if (this->types_seen_ != NULL)
8101 delete this->types_seen_;
8102 if (this->expressions_seen_ != NULL)
8103 delete this->expressions_seen_;
8106 // Record that we are looking at a type, and return true if we have
8107 // already seen it.
8109 bool
8110 Traverse::remember_type(const Type* type)
8112 if (type->is_error_type())
8113 return true;
8114 go_assert((this->traverse_mask() & traverse_types) != 0
8115 || (this->traverse_mask() & traverse_expressions) != 0);
8116 // We mostly only have to remember named types. But it turns out
8117 // that an interface type can refer to itself without using a name
8118 // by relying on interface inheritance, as in
8119 // type I interface { F() interface{I} }
8120 if (type->classification() != Type::TYPE_NAMED
8121 && type->classification() != Type::TYPE_INTERFACE)
8122 return false;
8123 if (this->types_seen_ == NULL)
8124 this->types_seen_ = new Types_seen();
8125 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
8126 return !ins.second;
8129 // Record that we are looking at an expression, and return true if we
8130 // have already seen it. NB: this routine used to assert if the traverse
8131 // mask did not include expressions/types -- this is no longer the case,
8132 // since it can be useful to remember specific expressions during
8133 // walks that only cover statements.
8135 bool
8136 Traverse::remember_expression(const Expression* expression)
8138 if (this->expressions_seen_ == NULL)
8139 this->expressions_seen_ = new Expressions_seen();
8140 std::pair<Expressions_seen::iterator, bool> ins =
8141 this->expressions_seen_->insert(expression);
8142 return !ins.second;
8145 // The default versions of these functions should never be called: the
8146 // traversal mask indicates which functions may be called.
8149 Traverse::variable(Named_object*)
8151 go_unreachable();
8155 Traverse::constant(Named_object*, bool)
8157 go_unreachable();
8161 Traverse::function(Named_object*)
8163 go_unreachable();
8167 Traverse::block(Block*)
8169 go_unreachable();
8173 Traverse::statement(Block*, size_t*, Statement*)
8175 go_unreachable();
8179 Traverse::expression(Expression**)
8181 go_unreachable();
8185 Traverse::type(Type*)
8187 go_unreachable();
8190 // Class Statement_inserter.
8192 void
8193 Statement_inserter::insert(Statement* s)
8195 if (this->block_ != NULL)
8197 go_assert(this->pindex_ != NULL);
8198 this->block_->insert_statement_before(*this->pindex_, s);
8199 ++*this->pindex_;
8201 else if (this->var_ != NULL)
8202 this->var_->add_preinit_statement(this->gogo_, s);
8203 else
8204 go_assert(saw_errors());