Rebase.
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blob623befd1027960c52031dd67ed4e9b1fbfa90663
1 // gogo.cc -- Go frontend parsed representation.
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 #include "go-system.h"
9 #include "filenames.h"
11 #include "go-c.h"
12 #include "go-dump.h"
13 #include "lex.h"
14 #include "types.h"
15 #include "statements.h"
16 #include "expressions.h"
17 #include "dataflow.h"
18 #include "runtime.h"
19 #include "import.h"
20 #include "export.h"
21 #include "backend.h"
22 #include "gogo.h"
24 // Class Gogo.
26 Gogo::Gogo(Backend* backend, Linemap* linemap, int, int pointer_size)
27 : backend_(backend),
28 linemap_(linemap),
29 package_(NULL),
30 functions_(),
31 globals_(new Bindings(NULL)),
32 file_block_names_(),
33 imports_(),
34 imported_unsafe_(false),
35 packages_(),
36 init_functions_(),
37 var_deps_(),
38 need_init_fn_(false),
39 init_fn_name_(),
40 imported_init_fns_(),
41 pkgpath_(),
42 pkgpath_symbol_(),
43 prefix_(),
44 zero_value_(NULL),
45 zero_value_size_(0),
46 zero_value_align_(0),
47 pkgpath_set_(false),
48 pkgpath_from_option_(false),
49 prefix_from_option_(false),
50 relative_import_path_(),
51 verify_types_(),
52 interface_types_(),
53 specific_type_functions_(),
54 specific_type_functions_are_written_(false),
55 named_types_are_converted_(false)
57 const Location loc = Linemap::predeclared_location();
59 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
60 RUNTIME_TYPE_KIND_UINT8);
61 this->add_named_type(uint8_type);
62 this->add_named_type(Type::make_integer_type("uint16", true, 16,
63 RUNTIME_TYPE_KIND_UINT16));
64 this->add_named_type(Type::make_integer_type("uint32", true, 32,
65 RUNTIME_TYPE_KIND_UINT32));
66 this->add_named_type(Type::make_integer_type("uint64", true, 64,
67 RUNTIME_TYPE_KIND_UINT64));
69 this->add_named_type(Type::make_integer_type("int8", false, 8,
70 RUNTIME_TYPE_KIND_INT8));
71 this->add_named_type(Type::make_integer_type("int16", false, 16,
72 RUNTIME_TYPE_KIND_INT16));
73 Named_type* int32_type = Type::make_integer_type("int32", false, 32,
74 RUNTIME_TYPE_KIND_INT32);
75 this->add_named_type(int32_type);
76 this->add_named_type(Type::make_integer_type("int64", false, 64,
77 RUNTIME_TYPE_KIND_INT64));
79 this->add_named_type(Type::make_float_type("float32", 32,
80 RUNTIME_TYPE_KIND_FLOAT32));
81 this->add_named_type(Type::make_float_type("float64", 64,
82 RUNTIME_TYPE_KIND_FLOAT64));
84 this->add_named_type(Type::make_complex_type("complex64", 64,
85 RUNTIME_TYPE_KIND_COMPLEX64));
86 this->add_named_type(Type::make_complex_type("complex128", 128,
87 RUNTIME_TYPE_KIND_COMPLEX128));
89 int int_type_size = pointer_size;
90 if (int_type_size < 32)
91 int_type_size = 32;
92 this->add_named_type(Type::make_integer_type("uint", true,
93 int_type_size,
94 RUNTIME_TYPE_KIND_UINT));
95 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
96 RUNTIME_TYPE_KIND_INT);
97 this->add_named_type(int_type);
99 this->add_named_type(Type::make_integer_type("uintptr", true,
100 pointer_size,
101 RUNTIME_TYPE_KIND_UINTPTR));
103 // "byte" is an alias for "uint8".
104 uint8_type->integer_type()->set_is_byte();
105 Named_object* byte_type = Named_object::make_type("byte", NULL, uint8_type,
106 loc);
107 this->add_named_type(byte_type->type_value());
109 // "rune" is an alias for "int32".
110 int32_type->integer_type()->set_is_rune();
111 Named_object* rune_type = Named_object::make_type("rune", NULL, int32_type,
112 loc);
113 this->add_named_type(rune_type->type_value());
115 this->add_named_type(Type::make_named_bool_type());
117 this->add_named_type(Type::make_named_string_type());
119 // "error" is interface { Error() string }.
121 Typed_identifier_list *methods = new Typed_identifier_list;
122 Typed_identifier_list *results = new Typed_identifier_list;
123 results->push_back(Typed_identifier("", Type::lookup_string_type(), loc));
124 Type *method_type = Type::make_function_type(NULL, NULL, results, loc);
125 methods->push_back(Typed_identifier("Error", method_type, loc));
126 Interface_type *error_iface = Type::make_interface_type(methods, loc);
127 error_iface->finalize_methods();
128 Named_type *error_type = Named_object::make_type("error", NULL, error_iface, loc)->type_value();
129 this->add_named_type(error_type);
132 this->globals_->add_constant(Typed_identifier("true",
133 Type::make_boolean_type(),
134 loc),
135 NULL,
136 Expression::make_boolean(true, loc),
138 this->globals_->add_constant(Typed_identifier("false",
139 Type::make_boolean_type(),
140 loc),
141 NULL,
142 Expression::make_boolean(false, loc),
145 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
146 loc),
147 NULL,
148 Expression::make_nil(loc),
151 Type* abstract_int_type = Type::make_abstract_integer_type();
152 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
153 loc),
154 NULL,
155 Expression::make_iota(),
158 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
159 new_type->set_is_varargs();
160 new_type->set_is_builtin();
161 this->globals_->add_function_declaration("new", NULL, new_type, loc);
163 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
164 make_type->set_is_varargs();
165 make_type->set_is_builtin();
166 this->globals_->add_function_declaration("make", NULL, make_type, loc);
168 Typed_identifier_list* len_result = new Typed_identifier_list();
169 len_result->push_back(Typed_identifier("", int_type, loc));
170 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
171 loc);
172 len_type->set_is_builtin();
173 this->globals_->add_function_declaration("len", NULL, len_type, loc);
175 Typed_identifier_list* cap_result = new Typed_identifier_list();
176 cap_result->push_back(Typed_identifier("", int_type, loc));
177 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
178 loc);
179 cap_type->set_is_builtin();
180 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
182 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
183 print_type->set_is_varargs();
184 print_type->set_is_builtin();
185 this->globals_->add_function_declaration("print", NULL, print_type, loc);
187 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
188 print_type->set_is_varargs();
189 print_type->set_is_builtin();
190 this->globals_->add_function_declaration("println", NULL, print_type, loc);
192 Type *empty = Type::make_empty_interface_type(loc);
193 Typed_identifier_list* panic_parms = new Typed_identifier_list();
194 panic_parms->push_back(Typed_identifier("e", empty, loc));
195 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
196 NULL, loc);
197 panic_type->set_is_builtin();
198 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
200 Typed_identifier_list* recover_result = new Typed_identifier_list();
201 recover_result->push_back(Typed_identifier("", empty, loc));
202 Function_type* recover_type = Type::make_function_type(NULL, NULL,
203 recover_result,
204 loc);
205 recover_type->set_is_builtin();
206 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
208 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
209 close_type->set_is_varargs();
210 close_type->set_is_builtin();
211 this->globals_->add_function_declaration("close", NULL, close_type, loc);
213 Typed_identifier_list* copy_result = new Typed_identifier_list();
214 copy_result->push_back(Typed_identifier("", int_type, loc));
215 Function_type* copy_type = Type::make_function_type(NULL, NULL,
216 copy_result, loc);
217 copy_type->set_is_varargs();
218 copy_type->set_is_builtin();
219 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
221 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
222 append_type->set_is_varargs();
223 append_type->set_is_builtin();
224 this->globals_->add_function_declaration("append", NULL, append_type, loc);
226 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
227 complex_type->set_is_varargs();
228 complex_type->set_is_builtin();
229 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
231 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
232 real_type->set_is_varargs();
233 real_type->set_is_builtin();
234 this->globals_->add_function_declaration("real", NULL, real_type, loc);
236 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
237 imag_type->set_is_varargs();
238 imag_type->set_is_builtin();
239 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
241 Function_type* delete_type = Type::make_function_type(NULL, NULL, NULL, loc);
242 delete_type->set_is_varargs();
243 delete_type->set_is_builtin();
244 this->globals_->add_function_declaration("delete", NULL, delete_type, loc);
247 // Convert a pkgpath into a string suitable for a symbol. Note that
248 // this transformation is convenient but imperfect. A -fgo-pkgpath
249 // option of a/b_c will conflict with a -fgo-pkgpath option of a_b/c,
250 // possibly leading to link time errors.
252 std::string
253 Gogo::pkgpath_for_symbol(const std::string& pkgpath)
255 std::string s = pkgpath;
256 for (size_t i = 0; i < s.length(); ++i)
258 char c = s[i];
259 if ((c >= 'a' && c <= 'z')
260 || (c >= 'A' && c <= 'Z')
261 || (c >= '0' && c <= '9')
262 || c == '_'
263 || c == '.'
264 || c == '$')
266 else
267 s[i] = '_';
269 return s;
272 // Get the package path to use for type reflection data. This should
273 // ideally be unique across the entire link.
275 const std::string&
276 Gogo::pkgpath() const
278 go_assert(this->pkgpath_set_);
279 return this->pkgpath_;
282 // Set the package path from the -fgo-pkgpath command line option.
284 void
285 Gogo::set_pkgpath(const std::string& arg)
287 go_assert(!this->pkgpath_set_);
288 this->pkgpath_ = arg;
289 this->pkgpath_set_ = true;
290 this->pkgpath_from_option_ = true;
293 // Get the package path to use for symbol names.
295 const std::string&
296 Gogo::pkgpath_symbol() const
298 go_assert(this->pkgpath_set_);
299 return this->pkgpath_symbol_;
302 // Set the unique prefix to use to determine the package path, from
303 // the -fgo-prefix command line option.
305 void
306 Gogo::set_prefix(const std::string& arg)
308 go_assert(!this->prefix_from_option_);
309 this->prefix_ = arg;
310 this->prefix_from_option_ = true;
313 // Munge name for use in an error message.
315 std::string
316 Gogo::message_name(const std::string& name)
318 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
321 // Get the package name.
323 const std::string&
324 Gogo::package_name() const
326 go_assert(this->package_ != NULL);
327 return this->package_->package_name();
330 // Set the package name.
332 void
333 Gogo::set_package_name(const std::string& package_name,
334 Location location)
336 if (this->package_ != NULL)
338 if (this->package_->package_name() != package_name)
339 error_at(location, "expected package %<%s%>",
340 Gogo::message_name(this->package_->package_name()).c_str());
341 return;
344 // Now that we know the name of the package we are compiling, set
345 // the package path to use for reflect.Type.PkgPath and global
346 // symbol names.
347 if (!this->pkgpath_set_)
349 if (!this->prefix_from_option_ && package_name == "main")
350 this->pkgpath_ = package_name;
351 else
353 if (!this->prefix_from_option_)
354 this->prefix_ = "go";
355 this->pkgpath_ = this->prefix_ + '.' + package_name;
357 this->pkgpath_set_ = true;
360 this->pkgpath_symbol_ = Gogo::pkgpath_for_symbol(this->pkgpath_);
362 this->package_ = this->register_package(this->pkgpath_, location);
363 this->package_->set_package_name(package_name, location);
365 if (this->is_main_package())
367 // Declare "main" as a function which takes no parameters and
368 // returns no value.
369 Location uloc = Linemap::unknown_location();
370 this->declare_function(Gogo::pack_hidden_name("main", false),
371 Type::make_function_type (NULL, NULL, NULL, uloc),
372 uloc);
376 // Return whether this is the "main" package. This is not true if
377 // -fgo-pkgpath or -fgo-prefix was used.
379 bool
380 Gogo::is_main_package() const
382 return (this->package_name() == "main"
383 && !this->pkgpath_from_option_
384 && !this->prefix_from_option_);
387 // Import a package.
389 void
390 Gogo::import_package(const std::string& filename,
391 const std::string& local_name,
392 bool is_local_name_exported,
393 Location location)
395 if (filename.empty())
397 error_at(location, "import path is empty");
398 return;
401 const char *pf = filename.data();
402 const char *pend = pf + filename.length();
403 while (pf < pend)
405 unsigned int c;
406 int adv = Lex::fetch_char(pf, &c);
407 if (adv == 0)
409 error_at(location, "import path contains invalid UTF-8 sequence");
410 return;
412 if (c == '\0')
414 error_at(location, "import path contains NUL");
415 return;
417 if (c < 0x20 || c == 0x7f)
419 error_at(location, "import path contains control character");
420 return;
422 if (c == '\\')
424 error_at(location, "import path contains backslash; use slash");
425 return;
427 if (Lex::is_unicode_space(c))
429 error_at(location, "import path contains space character");
430 return;
432 if (c < 0x7f && strchr("!\"#$%&'()*,:;<=>?[]^`{|}", c) != NULL)
434 error_at(location, "import path contains invalid character '%c'", c);
435 return;
437 pf += adv;
440 if (IS_ABSOLUTE_PATH(filename.c_str()))
442 error_at(location, "import path cannot be absolute path");
443 return;
446 if (local_name == "init")
447 error_at(location, "cannot import package as init");
449 if (filename == "unsafe")
451 this->import_unsafe(local_name, is_local_name_exported, location);
452 return;
455 Imports::const_iterator p = this->imports_.find(filename);
456 if (p != this->imports_.end())
458 Package* package = p->second;
459 package->set_location(location);
460 package->set_is_imported();
461 std::string ln = local_name;
462 bool is_ln_exported = is_local_name_exported;
463 if (ln.empty())
465 ln = package->package_name();
466 go_assert(!ln.empty());
467 is_ln_exported = Lex::is_exported_name(ln);
469 if (ln == ".")
471 Bindings* bindings = package->bindings();
472 for (Bindings::const_declarations_iterator p =
473 bindings->begin_declarations();
474 p != bindings->end_declarations();
475 ++p)
476 this->add_dot_import_object(p->second);
478 else if (ln == "_")
479 package->set_uses_sink_alias();
480 else
482 ln = this->pack_hidden_name(ln, is_ln_exported);
483 this->package_->bindings()->add_package(ln, package);
485 return;
488 Import::Stream* stream = Import::open_package(filename, location,
489 this->relative_import_path_);
490 if (stream == NULL)
492 error_at(location, "import file %qs not found", filename.c_str());
493 return;
496 Import imp(stream, location);
497 imp.register_builtin_types(this);
498 Package* package = imp.import(this, local_name, is_local_name_exported);
499 if (package != NULL)
501 if (package->pkgpath() == this->pkgpath())
502 error_at(location,
503 ("imported package uses same package path as package "
504 "being compiled (see -fgo-pkgpath option)"));
506 this->imports_.insert(std::make_pair(filename, package));
507 package->set_is_imported();
510 delete stream;
513 // Add an import control function for an imported package to the list.
515 void
516 Gogo::add_import_init_fn(const std::string& package_name,
517 const std::string& init_name, int prio)
519 for (std::set<Import_init>::const_iterator p =
520 this->imported_init_fns_.begin();
521 p != this->imported_init_fns_.end();
522 ++p)
524 if (p->init_name() == init_name)
526 // If a test of package P1, built as part of package P1,
527 // imports package P2, and P2 imports P1 (perhaps
528 // indirectly), then we will see the same import name with
529 // different import priorities. That is OK, so don't give
530 // an error about it.
531 if (p->package_name() != package_name)
533 error("duplicate package initialization name %qs",
534 Gogo::message_name(init_name).c_str());
535 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
536 Gogo::message_name(p->package_name()).c_str(),
537 p->priority());
538 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
539 Gogo::message_name(package_name).c_str(), prio);
541 return;
545 this->imported_init_fns_.insert(Import_init(package_name, init_name,
546 prio));
549 // Return whether we are at the global binding level.
551 bool
552 Gogo::in_global_scope() const
554 return this->functions_.empty();
557 // Return the current binding contour.
559 Bindings*
560 Gogo::current_bindings()
562 if (!this->functions_.empty())
563 return this->functions_.back().blocks.back()->bindings();
564 else if (this->package_ != NULL)
565 return this->package_->bindings();
566 else
567 return this->globals_;
570 const Bindings*
571 Gogo::current_bindings() const
573 if (!this->functions_.empty())
574 return this->functions_.back().blocks.back()->bindings();
575 else if (this->package_ != NULL)
576 return this->package_->bindings();
577 else
578 return this->globals_;
581 // Return the special variable used as the zero value of types.
583 Named_object*
584 Gogo::zero_value(Type *type)
586 if (this->zero_value_ == NULL)
588 Location bloc = Linemap::predeclared_location();
590 // We will change the type later, when we know the size.
591 Type* byte_type = this->lookup_global("byte")->type_value();
593 mpz_t val;
594 mpz_init_set_ui(val, 0);
595 Expression* zero = Expression::make_integer(&val, NULL, bloc);
596 mpz_clear(val);
598 Type* array_type = Type::make_array_type(byte_type, zero);
600 Variable* var = new Variable(array_type, NULL, true, false, false, bloc);
601 this->zero_value_ = Named_object::make_variable("go$zerovalue", NULL,
602 var);
605 // The zero value will be the maximum required size.
606 unsigned long size;
607 bool ok = type->backend_type_size(this, &size);
608 if (!ok) {
609 go_assert(saw_errors());
610 size = 4;
612 if (size > this->zero_value_size_)
613 this->zero_value_size_ = size;
615 unsigned long align;
616 ok = type->backend_type_align(this, &align);
617 if (!ok) {
618 go_assert(saw_errors());
619 align = 4;
621 if (align > this->zero_value_align_)
622 this->zero_value_align_ = align;
624 return this->zero_value_;
627 // Return whether V is the zero value variable.
629 bool
630 Gogo::is_zero_value(Variable* v) const
632 return this->zero_value_ != NULL && this->zero_value_->var_value() == v;
635 // Return the backend variable for the special zero value, or NULL if
636 // it is not needed.
638 Bvariable*
639 Gogo::backend_zero_value()
641 if (this->zero_value_ == NULL)
642 return NULL;
644 Type* byte_type = this->lookup_global("byte")->type_value();
645 Btype* bbtype_type = byte_type->get_backend(this);
647 Type* int_type = this->lookup_global("int")->type_value();
648 Btype* bint_type = int_type->get_backend(this);
650 mpz_t val;
651 mpz_init_set_ui(val, this->zero_value_size_);
652 Bexpression* blength =
653 this->backend()->integer_constant_expression(bint_type, val);
654 mpz_clear(val);
656 Btype* barray_type = this->backend()->array_type(bbtype_type, blength);
658 return this->backend()->implicit_variable(this->zero_value_->name(),
659 barray_type, NULL, true, true,
660 this->zero_value_align_);
663 // Add statements to INIT_STMTS which run the initialization
664 // functions for imported packages. This is only used for the "main"
665 // package.
667 void
668 Gogo::init_imports(std::vector<Bstatement*>& init_stmts)
670 go_assert(this->is_main_package());
672 if (this->imported_init_fns_.empty())
673 return;
675 Location unknown_loc = Linemap::unknown_location();
676 Function_type* func_type =
677 Type::make_function_type(NULL, NULL, NULL, unknown_loc);
678 Btype* fntype = func_type->get_backend_fntype(this);
680 // We must call them in increasing priority order.
681 std::vector<Import_init> v;
682 for (std::set<Import_init>::const_iterator p =
683 this->imported_init_fns_.begin();
684 p != this->imported_init_fns_.end();
685 ++p)
686 v.push_back(*p);
687 std::sort(v.begin(), v.end());
689 // We build calls to the init functions, which take no arguments.
690 std::vector<Bexpression*> empty_args;
691 for (std::vector<Import_init>::const_iterator p = v.begin();
692 p != v.end();
693 ++p)
695 std::string user_name = p->package_name() + ".init";
696 const std::string& init_name(p->init_name());
698 Bfunction* pfunc = this->backend()->function(fntype, user_name, init_name,
699 true, true, true, false,
700 false, unknown_loc);
701 Bexpression* pfunc_code =
702 this->backend()->function_code_expression(pfunc, unknown_loc);
703 Bexpression* pfunc_call =
704 this->backend()->call_expression(pfunc_code, empty_args, unknown_loc);
705 init_stmts.push_back(this->backend()->expression_statement(pfunc_call));
709 // Register global variables with the garbage collector. We need to
710 // register all variables which can hold a pointer value. They become
711 // roots during the mark phase. We build a struct that is easy to
712 // hook into a list of roots.
714 // struct __go_gc_root_list
715 // {
716 // struct __go_gc_root_list* __next;
717 // struct __go_gc_root
718 // {
719 // void* __decl;
720 // size_t __size;
721 // } __roots[];
722 // };
724 // The last entry in the roots array has a NULL decl field.
726 void
727 Gogo::register_gc_vars(const std::vector<Named_object*>& var_gc,
728 std::vector<Bstatement*>& init_stmts)
730 if (var_gc.empty())
731 return;
733 Type* pvt = Type::make_pointer_type(Type::make_void_type());
734 Type* uint_type = Type::lookup_integer_type("uint");
735 Struct_type* root_type = Type::make_builtin_struct_type(2,
736 "__decl", pvt,
737 "__size", uint_type);
739 Location builtin_loc = Linemap::predeclared_location();
740 size_t count = var_gc.size();
741 mpz_t lenval;
742 mpz_init_set_ui(lenval, count);
743 Expression* length = Expression::make_integer(&lenval, NULL, builtin_loc);
744 mpz_clear(lenval);
746 Array_type* root_array_type = Type::make_array_type(root_type, length);
747 Type* ptdt = Type::make_type_descriptor_ptr_type();
748 Struct_type* root_list_type =
749 Type::make_builtin_struct_type(2,
750 "__next", ptdt,
751 "__roots", root_array_type);
753 // Build an initializer for the __roots array.
755 Expression_list* roots_init = new Expression_list();
757 size_t i = 0;
758 for (std::vector<Named_object*>::const_iterator p = var_gc.begin();
759 p != var_gc.end();
760 ++p, ++i)
762 Expression_list* init = new Expression_list();
764 Location no_loc = (*p)->location();
765 Expression* decl = Expression::make_var_reference(*p, no_loc);
766 Expression* decl_addr =
767 Expression::make_unary(OPERATOR_AND, decl, no_loc);
768 init->push_back(decl_addr);
770 Expression* decl_size =
771 Expression::make_type_info(decl->type(), Expression::TYPE_INFO_SIZE);
772 init->push_back(decl_size);
774 Expression* root_ctor =
775 Expression::make_struct_composite_literal(root_type, init, no_loc);
776 roots_init->push_back(root_ctor);
779 // The list ends with a NULL entry.
781 Expression_list* null_init = new Expression_list();
782 Expression* nil = Expression::make_nil(builtin_loc);
783 null_init->push_back(nil);
785 mpz_t zval;
786 mpz_init_set_ui(zval, 0UL);
787 Expression* zero = Expression::make_integer(&zval, NULL, builtin_loc);
788 mpz_clear(zval);
789 null_init->push_back(zero);
791 Expression* null_root_ctor =
792 Expression::make_struct_composite_literal(root_type, null_init,
793 builtin_loc);
794 roots_init->push_back(null_root_ctor);
796 // Build a constructor for the struct.
798 Expression_list* root_list_init = new Expression_list();
799 root_list_init->push_back(nil);
801 Expression* roots_ctor =
802 Expression::make_array_composite_literal(root_array_type, roots_init,
803 builtin_loc);
804 root_list_init->push_back(roots_ctor);
806 Expression* root_list_ctor =
807 Expression::make_struct_composite_literal(root_list_type, root_list_init,
808 builtin_loc);
810 Expression* root_addr = Expression::make_unary(OPERATOR_AND, root_list_ctor,
811 builtin_loc);
812 root_addr->unary_expression()->set_is_gc_root();
813 Expression* register_roots = Runtime::make_call(Runtime::REGISTER_GC_ROOTS,
814 builtin_loc, 1, root_addr);
816 Translate_context context(this, NULL, NULL, NULL);
817 Bexpression* bcall = register_roots->get_backend(&context);
818 init_stmts.push_back(this->backend()->expression_statement(bcall));
821 // Get the name to use for the import control function. If there is a
822 // global function or variable, then we know that that name must be
823 // unique in the link, and we use it as the basis for our name.
825 const std::string&
826 Gogo::get_init_fn_name()
828 if (this->init_fn_name_.empty())
830 go_assert(this->package_ != NULL);
831 if (this->is_main_package())
833 // Use a name which the runtime knows.
834 this->init_fn_name_ = "__go_init_main";
836 else
838 std::string s = this->pkgpath_symbol();
839 s.append("..import");
840 this->init_fn_name_ = s;
844 return this->init_fn_name_;
847 // Build the decl for the initialization function.
849 Named_object*
850 Gogo::initialization_function_decl()
852 std::string name = this->get_init_fn_name();
853 Location loc = this->package_->location();
855 Function_type* fntype = Type::make_function_type(NULL, NULL, NULL, loc);
856 Function* initfn = new Function(fntype, NULL, NULL, loc);
857 return Named_object::make_function(name, NULL, initfn);
860 // Create the magic initialization function. CODE_STMT is the
861 // code that it needs to run.
863 Named_object*
864 Gogo::create_initialization_function(Named_object* initfn,
865 Bstatement* code_stmt)
867 // Make sure that we thought we needed an initialization function,
868 // as otherwise we will not have reported it in the export data.
869 go_assert(this->is_main_package() || this->need_init_fn_);
871 if (initfn == NULL)
872 initfn = this->initialization_function_decl();
874 // Bind the initialization function code to a block.
875 Bfunction* fndecl = initfn->func_value()->get_or_make_decl(this, initfn);
876 Location pkg_loc = this->package_->location();
877 std::vector<Bvariable*> vars;
878 this->backend()->block(fndecl, NULL, vars, pkg_loc, pkg_loc);
880 if (!this->backend()->function_set_body(fndecl, code_stmt))
882 go_assert(saw_errors());
883 return NULL;
885 return initfn;
888 // Search for references to VAR in any statements or called functions.
890 class Find_var : public Traverse
892 public:
893 // A hash table we use to avoid looping. The index is the name of a
894 // named object. We only look through objects defined in this
895 // package.
896 typedef Unordered_set(const void*) Seen_objects;
898 Find_var(Named_object* var, Seen_objects* seen_objects)
899 : Traverse(traverse_expressions),
900 var_(var), seen_objects_(seen_objects), found_(false)
903 // Whether the variable was found.
904 bool
905 found() const
906 { return this->found_; }
909 expression(Expression**);
911 private:
912 // The variable we are looking for.
913 Named_object* var_;
914 // Names of objects we have already seen.
915 Seen_objects* seen_objects_;
916 // True if the variable was found.
917 bool found_;
920 // See if EXPR refers to VAR, looking through function calls and
921 // variable initializations.
924 Find_var::expression(Expression** pexpr)
926 Expression* e = *pexpr;
928 Var_expression* ve = e->var_expression();
929 if (ve != NULL)
931 Named_object* v = ve->named_object();
932 if (v == this->var_)
934 this->found_ = true;
935 return TRAVERSE_EXIT;
938 if (v->is_variable() && v->package() == NULL)
940 Expression* init = v->var_value()->init();
941 if (init != NULL)
943 std::pair<Seen_objects::iterator, bool> ins =
944 this->seen_objects_->insert(v);
945 if (ins.second)
947 // This is the first time we have seen this name.
948 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
949 return TRAVERSE_EXIT;
955 // We traverse the code of any function we see. Note that this
956 // means that we will traverse the code of a function whose address
957 // is taken even if it is not called.
958 Func_expression* fe = e->func_expression();
959 if (fe != NULL)
961 const Named_object* f = fe->named_object();
962 if (f->is_function() && f->package() == NULL)
964 std::pair<Seen_objects::iterator, bool> ins =
965 this->seen_objects_->insert(f);
966 if (ins.second)
968 // This is the first time we have seen this name.
969 if (f->func_value()->block()->traverse(this) == TRAVERSE_EXIT)
970 return TRAVERSE_EXIT;
975 Temporary_reference_expression* tre = e->temporary_reference_expression();
976 if (tre != NULL)
978 Temporary_statement* ts = tre->statement();
979 Expression* init = ts->init();
980 if (init != NULL)
982 std::pair<Seen_objects::iterator, bool> ins =
983 this->seen_objects_->insert(ts);
984 if (ins.second)
986 // This is the first time we have seen this temporary
987 // statement.
988 if (Expression::traverse(&init, this) == TRAVERSE_EXIT)
989 return TRAVERSE_EXIT;
994 return TRAVERSE_CONTINUE;
997 // Return true if EXPR, PREINIT, or DEP refers to VAR.
999 static bool
1000 expression_requires(Expression* expr, Block* preinit, Named_object* dep,
1001 Named_object* var)
1003 Find_var::Seen_objects seen_objects;
1004 Find_var find_var(var, &seen_objects);
1005 if (expr != NULL)
1006 Expression::traverse(&expr, &find_var);
1007 if (preinit != NULL)
1008 preinit->traverse(&find_var);
1009 if (dep != NULL)
1011 Expression* init = dep->var_value()->init();
1012 if (init != NULL)
1013 Expression::traverse(&init, &find_var);
1014 if (dep->var_value()->has_pre_init())
1015 dep->var_value()->preinit()->traverse(&find_var);
1018 return find_var.found();
1021 // Sort variable initializations. If the initialization expression
1022 // for variable A refers directly or indirectly to the initialization
1023 // expression for variable B, then we must initialize B before A.
1025 class Var_init
1027 public:
1028 Var_init()
1029 : var_(NULL), init_(NULL)
1032 Var_init(Named_object* var, Bstatement* init)
1033 : var_(var), init_(init)
1036 // Return the variable.
1037 Named_object*
1038 var() const
1039 { return this->var_; }
1041 // Return the initialization expression.
1042 Bstatement*
1043 init() const
1044 { return this->init_; }
1046 private:
1047 // The variable being initialized.
1048 Named_object* var_;
1049 // The initialization statement.
1050 Bstatement* init_;
1053 typedef std::list<Var_init> Var_inits;
1055 // Sort the variable initializations. The rule we follow is that we
1056 // emit them in the order they appear in the array, except that if the
1057 // initialization expression for a variable V1 depends upon another
1058 // variable V2 then we initialize V1 after V2.
1060 static void
1061 sort_var_inits(Gogo* gogo, Var_inits* var_inits)
1063 typedef std::pair<Named_object*, Named_object*> No_no;
1064 typedef std::map<No_no, bool> Cache;
1065 Cache cache;
1067 Var_inits ready;
1068 while (!var_inits->empty())
1070 Var_inits::iterator p1 = var_inits->begin();
1071 Named_object* var = p1->var();
1072 Expression* init = var->var_value()->init();
1073 Block* preinit = var->var_value()->preinit();
1074 Named_object* dep = gogo->var_depends_on(var->var_value());
1076 // Start walking through the list to see which variables VAR
1077 // needs to wait for.
1078 Var_inits::iterator p2 = p1;
1079 ++p2;
1081 for (; p2 != var_inits->end(); ++p2)
1083 Named_object* p2var = p2->var();
1084 No_no key(var, p2var);
1085 std::pair<Cache::iterator, bool> ins =
1086 cache.insert(std::make_pair(key, false));
1087 if (ins.second)
1088 ins.first->second = expression_requires(init, preinit, dep, p2var);
1089 if (ins.first->second)
1091 // Check for cycles.
1092 key = std::make_pair(p2var, var);
1093 ins = cache.insert(std::make_pair(key, false));
1094 if (ins.second)
1095 ins.first->second =
1096 expression_requires(p2var->var_value()->init(),
1097 p2var->var_value()->preinit(),
1098 gogo->var_depends_on(p2var->var_value()),
1099 var);
1100 if (ins.first->second)
1102 error_at(var->location(),
1103 ("initialization expressions for %qs and "
1104 "%qs depend upon each other"),
1105 var->message_name().c_str(),
1106 p2var->message_name().c_str());
1107 inform(p2->var()->location(), "%qs defined here",
1108 p2var->message_name().c_str());
1109 p2 = var_inits->end();
1111 else
1113 // We can't emit P1 until P2 is emitted. Move P1.
1114 Var_inits::iterator p3 = p2;
1115 ++p3;
1116 var_inits->splice(p3, *var_inits, p1);
1118 break;
1122 if (p2 == var_inits->end())
1124 // VAR does not depends upon any other initialization expressions.
1126 // Check for a loop of VAR on itself. We only do this if
1127 // INIT is not NULL and there is no dependency; when INIT is
1128 // NULL, it means that PREINIT sets VAR, which we will
1129 // interpret as a loop.
1130 if (init != NULL && dep == NULL
1131 && expression_requires(init, preinit, NULL, var))
1132 error_at(var->location(),
1133 "initialization expression for %qs depends upon itself",
1134 var->message_name().c_str());
1135 ready.splice(ready.end(), *var_inits, p1);
1139 // Now READY is the list in the desired initialization order.
1140 var_inits->swap(ready);
1143 // Write out the global definitions.
1145 void
1146 Gogo::write_globals()
1148 this->build_interface_method_tables();
1150 Bindings* bindings = this->current_bindings();
1152 for (Bindings::const_declarations_iterator p = bindings->begin_declarations();
1153 p != bindings->end_declarations();
1154 ++p)
1156 // If any function declarations needed a descriptor, make sure
1157 // we build it.
1158 Named_object* no = p->second;
1159 if (no->is_function_declaration())
1160 no->func_declaration_value()->build_backend_descriptor(this);
1163 // Lists of globally declared types, variables, constants, and functions
1164 // that must be defined.
1165 std::vector<Btype*> type_decls;
1166 std::vector<Bvariable*> var_decls;
1167 std::vector<Bexpression*> const_decls;
1168 std::vector<Bfunction*> func_decls;
1170 // The init function declaration, if necessary.
1171 Named_object* init_fndecl = NULL;
1173 std::vector<Bstatement*> init_stmts;
1174 std::vector<Bstatement*> var_init_stmts;
1176 if (this->is_main_package())
1177 this->init_imports(init_stmts);
1179 // A list of variable initializations.
1180 Var_inits var_inits;
1182 // A list of variables which need to be registered with the garbage
1183 // collector.
1184 size_t count_definitions = bindings->size_definitions();
1185 std::vector<Named_object*> var_gc;
1186 var_gc.reserve(count_definitions);
1188 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1189 p != bindings->end_definitions();
1190 ++p)
1192 Named_object* no = *p;
1193 go_assert(!no->is_type_declaration() && !no->is_function_declaration());
1195 // There is nothing to do for a package.
1196 if (no->is_package())
1197 continue;
1199 // There is nothing to do for an object which was imported from
1200 // a different package into the global scope.
1201 if (no->package() != NULL)
1202 continue;
1204 // Skip blank named functions and constants.
1205 if ((no->is_function() && no->func_value()->is_sink())
1206 || (no->is_const() && no->const_value()->is_sink()))
1207 continue;
1209 // There is nothing useful we can output for constants which
1210 // have ideal or non-integral type.
1211 if (no->is_const())
1213 Type* type = no->const_value()->type();
1214 if (type == NULL)
1215 type = no->const_value()->expr()->type();
1216 if (type->is_abstract() || !type->is_numeric_type())
1217 continue;
1220 if (!no->is_variable())
1221 no->get_backend(this, const_decls, type_decls, func_decls);
1222 else
1224 Variable* var = no->var_value();
1225 Bvariable* bvar = no->get_backend_variable(this, NULL);
1226 var_decls.push_back(bvar);
1228 // Check for a sink variable, which may be used to run an
1229 // initializer purely for its side effects.
1230 bool is_sink = no->name()[0] == '_' && no->name()[1] == '.';
1232 Bstatement* var_init_stmt = NULL;
1233 if (!var->has_pre_init())
1235 // If the backend representation of the variable initializer is
1236 // constant, we can just set the initial value using
1237 // global_var_set_init instead of during the init() function.
1238 // The initializer is constant if it is the zero-value of the
1239 // variable's type or if the initial value is an immutable value
1240 // that is not copied to the heap.
1241 bool is_constant_initializer = false;
1242 if (var->init() == NULL)
1243 is_constant_initializer = true;
1244 else
1246 Type* var_type = var->type();
1247 Expression* init = var->init();
1248 Expression* init_cast =
1249 Expression::make_cast(var_type, init, var->location());
1250 is_constant_initializer =
1251 init_cast->is_immutable() && !var_type->has_pointer();
1254 // Non-constant variable initializations might need to create
1255 // temporary variables, which will need the initialization
1256 // function as context.
1257 if (!is_constant_initializer && init_fndecl == NULL)
1258 init_fndecl = this->initialization_function_decl();
1259 Bexpression* var_binit = var->get_init(this, init_fndecl);
1261 if (var_binit == NULL)
1263 else if (is_constant_initializer)
1265 if (expression_requires(var->init(), NULL,
1266 this->var_depends_on(var), no))
1267 error_at(no->location(),
1268 "initialization expression for %qs depends "
1269 "upon itself",
1270 no->message_name().c_str());
1271 this->backend()->global_variable_set_init(bvar, var_binit);
1273 else if (is_sink)
1274 var_init_stmt =
1275 this->backend()->expression_statement(var_binit);
1276 else
1278 Location loc = var->location();
1279 Bexpression* var_expr =
1280 this->backend()->var_expression(bvar, loc);
1281 var_init_stmt =
1282 this->backend()->assignment_statement(var_expr, var_binit,
1283 loc);
1286 else
1288 // We are going to create temporary variables which
1289 // means that we need an fndecl.
1290 if (init_fndecl == NULL)
1291 init_fndecl = this->initialization_function_decl();
1293 Bvariable* var_decl = is_sink ? NULL : bvar;
1294 var_init_stmt = var->get_init_block(this, init_fndecl, var_decl);
1297 if (var_init_stmt != NULL)
1299 if (var->init() == NULL && !var->has_pre_init())
1300 var_init_stmts.push_back(var_init_stmt);
1301 else
1302 var_inits.push_back(Var_init(no, var_init_stmt));
1304 else if (this->var_depends_on(var) != NULL)
1306 // This variable is initialized from something that is
1307 // not in its init or preinit. This variable needs to
1308 // participate in dependency analysis sorting, in case
1309 // some other variable depends on this one.
1310 Btype* btype = no->var_value()->type()->get_backend(this);
1311 Bexpression* zero = this->backend()->zero_expression(btype);
1312 Bstatement* zero_stmt =
1313 this->backend()->expression_statement(zero);
1314 var_inits.push_back(Var_init(no, zero_stmt));
1317 if (!is_sink && var->type()->has_pointer())
1318 var_gc.push_back(no);
1322 // Register global variables with the garbage collector.
1323 this->register_gc_vars(var_gc, init_stmts);
1325 // Simple variable initializations, after all variables are
1326 // registered.
1327 init_stmts.push_back(this->backend()->statement_list(var_init_stmts));
1329 // Complete variable initializations, first sorting them into a
1330 // workable order.
1331 if (!var_inits.empty())
1333 sort_var_inits(this, &var_inits);
1334 for (Var_inits::const_iterator p = var_inits.begin();
1335 p != var_inits.end();
1336 ++p)
1337 init_stmts.push_back(p->init());
1340 // After all the variables are initialized, call the init
1341 // functions if there are any. Init functions take no arguments, so
1342 // we pass in EMPTY_ARGS to call them.
1343 std::vector<Bexpression*> empty_args;
1344 for (std::vector<Named_object*>::const_iterator p =
1345 this->init_functions_.begin();
1346 p != this->init_functions_.end();
1347 ++p)
1349 Location func_loc = (*p)->location();
1350 Function* func = (*p)->func_value();
1351 Bfunction* initfn = func->get_or_make_decl(this, *p);
1352 Bexpression* func_code =
1353 this->backend()->function_code_expression(initfn, func_loc);
1354 Bexpression* call = this->backend()->call_expression(func_code,
1355 empty_args,
1356 func_loc);
1357 init_stmts.push_back(this->backend()->expression_statement(call));
1360 // Set up a magic function to do all the initialization actions.
1361 // This will be called if this package is imported.
1362 Bstatement* init_fncode = this->backend()->statement_list(init_stmts);
1363 if (this->need_init_fn_ || this->is_main_package())
1365 init_fndecl =
1366 this->create_initialization_function(init_fndecl, init_fncode);
1367 if (init_fndecl != NULL)
1368 func_decls.push_back(init_fndecl->func_value()->get_decl());
1371 // We should not have seen any new bindings created during the conversion.
1372 go_assert(count_definitions == this->current_bindings()->size_definitions());
1374 // Define all globally declared values.
1375 if (!saw_errors())
1376 this->backend()->write_global_definitions(type_decls, const_decls,
1377 func_decls, var_decls);
1380 // Return the current block.
1382 Block*
1383 Gogo::current_block()
1385 if (this->functions_.empty())
1386 return NULL;
1387 else
1388 return this->functions_.back().blocks.back();
1391 // Look up a name in the current binding contour. If PFUNCTION is not
1392 // NULL, set it to the function in which the name is defined, or NULL
1393 // if the name is defined in global scope.
1395 Named_object*
1396 Gogo::lookup(const std::string& name, Named_object** pfunction) const
1398 if (pfunction != NULL)
1399 *pfunction = NULL;
1401 if (Gogo::is_sink_name(name))
1402 return Named_object::make_sink();
1404 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
1405 p != this->functions_.rend();
1406 ++p)
1408 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
1409 if (ret != NULL)
1411 if (pfunction != NULL)
1412 *pfunction = p->function;
1413 return ret;
1417 if (this->package_ != NULL)
1419 Named_object* ret = this->package_->bindings()->lookup(name);
1420 if (ret != NULL)
1422 if (ret->package() != NULL)
1423 ret->package()->set_used();
1424 return ret;
1428 // We do not look in the global namespace. If we did, the global
1429 // namespace would effectively hide names which were defined in
1430 // package scope which we have not yet seen. Instead,
1431 // define_global_names is called after parsing is over to connect
1432 // undefined names at package scope with names defined at global
1433 // scope.
1435 return NULL;
1438 // Look up a name in the current block, without searching enclosing
1439 // blocks.
1441 Named_object*
1442 Gogo::lookup_in_block(const std::string& name) const
1444 go_assert(!this->functions_.empty());
1445 go_assert(!this->functions_.back().blocks.empty());
1446 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
1449 // Look up a name in the global namespace.
1451 Named_object*
1452 Gogo::lookup_global(const char* name) const
1454 return this->globals_->lookup(name);
1457 // Add an imported package.
1459 Package*
1460 Gogo::add_imported_package(const std::string& real_name,
1461 const std::string& alias_arg,
1462 bool is_alias_exported,
1463 const std::string& pkgpath,
1464 Location location,
1465 bool* padd_to_globals)
1467 Package* ret = this->register_package(pkgpath, location);
1468 ret->set_package_name(real_name, location);
1470 *padd_to_globals = false;
1472 if (alias_arg == ".")
1473 *padd_to_globals = true;
1474 else if (alias_arg == "_")
1475 ret->set_uses_sink_alias();
1476 else
1478 std::string alias = alias_arg;
1479 if (alias.empty())
1481 alias = real_name;
1482 is_alias_exported = Lex::is_exported_name(alias);
1484 alias = this->pack_hidden_name(alias, is_alias_exported);
1485 Named_object* no = this->package_->bindings()->add_package(alias, ret);
1486 if (!no->is_package())
1487 return NULL;
1490 return ret;
1493 // Register a package. This package may or may not be imported. This
1494 // returns the Package structure for the package, creating if it
1495 // necessary. LOCATION is the location of the import statement that
1496 // led us to see this package.
1498 Package*
1499 Gogo::register_package(const std::string& pkgpath, Location location)
1501 Package* package = NULL;
1502 std::pair<Packages::iterator, bool> ins =
1503 this->packages_.insert(std::make_pair(pkgpath, package));
1504 if (!ins.second)
1506 // We have seen this package name before.
1507 package = ins.first->second;
1508 go_assert(package != NULL && package->pkgpath() == pkgpath);
1509 if (Linemap::is_unknown_location(package->location()))
1510 package->set_location(location);
1512 else
1514 // First time we have seen this package name.
1515 package = new Package(pkgpath, location);
1516 go_assert(ins.first->second == NULL);
1517 ins.first->second = package;
1520 return package;
1523 // Start compiling a function.
1525 Named_object*
1526 Gogo::start_function(const std::string& name, Function_type* type,
1527 bool add_method_to_type, Location location)
1529 bool at_top_level = this->functions_.empty();
1531 Block* block = new Block(NULL, location);
1533 Function* enclosing = (at_top_level
1534 ? NULL
1535 : this->functions_.back().function->func_value());
1537 Function* function = new Function(type, enclosing, block, location);
1539 if (type->is_method())
1541 const Typed_identifier* receiver = type->receiver();
1542 Variable* this_param = new Variable(receiver->type(), NULL, false,
1543 true, true, location);
1544 std::string rname = receiver->name();
1545 if (rname.empty() || Gogo::is_sink_name(rname))
1547 // We need to give receivers a name since they wind up in
1548 // DECL_ARGUMENTS. FIXME.
1549 static unsigned int count;
1550 char buf[50];
1551 snprintf(buf, sizeof buf, "r.%u", count);
1552 ++count;
1553 rname = buf;
1555 block->bindings()->add_variable(rname, NULL, this_param);
1558 const Typed_identifier_list* parameters = type->parameters();
1559 bool is_varargs = type->is_varargs();
1560 if (parameters != NULL)
1562 for (Typed_identifier_list::const_iterator p = parameters->begin();
1563 p != parameters->end();
1564 ++p)
1566 Variable* param = new Variable(p->type(), NULL, false, true, false,
1567 location);
1568 if (is_varargs && p + 1 == parameters->end())
1569 param->set_is_varargs_parameter();
1571 std::string pname = p->name();
1572 if (pname.empty() || Gogo::is_sink_name(pname))
1574 // We need to give parameters a name since they wind up
1575 // in DECL_ARGUMENTS. FIXME.
1576 static unsigned int count;
1577 char buf[50];
1578 snprintf(buf, sizeof buf, "p.%u", count);
1579 ++count;
1580 pname = buf;
1582 block->bindings()->add_variable(pname, NULL, param);
1586 function->create_result_variables(this);
1588 const std::string* pname;
1589 std::string nested_name;
1590 bool is_init = false;
1591 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
1593 if ((type->parameters() != NULL && !type->parameters()->empty())
1594 || (type->results() != NULL && !type->results()->empty()))
1595 error_at(location,
1596 "func init must have no arguments and no return values");
1597 // There can be multiple "init" functions, so give them each a
1598 // different name.
1599 static int init_count;
1600 char buf[30];
1601 snprintf(buf, sizeof buf, ".$init%d", init_count);
1602 ++init_count;
1603 nested_name = buf;
1604 pname = &nested_name;
1605 is_init = true;
1607 else if (!name.empty())
1608 pname = &name;
1609 else
1611 // Invent a name for a nested function.
1612 static int nested_count;
1613 char buf[30];
1614 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
1615 ++nested_count;
1616 nested_name = buf;
1617 pname = &nested_name;
1620 Named_object* ret;
1621 if (Gogo::is_sink_name(*pname))
1623 static int sink_count;
1624 char buf[30];
1625 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
1626 ++sink_count;
1627 ret = this->package_->bindings()->add_function(buf, NULL, function);
1628 ret->func_value()->set_is_sink();
1630 else if (!type->is_method())
1632 ret = this->package_->bindings()->add_function(*pname, NULL, function);
1633 if (!ret->is_function() || ret->func_value() != function)
1635 // Redefinition error. Invent a name to avoid knockon
1636 // errors.
1637 static int redefinition_count;
1638 char buf[30];
1639 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
1640 ++redefinition_count;
1641 ret = this->package_->bindings()->add_function(buf, NULL, function);
1644 else
1646 if (!add_method_to_type)
1647 ret = Named_object::make_function(name, NULL, function);
1648 else
1650 go_assert(at_top_level);
1651 Type* rtype = type->receiver()->type();
1653 // We want to look through the pointer created by the
1654 // parser, without getting an error if the type is not yet
1655 // defined.
1656 if (rtype->classification() == Type::TYPE_POINTER)
1657 rtype = rtype->points_to();
1659 if (rtype->is_error_type())
1660 ret = Named_object::make_function(name, NULL, function);
1661 else if (rtype->named_type() != NULL)
1663 ret = rtype->named_type()->add_method(name, function);
1664 if (!ret->is_function())
1666 // Redefinition error.
1667 ret = Named_object::make_function(name, NULL, function);
1670 else if (rtype->forward_declaration_type() != NULL)
1672 Named_object* type_no =
1673 rtype->forward_declaration_type()->named_object();
1674 if (type_no->is_unknown())
1676 // If we are seeing methods it really must be a
1677 // type. Declare it as such. An alternative would
1678 // be to support lists of methods for unknown
1679 // expressions. Either way the error messages if
1680 // this is not a type are going to get confusing.
1681 Named_object* declared =
1682 this->declare_package_type(type_no->name(),
1683 type_no->location());
1684 go_assert(declared
1685 == type_no->unknown_value()->real_named_object());
1687 ret = rtype->forward_declaration_type()->add_method(name,
1688 function);
1690 else
1691 go_unreachable();
1693 this->package_->bindings()->add_method(ret);
1696 this->functions_.resize(this->functions_.size() + 1);
1697 Open_function& of(this->functions_.back());
1698 of.function = ret;
1699 of.blocks.push_back(block);
1701 if (is_init)
1703 this->init_functions_.push_back(ret);
1704 this->need_init_fn_ = true;
1707 return ret;
1710 // Finish compiling a function.
1712 void
1713 Gogo::finish_function(Location location)
1715 this->finish_block(location);
1716 go_assert(this->functions_.back().blocks.empty());
1717 this->functions_.pop_back();
1720 // Return the current function.
1722 Named_object*
1723 Gogo::current_function() const
1725 go_assert(!this->functions_.empty());
1726 return this->functions_.back().function;
1729 // Start a new block.
1731 void
1732 Gogo::start_block(Location location)
1734 go_assert(!this->functions_.empty());
1735 Block* block = new Block(this->current_block(), location);
1736 this->functions_.back().blocks.push_back(block);
1739 // Finish a block.
1741 Block*
1742 Gogo::finish_block(Location location)
1744 go_assert(!this->functions_.empty());
1745 go_assert(!this->functions_.back().blocks.empty());
1746 Block* block = this->functions_.back().blocks.back();
1747 this->functions_.back().blocks.pop_back();
1748 block->set_end_location(location);
1749 return block;
1752 // Add an erroneous name.
1754 Named_object*
1755 Gogo::add_erroneous_name(const std::string& name)
1757 return this->package_->bindings()->add_erroneous_name(name);
1760 // Add an unknown name.
1762 Named_object*
1763 Gogo::add_unknown_name(const std::string& name, Location location)
1765 return this->package_->bindings()->add_unknown_name(name, location);
1768 // Declare a function.
1770 Named_object*
1771 Gogo::declare_function(const std::string& name, Function_type* type,
1772 Location location)
1774 if (!type->is_method())
1775 return this->current_bindings()->add_function_declaration(name, NULL, type,
1776 location);
1777 else
1779 // We don't bother to add this to the list of global
1780 // declarations.
1781 Type* rtype = type->receiver()->type();
1783 // We want to look through the pointer created by the
1784 // parser, without getting an error if the type is not yet
1785 // defined.
1786 if (rtype->classification() == Type::TYPE_POINTER)
1787 rtype = rtype->points_to();
1789 if (rtype->is_error_type())
1790 return NULL;
1791 else if (rtype->named_type() != NULL)
1792 return rtype->named_type()->add_method_declaration(name, NULL, type,
1793 location);
1794 else if (rtype->forward_declaration_type() != NULL)
1796 Forward_declaration_type* ftype = rtype->forward_declaration_type();
1797 return ftype->add_method_declaration(name, NULL, type, location);
1799 else
1800 go_unreachable();
1804 // Add a label definition.
1806 Label*
1807 Gogo::add_label_definition(const std::string& label_name,
1808 Location location)
1810 // A label with a blank identifier is never declared or defined.
1811 if (label_name == "_")
1812 return NULL;
1814 go_assert(!this->functions_.empty());
1815 Function* func = this->functions_.back().function->func_value();
1816 Label* label = func->add_label_definition(this, label_name, location);
1817 this->add_statement(Statement::make_label_statement(label, location));
1818 return label;
1821 // Add a label reference.
1823 Label*
1824 Gogo::add_label_reference(const std::string& label_name,
1825 Location location, bool issue_goto_errors)
1827 go_assert(!this->functions_.empty());
1828 Function* func = this->functions_.back().function->func_value();
1829 return func->add_label_reference(this, label_name, location,
1830 issue_goto_errors);
1833 // Return the current binding state.
1835 Bindings_snapshot*
1836 Gogo::bindings_snapshot(Location location)
1838 return new Bindings_snapshot(this->current_block(), location);
1841 // Add a statement.
1843 void
1844 Gogo::add_statement(Statement* statement)
1846 go_assert(!this->functions_.empty()
1847 && !this->functions_.back().blocks.empty());
1848 this->functions_.back().blocks.back()->add_statement(statement);
1851 // Add a block.
1853 void
1854 Gogo::add_block(Block* block, Location location)
1856 go_assert(!this->functions_.empty()
1857 && !this->functions_.back().blocks.empty());
1858 Statement* statement = Statement::make_block_statement(block, location);
1859 this->functions_.back().blocks.back()->add_statement(statement);
1862 // Add a constant.
1864 Named_object*
1865 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
1866 int iota_value)
1868 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
1871 // Add a type.
1873 void
1874 Gogo::add_type(const std::string& name, Type* type, Location location)
1876 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
1877 location);
1878 if (!this->in_global_scope() && no->is_type())
1880 Named_object* f = this->functions_.back().function;
1881 unsigned int index;
1882 if (f->is_function())
1883 index = f->func_value()->new_local_type_index();
1884 else
1885 index = 0;
1886 no->type_value()->set_in_function(f, index);
1890 // Add a named type.
1892 void
1893 Gogo::add_named_type(Named_type* type)
1895 go_assert(this->in_global_scope());
1896 this->current_bindings()->add_named_type(type);
1899 // Declare a type.
1901 Named_object*
1902 Gogo::declare_type(const std::string& name, Location location)
1904 Bindings* bindings = this->current_bindings();
1905 Named_object* no = bindings->add_type_declaration(name, NULL, location);
1906 if (!this->in_global_scope() && no->is_type_declaration())
1908 Named_object* f = this->functions_.back().function;
1909 unsigned int index;
1910 if (f->is_function())
1911 index = f->func_value()->new_local_type_index();
1912 else
1913 index = 0;
1914 no->type_declaration_value()->set_in_function(f, index);
1916 return no;
1919 // Declare a type at the package level.
1921 Named_object*
1922 Gogo::declare_package_type(const std::string& name, Location location)
1924 return this->package_->bindings()->add_type_declaration(name, NULL, location);
1927 // Declare a function at the package level.
1929 Named_object*
1930 Gogo::declare_package_function(const std::string& name, Function_type* type,
1931 Location location)
1933 return this->package_->bindings()->add_function_declaration(name, NULL, type,
1934 location);
1937 // Define a type which was already declared.
1939 void
1940 Gogo::define_type(Named_object* no, Named_type* type)
1942 this->current_bindings()->define_type(no, type);
1945 // Add a variable.
1947 Named_object*
1948 Gogo::add_variable(const std::string& name, Variable* variable)
1950 Named_object* no = this->current_bindings()->add_variable(name, NULL,
1951 variable);
1953 // In a function the middle-end wants to see a DECL_EXPR node.
1954 if (no != NULL
1955 && no->is_variable()
1956 && !no->var_value()->is_parameter()
1957 && !this->functions_.empty())
1958 this->add_statement(Statement::make_variable_declaration(no));
1960 return no;
1963 // Add a sink--a reference to the blank identifier _.
1965 Named_object*
1966 Gogo::add_sink()
1968 return Named_object::make_sink();
1971 // Add a named object for a dot import.
1973 void
1974 Gogo::add_dot_import_object(Named_object* no)
1976 // If the name already exists, then it was defined in some file seen
1977 // earlier. If the earlier name is just a declaration, don't add
1978 // this name, because that will cause the previous declaration to
1979 // merge to this imported name, which should not happen. Just add
1980 // this name to the list of file block names to get appropriate
1981 // errors if we see a later definition.
1982 Named_object* e = this->package_->bindings()->lookup(no->name());
1983 if (e != NULL && e->package() == NULL)
1985 if (e->is_unknown())
1986 e = e->resolve();
1987 if (e->package() == NULL
1988 && (e->is_type_declaration()
1989 || e->is_function_declaration()
1990 || e->is_unknown()))
1992 this->add_file_block_name(no->name(), no->location());
1993 return;
1997 this->current_bindings()->add_named_object(no);
2000 // Mark all local variables used. This is used when some types of
2001 // parse error occur.
2003 void
2004 Gogo::mark_locals_used()
2006 for (Open_functions::iterator pf = this->functions_.begin();
2007 pf != this->functions_.end();
2008 ++pf)
2010 for (std::vector<Block*>::iterator pb = pf->blocks.begin();
2011 pb != pf->blocks.end();
2012 ++pb)
2013 (*pb)->bindings()->mark_locals_used();
2017 // Record that we've seen an interface type.
2019 void
2020 Gogo::record_interface_type(Interface_type* itype)
2022 this->interface_types_.push_back(itype);
2025 // Return an erroneous name that indicates that an error has already
2026 // been reported.
2028 std::string
2029 Gogo::erroneous_name()
2031 static int erroneous_count;
2032 char name[50];
2033 snprintf(name, sizeof name, "$erroneous%d", erroneous_count);
2034 ++erroneous_count;
2035 return name;
2038 // Return whether a name is an erroneous name.
2040 bool
2041 Gogo::is_erroneous_name(const std::string& name)
2043 return name.compare(0, 10, "$erroneous") == 0;
2046 // Return a name for a thunk object.
2048 std::string
2049 Gogo::thunk_name()
2051 static int thunk_count;
2052 char thunk_name[50];
2053 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
2054 ++thunk_count;
2055 return thunk_name;
2058 // Return whether a function is a thunk.
2060 bool
2061 Gogo::is_thunk(const Named_object* no)
2063 return no->name().compare(0, 6, "$thunk") == 0;
2066 // Define the global names. We do this only after parsing all the
2067 // input files, because the program might define the global names
2068 // itself.
2070 void
2071 Gogo::define_global_names()
2073 for (Bindings::const_declarations_iterator p =
2074 this->globals_->begin_declarations();
2075 p != this->globals_->end_declarations();
2076 ++p)
2078 Named_object* global_no = p->second;
2079 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
2080 Named_object* no = this->package_->bindings()->lookup(name);
2081 if (no == NULL)
2082 continue;
2083 no = no->resolve();
2084 if (no->is_type_declaration())
2086 if (global_no->is_type())
2088 if (no->type_declaration_value()->has_methods())
2089 error_at(no->location(),
2090 "may not define methods for global type");
2091 no->set_type_value(global_no->type_value());
2093 else
2095 error_at(no->location(), "expected type");
2096 Type* errtype = Type::make_error_type();
2097 Named_object* err =
2098 Named_object::make_type("erroneous_type", NULL, errtype,
2099 Linemap::predeclared_location());
2100 no->set_type_value(err->type_value());
2103 else if (no->is_unknown())
2104 no->unknown_value()->set_real_named_object(global_no);
2107 // Give an error if any name is defined in both the package block
2108 // and the file block. For example, this can happen if one file
2109 // imports "fmt" and another file defines a global variable fmt.
2110 for (Bindings::const_declarations_iterator p =
2111 this->package_->bindings()->begin_declarations();
2112 p != this->package_->bindings()->end_declarations();
2113 ++p)
2115 if (p->second->is_unknown()
2116 && p->second->unknown_value()->real_named_object() == NULL)
2118 // No point in warning about an undefined name, as we will
2119 // get other errors later anyhow.
2120 continue;
2122 File_block_names::const_iterator pf =
2123 this->file_block_names_.find(p->second->name());
2124 if (pf != this->file_block_names_.end())
2126 std::string n = p->second->message_name();
2127 error_at(p->second->location(),
2128 "%qs defined as both imported name and global name",
2129 n.c_str());
2130 inform(pf->second, "%qs imported here", n.c_str());
2133 // No package scope identifier may be named "init".
2134 if (!p->second->is_function()
2135 && Gogo::unpack_hidden_name(p->second->name()) == "init")
2137 error_at(p->second->location(),
2138 "cannot declare init - must be func");
2143 // Clear out names in file scope.
2145 void
2146 Gogo::clear_file_scope()
2148 this->package_->bindings()->clear_file_scope(this);
2150 // Warn about packages which were imported but not used.
2151 bool quiet = saw_errors();
2152 for (Packages::iterator p = this->packages_.begin();
2153 p != this->packages_.end();
2154 ++p)
2156 Package* package = p->second;
2157 if (package != this->package_
2158 && package->is_imported()
2159 && !package->used()
2160 && !package->uses_sink_alias()
2161 && !quiet)
2162 error_at(package->location(), "imported and not used: %s",
2163 Gogo::message_name(package->package_name()).c_str());
2164 package->clear_is_imported();
2165 package->clear_uses_sink_alias();
2166 package->clear_used();
2170 // Queue up a type specific function for later writing. These are
2171 // written out in write_specific_type_functions, called after the
2172 // parse tree is lowered.
2174 void
2175 Gogo::queue_specific_type_function(Type* type, Named_type* name,
2176 const std::string& hash_name,
2177 Function_type* hash_fntype,
2178 const std::string& equal_name,
2179 Function_type* equal_fntype)
2181 go_assert(!this->specific_type_functions_are_written_);
2182 go_assert(!this->in_global_scope());
2183 Specific_type_function* tsf = new Specific_type_function(type, name,
2184 hash_name,
2185 hash_fntype,
2186 equal_name,
2187 equal_fntype);
2188 this->specific_type_functions_.push_back(tsf);
2191 // Look for types which need specific hash or equality functions.
2193 class Specific_type_functions : public Traverse
2195 public:
2196 Specific_type_functions(Gogo* gogo)
2197 : Traverse(traverse_types),
2198 gogo_(gogo)
2202 type(Type*);
2204 private:
2205 Gogo* gogo_;
2209 Specific_type_functions::type(Type* t)
2211 Named_object* hash_fn;
2212 Named_object* equal_fn;
2213 switch (t->classification())
2215 case Type::TYPE_NAMED:
2217 Named_type* nt = t->named_type();
2218 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
2219 t->type_functions(this->gogo_, nt, NULL, NULL, &hash_fn, &equal_fn);
2221 // If this is a struct type, we don't want to make functions
2222 // for the unnamed struct.
2223 Type* rt = nt->real_type();
2224 if (rt->struct_type() == NULL)
2226 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2227 return TRAVERSE_EXIT;
2229 else
2231 // If this type is defined in another package, then we don't
2232 // need to worry about the unexported fields.
2233 bool is_defined_elsewhere = nt->named_object()->package() != NULL;
2234 const Struct_field_list* fields = rt->struct_type()->fields();
2235 for (Struct_field_list::const_iterator p = fields->begin();
2236 p != fields->end();
2237 ++p)
2239 if (is_defined_elsewhere
2240 && Gogo::is_hidden_name(p->field_name()))
2241 continue;
2242 if (Type::traverse(p->type(), this) == TRAVERSE_EXIT)
2243 return TRAVERSE_EXIT;
2247 return TRAVERSE_SKIP_COMPONENTS;
2250 case Type::TYPE_STRUCT:
2251 case Type::TYPE_ARRAY:
2252 if (!t->compare_is_identity(this->gogo_) && t->is_comparable())
2253 t->type_functions(this->gogo_, NULL, NULL, NULL, &hash_fn, &equal_fn);
2254 break;
2256 default:
2257 break;
2260 return TRAVERSE_CONTINUE;
2263 // Write out type specific functions.
2265 void
2266 Gogo::write_specific_type_functions()
2268 Specific_type_functions stf(this);
2269 this->traverse(&stf);
2271 while (!this->specific_type_functions_.empty())
2273 Specific_type_function* tsf = this->specific_type_functions_.back();
2274 this->specific_type_functions_.pop_back();
2275 tsf->type->write_specific_type_functions(this, tsf->name,
2276 tsf->hash_name,
2277 tsf->hash_fntype,
2278 tsf->equal_name,
2279 tsf->equal_fntype);
2280 delete tsf;
2282 this->specific_type_functions_are_written_ = true;
2285 // Traverse the tree.
2287 void
2288 Gogo::traverse(Traverse* traverse)
2290 // Traverse the current package first for consistency. The other
2291 // packages will only contain imported types, constants, and
2292 // declarations.
2293 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2294 return;
2295 for (Packages::const_iterator p = this->packages_.begin();
2296 p != this->packages_.end();
2297 ++p)
2299 if (p->second != this->package_)
2301 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
2302 break;
2307 // Add a type to verify. This is used for types of sink variables, in
2308 // order to give appropriate error messages.
2310 void
2311 Gogo::add_type_to_verify(Type* type)
2313 this->verify_types_.push_back(type);
2316 // Traversal class used to verify types.
2318 class Verify_types : public Traverse
2320 public:
2321 Verify_types()
2322 : Traverse(traverse_types)
2326 type(Type*);
2329 // Verify that a type is correct.
2332 Verify_types::type(Type* t)
2334 if (!t->verify())
2335 return TRAVERSE_SKIP_COMPONENTS;
2336 return TRAVERSE_CONTINUE;
2339 // Verify that all types are correct.
2341 void
2342 Gogo::verify_types()
2344 Verify_types traverse;
2345 this->traverse(&traverse);
2347 for (std::vector<Type*>::iterator p = this->verify_types_.begin();
2348 p != this->verify_types_.end();
2349 ++p)
2350 (*p)->verify();
2351 this->verify_types_.clear();
2354 // Traversal class used to lower parse tree.
2356 class Lower_parse_tree : public Traverse
2358 public:
2359 Lower_parse_tree(Gogo* gogo, Named_object* function)
2360 : Traverse(traverse_variables
2361 | traverse_constants
2362 | traverse_functions
2363 | traverse_statements
2364 | traverse_expressions),
2365 gogo_(gogo), function_(function), iota_value_(-1), inserter_()
2368 void
2369 set_inserter(const Statement_inserter* inserter)
2370 { this->inserter_ = *inserter; }
2373 variable(Named_object*);
2376 constant(Named_object*, bool);
2379 function(Named_object*);
2382 statement(Block*, size_t* pindex, Statement*);
2385 expression(Expression**);
2387 private:
2388 // General IR.
2389 Gogo* gogo_;
2390 // The function we are traversing.
2391 Named_object* function_;
2392 // Value to use for the predeclared constant iota.
2393 int iota_value_;
2394 // Current statement inserter for use by expressions.
2395 Statement_inserter inserter_;
2398 // Lower variables.
2401 Lower_parse_tree::variable(Named_object* no)
2403 if (!no->is_variable())
2404 return TRAVERSE_CONTINUE;
2406 if (no->is_variable() && no->var_value()->is_global())
2408 // Global variables can have loops in their initialization
2409 // expressions. This is handled in lower_init_expression.
2410 no->var_value()->lower_init_expression(this->gogo_, this->function_,
2411 &this->inserter_);
2412 return TRAVERSE_CONTINUE;
2415 // This is a local variable. We are going to return
2416 // TRAVERSE_SKIP_COMPONENTS here because we want to traverse the
2417 // initialization expression when we reach the variable declaration
2418 // statement. However, that means that we need to traverse the type
2419 // ourselves.
2420 if (no->var_value()->has_type())
2422 Type* type = no->var_value()->type();
2423 if (type != NULL)
2425 if (Type::traverse(type, this) == TRAVERSE_EXIT)
2426 return TRAVERSE_EXIT;
2429 go_assert(!no->var_value()->has_pre_init());
2431 return TRAVERSE_SKIP_COMPONENTS;
2434 // Lower constants. We handle constants specially so that we can set
2435 // the right value for the predeclared constant iota. This works in
2436 // conjunction with the way we lower Const_expression objects.
2439 Lower_parse_tree::constant(Named_object* no, bool)
2441 Named_constant* nc = no->const_value();
2443 // Don't get into trouble if the constant's initializer expression
2444 // refers to the constant itself.
2445 if (nc->lowering())
2446 return TRAVERSE_CONTINUE;
2447 nc->set_lowering();
2449 go_assert(this->iota_value_ == -1);
2450 this->iota_value_ = nc->iota_value();
2451 nc->traverse_expression(this);
2452 this->iota_value_ = -1;
2454 nc->clear_lowering();
2456 // We will traverse the expression a second time, but that will be
2457 // fast.
2459 return TRAVERSE_CONTINUE;
2462 // Lower the body of a function, and set the closure type. Record the
2463 // function while lowering it, so that we can pass it down when
2464 // lowering an expression.
2467 Lower_parse_tree::function(Named_object* no)
2469 no->func_value()->set_closure_type();
2471 go_assert(this->function_ == NULL);
2472 this->function_ = no;
2473 int t = no->func_value()->traverse(this);
2474 this->function_ = NULL;
2476 if (t == TRAVERSE_EXIT)
2477 return t;
2478 return TRAVERSE_SKIP_COMPONENTS;
2481 // Lower statement parse trees.
2484 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
2486 // Because we explicitly traverse the statement's contents
2487 // ourselves, we want to skip block statements here. There is
2488 // nothing to lower in a block statement.
2489 if (sorig->is_block_statement())
2490 return TRAVERSE_CONTINUE;
2492 Statement_inserter hold_inserter(this->inserter_);
2493 this->inserter_ = Statement_inserter(block, pindex);
2495 // Lower the expressions first.
2496 int t = sorig->traverse_contents(this);
2497 if (t == TRAVERSE_EXIT)
2499 this->inserter_ = hold_inserter;
2500 return t;
2503 // Keep lowering until nothing changes.
2504 Statement* s = sorig;
2505 while (true)
2507 Statement* snew = s->lower(this->gogo_, this->function_, block,
2508 &this->inserter_);
2509 if (snew == s)
2510 break;
2511 s = snew;
2512 t = s->traverse_contents(this);
2513 if (t == TRAVERSE_EXIT)
2515 this->inserter_ = hold_inserter;
2516 return t;
2520 if (s != sorig)
2521 block->replace_statement(*pindex, s);
2523 this->inserter_ = hold_inserter;
2524 return TRAVERSE_SKIP_COMPONENTS;
2527 // Lower expression parse trees.
2530 Lower_parse_tree::expression(Expression** pexpr)
2532 // We have to lower all subexpressions first, so that we can get
2533 // their type if necessary. This is awkward, because we don't have
2534 // a postorder traversal pass.
2535 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
2536 return TRAVERSE_EXIT;
2537 // Keep lowering until nothing changes.
2538 while (true)
2540 Expression* e = *pexpr;
2541 Expression* enew = e->lower(this->gogo_, this->function_,
2542 &this->inserter_, this->iota_value_);
2543 if (enew == e)
2544 break;
2545 if (enew->traverse_subexpressions(this) == TRAVERSE_EXIT)
2546 return TRAVERSE_EXIT;
2547 *pexpr = enew;
2549 return TRAVERSE_SKIP_COMPONENTS;
2552 // Lower the parse tree. This is called after the parse is complete,
2553 // when all names should be resolved.
2555 void
2556 Gogo::lower_parse_tree()
2558 Lower_parse_tree lower_parse_tree(this, NULL);
2559 this->traverse(&lower_parse_tree);
2562 // Lower a block.
2564 void
2565 Gogo::lower_block(Named_object* function, Block* block)
2567 Lower_parse_tree lower_parse_tree(this, function);
2568 block->traverse(&lower_parse_tree);
2571 // Lower an expression. INSERTER may be NULL, in which case the
2572 // expression had better not need to create any temporaries.
2574 void
2575 Gogo::lower_expression(Named_object* function, Statement_inserter* inserter,
2576 Expression** pexpr)
2578 Lower_parse_tree lower_parse_tree(this, function);
2579 if (inserter != NULL)
2580 lower_parse_tree.set_inserter(inserter);
2581 lower_parse_tree.expression(pexpr);
2584 // Lower a constant. This is called when lowering a reference to a
2585 // constant. We have to make sure that the constant has already been
2586 // lowered.
2588 void
2589 Gogo::lower_constant(Named_object* no)
2591 go_assert(no->is_const());
2592 Lower_parse_tree lower(this, NULL);
2593 lower.constant(no, false);
2596 // Traverse the tree to create function descriptors as needed.
2598 class Create_function_descriptors : public Traverse
2600 public:
2601 Create_function_descriptors(Gogo* gogo)
2602 : Traverse(traverse_functions | traverse_expressions),
2603 gogo_(gogo)
2607 function(Named_object*);
2610 expression(Expression**);
2612 private:
2613 Gogo* gogo_;
2616 // Create a descriptor for every top-level exported function.
2619 Create_function_descriptors::function(Named_object* no)
2621 if (no->is_function()
2622 && no->func_value()->enclosing() == NULL
2623 && !no->func_value()->is_method()
2624 && !Gogo::is_hidden_name(no->name())
2625 && !Gogo::is_thunk(no))
2626 no->func_value()->descriptor(this->gogo_, no);
2628 return TRAVERSE_CONTINUE;
2631 // If we see a function referenced in any way other than calling it,
2632 // create a descriptor for it.
2635 Create_function_descriptors::expression(Expression** pexpr)
2637 Expression* expr = *pexpr;
2639 Func_expression* fe = expr->func_expression();
2640 if (fe != NULL)
2642 // We would not get here for a call to this function, so this is
2643 // a reference to a function other than calling it. We need a
2644 // descriptor.
2645 if (fe->closure() != NULL)
2646 return TRAVERSE_CONTINUE;
2647 Named_object* no = fe->named_object();
2648 if (no->is_function() && !no->func_value()->is_method())
2649 no->func_value()->descriptor(this->gogo_, no);
2650 else if (no->is_function_declaration()
2651 && !no->func_declaration_value()->type()->is_method()
2652 && !Linemap::is_predeclared_location(no->location()))
2653 no->func_declaration_value()->descriptor(this->gogo_, no);
2654 return TRAVERSE_CONTINUE;
2657 Bound_method_expression* bme = expr->bound_method_expression();
2658 if (bme != NULL)
2660 // We would not get here for a call to this method, so this is a
2661 // method value. We need to create a thunk.
2662 Bound_method_expression::create_thunk(this->gogo_, bme->method(),
2663 bme->function());
2664 return TRAVERSE_CONTINUE;
2667 Interface_field_reference_expression* ifre =
2668 expr->interface_field_reference_expression();
2669 if (ifre != NULL)
2671 // We would not get here for a call to this interface method, so
2672 // this is a method value. We need to create a thunk.
2673 Interface_type* type = ifre->expr()->type()->interface_type();
2674 if (type != NULL)
2675 Interface_field_reference_expression::create_thunk(this->gogo_, type,
2676 ifre->name());
2677 return TRAVERSE_CONTINUE;
2680 Call_expression* ce = expr->call_expression();
2681 if (ce != NULL)
2683 Expression* fn = ce->fn();
2684 if (fn->func_expression() != NULL
2685 || fn->bound_method_expression() != NULL
2686 || fn->interface_field_reference_expression() != NULL)
2688 // Traverse the arguments but not the function.
2689 Expression_list* args = ce->args();
2690 if (args != NULL)
2692 if (args->traverse(this) == TRAVERSE_EXIT)
2693 return TRAVERSE_EXIT;
2695 return TRAVERSE_SKIP_COMPONENTS;
2699 return TRAVERSE_CONTINUE;
2702 // Create function descriptors as needed. We need a function
2703 // descriptor for all exported functions and for all functions that
2704 // are referenced without being called.
2706 void
2707 Gogo::create_function_descriptors()
2709 // Create a function descriptor for any exported function that is
2710 // declared in this package. This is so that we have a descriptor
2711 // for functions written in assembly. Gather the descriptors first
2712 // so that we don't add declarations while looping over them.
2713 std::vector<Named_object*> fndecls;
2714 Bindings* b = this->package_->bindings();
2715 for (Bindings::const_declarations_iterator p = b->begin_declarations();
2716 p != b->end_declarations();
2717 ++p)
2719 Named_object* no = p->second;
2720 if (no->is_function_declaration()
2721 && !no->func_declaration_value()->type()->is_method()
2722 && !Linemap::is_predeclared_location(no->location())
2723 && !Gogo::is_hidden_name(no->name()))
2724 fndecls.push_back(no);
2726 for (std::vector<Named_object*>::const_iterator p = fndecls.begin();
2727 p != fndecls.end();
2728 ++p)
2729 (*p)->func_declaration_value()->descriptor(this, *p);
2730 fndecls.clear();
2732 Create_function_descriptors cfd(this);
2733 this->traverse(&cfd);
2736 // Look for interface types to finalize methods of inherited
2737 // interfaces.
2739 class Finalize_methods : public Traverse
2741 public:
2742 Finalize_methods(Gogo* gogo)
2743 : Traverse(traverse_types),
2744 gogo_(gogo)
2748 type(Type*);
2750 private:
2751 Gogo* gogo_;
2754 // Finalize the methods of an interface type.
2757 Finalize_methods::type(Type* t)
2759 // Check the classification so that we don't finalize the methods
2760 // twice for a named interface type.
2761 switch (t->classification())
2763 case Type::TYPE_INTERFACE:
2764 t->interface_type()->finalize_methods();
2765 break;
2767 case Type::TYPE_NAMED:
2769 // We have to finalize the methods of the real type first.
2770 // But if the real type is a struct type, then we only want to
2771 // finalize the methods of the field types, not of the struct
2772 // type itself. We don't want to add methods to the struct,
2773 // since it has a name.
2774 Named_type* nt = t->named_type();
2775 Type* rt = nt->real_type();
2776 if (rt->classification() != Type::TYPE_STRUCT)
2778 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
2779 return TRAVERSE_EXIT;
2781 else
2783 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
2784 return TRAVERSE_EXIT;
2787 nt->finalize_methods(this->gogo_);
2789 // If this type is defined in a different package, then finalize the
2790 // types of all the methods, since we won't see them otherwise.
2791 if (nt->named_object()->package() != NULL && nt->has_any_methods())
2793 const Methods* methods = nt->methods();
2794 for (Methods::const_iterator p = methods->begin();
2795 p != methods->end();
2796 ++p)
2798 if (Type::traverse(p->second->type(), this) == TRAVERSE_EXIT)
2799 return TRAVERSE_EXIT;
2803 // Finalize the types of all methods that are declared but not
2804 // defined, since we won't see the declarations otherwise.
2805 if (nt->named_object()->package() == NULL
2806 && nt->local_methods() != NULL)
2808 const Bindings* methods = nt->local_methods();
2809 for (Bindings::const_declarations_iterator p =
2810 methods->begin_declarations();
2811 p != methods->end_declarations();
2812 p++)
2814 if (p->second->is_function_declaration())
2816 Type* mt = p->second->func_declaration_value()->type();
2817 if (Type::traverse(mt, this) == TRAVERSE_EXIT)
2818 return TRAVERSE_EXIT;
2823 return TRAVERSE_SKIP_COMPONENTS;
2826 case Type::TYPE_STRUCT:
2827 // Traverse the field types first in case there is an embedded
2828 // field with methods that the struct should inherit.
2829 if (t->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
2830 return TRAVERSE_EXIT;
2831 t->struct_type()->finalize_methods(this->gogo_);
2832 return TRAVERSE_SKIP_COMPONENTS;
2834 default:
2835 break;
2838 return TRAVERSE_CONTINUE;
2841 // Finalize method lists and build stub methods for types.
2843 void
2844 Gogo::finalize_methods()
2846 Finalize_methods finalize(this);
2847 this->traverse(&finalize);
2850 // Set types for unspecified variables and constants.
2852 void
2853 Gogo::determine_types()
2855 Bindings* bindings = this->current_bindings();
2856 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2857 p != bindings->end_definitions();
2858 ++p)
2860 if ((*p)->is_function())
2861 (*p)->func_value()->determine_types();
2862 else if ((*p)->is_variable())
2863 (*p)->var_value()->determine_type();
2864 else if ((*p)->is_const())
2865 (*p)->const_value()->determine_type();
2867 // See if a variable requires us to build an initialization
2868 // function. We know that we will see all global variables
2869 // here.
2870 if (!this->need_init_fn_ && (*p)->is_variable())
2872 Variable* variable = (*p)->var_value();
2874 // If this is a global variable which requires runtime
2875 // initialization, we need an initialization function.
2876 if (!variable->is_global())
2878 else if (variable->init() == NULL)
2880 else if (variable->type()->interface_type() != NULL)
2881 this->need_init_fn_ = true;
2882 else if (variable->init()->is_constant())
2884 else if (!variable->init()->is_composite_literal())
2885 this->need_init_fn_ = true;
2886 else if (variable->init()->is_nonconstant_composite_literal())
2887 this->need_init_fn_ = true;
2889 // If this is a global variable which holds a pointer value,
2890 // then we need an initialization function to register it as a
2891 // GC root.
2892 if (variable->is_global() && variable->type()->has_pointer())
2893 this->need_init_fn_ = true;
2897 // Determine the types of constants in packages.
2898 for (Packages::const_iterator p = this->packages_.begin();
2899 p != this->packages_.end();
2900 ++p)
2901 p->second->determine_types();
2904 // Traversal class used for type checking.
2906 class Check_types_traverse : public Traverse
2908 public:
2909 Check_types_traverse(Gogo* gogo)
2910 : Traverse(traverse_variables
2911 | traverse_constants
2912 | traverse_functions
2913 | traverse_statements
2914 | traverse_expressions),
2915 gogo_(gogo)
2919 variable(Named_object*);
2922 constant(Named_object*, bool);
2925 function(Named_object*);
2928 statement(Block*, size_t* pindex, Statement*);
2931 expression(Expression**);
2933 private:
2934 // General IR.
2935 Gogo* gogo_;
2938 // Check that a variable initializer has the right type.
2941 Check_types_traverse::variable(Named_object* named_object)
2943 if (named_object->is_variable())
2945 Variable* var = named_object->var_value();
2947 // Give error if variable type is not defined.
2948 var->type()->base();
2950 Expression* init = var->init();
2951 std::string reason;
2952 if (init != NULL
2953 && !Type::are_assignable(var->type(), init->type(), &reason))
2955 if (reason.empty())
2956 error_at(var->location(), "incompatible type in initialization");
2957 else
2958 error_at(var->location(),
2959 "incompatible type in initialization (%s)",
2960 reason.c_str());
2961 var->clear_init();
2963 else if (!var->is_used()
2964 && !var->is_global()
2965 && !var->is_parameter()
2966 && !var->is_receiver()
2967 && !var->type()->is_error()
2968 && (init == NULL || !init->is_error_expression())
2969 && !Lex::is_invalid_identifier(named_object->name()))
2970 error_at(var->location(), "%qs declared and not used",
2971 named_object->message_name().c_str());
2973 return TRAVERSE_CONTINUE;
2976 // Check that a constant initializer has the right type.
2979 Check_types_traverse::constant(Named_object* named_object, bool)
2981 Named_constant* constant = named_object->const_value();
2982 Type* ctype = constant->type();
2983 if (ctype->integer_type() == NULL
2984 && ctype->float_type() == NULL
2985 && ctype->complex_type() == NULL
2986 && !ctype->is_boolean_type()
2987 && !ctype->is_string_type())
2989 if (ctype->is_nil_type())
2990 error_at(constant->location(), "const initializer cannot be nil");
2991 else if (!ctype->is_error())
2992 error_at(constant->location(), "invalid constant type");
2993 constant->set_error();
2995 else if (!constant->expr()->is_constant())
2997 error_at(constant->expr()->location(), "expression is not constant");
2998 constant->set_error();
3000 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
3001 NULL))
3003 error_at(constant->location(),
3004 "initialization expression has wrong type");
3005 constant->set_error();
3007 return TRAVERSE_CONTINUE;
3010 // There are no types to check in a function, but this is where we
3011 // issue warnings about labels which are defined but not referenced.
3014 Check_types_traverse::function(Named_object* no)
3016 no->func_value()->check_labels();
3017 return TRAVERSE_CONTINUE;
3020 // Check that types are valid in a statement.
3023 Check_types_traverse::statement(Block*, size_t*, Statement* s)
3025 s->check_types(this->gogo_);
3026 return TRAVERSE_CONTINUE;
3029 // Check that types are valid in an expression.
3032 Check_types_traverse::expression(Expression** expr)
3034 (*expr)->check_types(this->gogo_);
3035 return TRAVERSE_CONTINUE;
3038 // Check that types are valid.
3040 void
3041 Gogo::check_types()
3043 Check_types_traverse traverse(this);
3044 this->traverse(&traverse);
3047 // Check the types in a single block.
3049 void
3050 Gogo::check_types_in_block(Block* block)
3052 Check_types_traverse traverse(this);
3053 block->traverse(&traverse);
3056 // A traversal class used to find a single shortcut operator within an
3057 // expression.
3059 class Find_shortcut : public Traverse
3061 public:
3062 Find_shortcut()
3063 : Traverse(traverse_blocks
3064 | traverse_statements
3065 | traverse_expressions),
3066 found_(NULL)
3069 // A pointer to the expression which was found, or NULL if none was
3070 // found.
3071 Expression**
3072 found() const
3073 { return this->found_; }
3075 protected:
3077 block(Block*)
3078 { return TRAVERSE_SKIP_COMPONENTS; }
3081 statement(Block*, size_t*, Statement*)
3082 { return TRAVERSE_SKIP_COMPONENTS; }
3085 expression(Expression**);
3087 private:
3088 Expression** found_;
3091 // Find a shortcut expression.
3094 Find_shortcut::expression(Expression** pexpr)
3096 Expression* expr = *pexpr;
3097 Binary_expression* be = expr->binary_expression();
3098 if (be == NULL)
3099 return TRAVERSE_CONTINUE;
3100 Operator op = be->op();
3101 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
3102 return TRAVERSE_CONTINUE;
3103 go_assert(this->found_ == NULL);
3104 this->found_ = pexpr;
3105 return TRAVERSE_EXIT;
3108 // A traversal class used to turn shortcut operators into explicit if
3109 // statements.
3111 class Shortcuts : public Traverse
3113 public:
3114 Shortcuts(Gogo* gogo)
3115 : Traverse(traverse_variables
3116 | traverse_statements),
3117 gogo_(gogo)
3120 protected:
3122 variable(Named_object*);
3125 statement(Block*, size_t*, Statement*);
3127 private:
3128 // Convert a shortcut operator.
3129 Statement*
3130 convert_shortcut(Block* enclosing, Expression** pshortcut);
3132 // The IR.
3133 Gogo* gogo_;
3136 // Remove shortcut operators in a single statement.
3139 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
3141 // FIXME: This approach doesn't work for switch statements, because
3142 // we add the new statements before the whole switch when we need to
3143 // instead add them just before the switch expression. The right
3144 // fix is probably to lower switch statements with nonconstant cases
3145 // to a series of conditionals.
3146 if (s->switch_statement() != NULL)
3147 return TRAVERSE_CONTINUE;
3149 while (true)
3151 Find_shortcut find_shortcut;
3153 // If S is a variable declaration, then ordinary traversal won't
3154 // do anything. We want to explicitly traverse the
3155 // initialization expression if there is one.
3156 Variable_declaration_statement* vds = s->variable_declaration_statement();
3157 Expression* init = NULL;
3158 if (vds == NULL)
3159 s->traverse_contents(&find_shortcut);
3160 else
3162 init = vds->var()->var_value()->init();
3163 if (init == NULL)
3164 return TRAVERSE_CONTINUE;
3165 init->traverse(&init, &find_shortcut);
3167 Expression** pshortcut = find_shortcut.found();
3168 if (pshortcut == NULL)
3169 return TRAVERSE_CONTINUE;
3171 Statement* snew = this->convert_shortcut(block, pshortcut);
3172 block->insert_statement_before(*pindex, snew);
3173 ++*pindex;
3175 if (pshortcut == &init)
3176 vds->var()->var_value()->set_init(init);
3180 // Remove shortcut operators in the initializer of a global variable.
3183 Shortcuts::variable(Named_object* no)
3185 if (no->is_result_variable())
3186 return TRAVERSE_CONTINUE;
3187 Variable* var = no->var_value();
3188 Expression* init = var->init();
3189 if (!var->is_global() || init == NULL)
3190 return TRAVERSE_CONTINUE;
3192 while (true)
3194 Find_shortcut find_shortcut;
3195 init->traverse(&init, &find_shortcut);
3196 Expression** pshortcut = find_shortcut.found();
3197 if (pshortcut == NULL)
3198 return TRAVERSE_CONTINUE;
3200 Statement* snew = this->convert_shortcut(NULL, pshortcut);
3201 var->add_preinit_statement(this->gogo_, snew);
3202 if (pshortcut == &init)
3203 var->set_init(init);
3207 // Given an expression which uses a shortcut operator, return a
3208 // statement which implements it, and update *PSHORTCUT accordingly.
3210 Statement*
3211 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
3213 Binary_expression* shortcut = (*pshortcut)->binary_expression();
3214 Expression* left = shortcut->left();
3215 Expression* right = shortcut->right();
3216 Location loc = shortcut->location();
3218 Block* retblock = new Block(enclosing, loc);
3219 retblock->set_end_location(loc);
3221 Temporary_statement* ts = Statement::make_temporary(shortcut->type(),
3222 left, loc);
3223 retblock->add_statement(ts);
3225 Block* block = new Block(retblock, loc);
3226 block->set_end_location(loc);
3227 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
3228 Statement* assign = Statement::make_assignment(tmpref, right, loc);
3229 block->add_statement(assign);
3231 Expression* cond = Expression::make_temporary_reference(ts, loc);
3232 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
3233 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
3235 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
3236 loc);
3237 retblock->add_statement(if_statement);
3239 *pshortcut = Expression::make_temporary_reference(ts, loc);
3241 delete shortcut;
3243 // Now convert any shortcut operators in LEFT and RIGHT.
3244 Shortcuts shortcuts(this->gogo_);
3245 retblock->traverse(&shortcuts);
3247 return Statement::make_block_statement(retblock, loc);
3250 // Turn shortcut operators into explicit if statements. Doing this
3251 // considerably simplifies the order of evaluation rules.
3253 void
3254 Gogo::remove_shortcuts()
3256 Shortcuts shortcuts(this);
3257 this->traverse(&shortcuts);
3260 // A traversal class which finds all the expressions which must be
3261 // evaluated in order within a statement or larger expression. This
3262 // is used to implement the rules about order of evaluation.
3264 class Find_eval_ordering : public Traverse
3266 private:
3267 typedef std::vector<Expression**> Expression_pointers;
3269 public:
3270 Find_eval_ordering()
3271 : Traverse(traverse_blocks
3272 | traverse_statements
3273 | traverse_expressions),
3274 exprs_()
3277 size_t
3278 size() const
3279 { return this->exprs_.size(); }
3281 typedef Expression_pointers::const_iterator const_iterator;
3283 const_iterator
3284 begin() const
3285 { return this->exprs_.begin(); }
3287 const_iterator
3288 end() const
3289 { return this->exprs_.end(); }
3291 protected:
3293 block(Block*)
3294 { return TRAVERSE_SKIP_COMPONENTS; }
3297 statement(Block*, size_t*, Statement*)
3298 { return TRAVERSE_SKIP_COMPONENTS; }
3301 expression(Expression**);
3303 private:
3304 // A list of pointers to expressions with side-effects.
3305 Expression_pointers exprs_;
3308 // If an expression must be evaluated in order, put it on the list.
3311 Find_eval_ordering::expression(Expression** expression_pointer)
3313 // We have to look at subexpressions before this one.
3314 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
3315 return TRAVERSE_EXIT;
3316 if ((*expression_pointer)->must_eval_in_order())
3317 this->exprs_.push_back(expression_pointer);
3318 return TRAVERSE_SKIP_COMPONENTS;
3321 // A traversal class for ordering evaluations.
3323 class Order_eval : public Traverse
3325 public:
3326 Order_eval(Gogo* gogo)
3327 : Traverse(traverse_variables
3328 | traverse_statements),
3329 gogo_(gogo)
3333 variable(Named_object*);
3336 statement(Block*, size_t*, Statement*);
3338 private:
3339 // The IR.
3340 Gogo* gogo_;
3343 // Implement the order of evaluation rules for a statement.
3346 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
3348 // FIXME: This approach doesn't work for switch statements, because
3349 // we add the new statements before the whole switch when we need to
3350 // instead add them just before the switch expression. The right
3351 // fix is probably to lower switch statements with nonconstant cases
3352 // to a series of conditionals.
3353 if (s->switch_statement() != NULL)
3354 return TRAVERSE_CONTINUE;
3356 Find_eval_ordering find_eval_ordering;
3358 // If S is a variable declaration, then ordinary traversal won't do
3359 // anything. We want to explicitly traverse the initialization
3360 // expression if there is one.
3361 Variable_declaration_statement* vds = s->variable_declaration_statement();
3362 Expression* init = NULL;
3363 Expression* orig_init = NULL;
3364 if (vds == NULL)
3365 s->traverse_contents(&find_eval_ordering);
3366 else
3368 init = vds->var()->var_value()->init();
3369 if (init == NULL)
3370 return TRAVERSE_CONTINUE;
3371 orig_init = init;
3373 // It might seem that this could be
3374 // init->traverse_subexpressions. Unfortunately that can fail
3375 // in a case like
3376 // var err os.Error
3377 // newvar, err := call(arg())
3378 // Here newvar will have an init of call result 0 of
3379 // call(arg()). If we only traverse subexpressions, we will
3380 // only find arg(), and we won't bother to move anything out.
3381 // Then we get to the assignment to err, we will traverse the
3382 // whole statement, and this time we will find both call() and
3383 // arg(), and so we will move them out. This will cause them to
3384 // be put into temporary variables before the assignment to err
3385 // but after the declaration of newvar. To avoid that problem,
3386 // we traverse the entire expression here.
3387 Expression::traverse(&init, &find_eval_ordering);
3390 size_t c = find_eval_ordering.size();
3391 if (c == 0)
3392 return TRAVERSE_CONTINUE;
3394 // If there is only one expression with a side-effect, we can
3395 // usually leave it in place.
3396 if (c == 1)
3398 switch (s->classification())
3400 case Statement::STATEMENT_ASSIGNMENT:
3401 // For an assignment statement, we need to evaluate an
3402 // expression on the right hand side before we evaluate any
3403 // index expression on the left hand side, so for that case
3404 // we always move the expression. Otherwise we mishandle
3405 // m[0] = len(m) where m is a map.
3406 break;
3408 case Statement::STATEMENT_EXPRESSION:
3410 // If this is a call statement that doesn't return any
3411 // values, it will not have been counted as a value to
3412 // move. We need to move any subexpressions in case they
3413 // are themselves call statements that require passing a
3414 // closure.
3415 Expression* expr = s->expression_statement()->expr();
3416 if (expr->call_expression() != NULL
3417 && expr->call_expression()->result_count() == 0)
3418 break;
3419 return TRAVERSE_CONTINUE;
3422 default:
3423 // We can leave the expression in place.
3424 return TRAVERSE_CONTINUE;
3428 bool is_thunk = s->thunk_statement() != NULL;
3429 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3430 p != find_eval_ordering.end();
3431 ++p)
3433 Expression** pexpr = *p;
3435 // The last expression in a thunk will be the call passed to go
3436 // or defer, which we must not evaluate early.
3437 if (is_thunk && p + 1 == find_eval_ordering.end())
3438 break;
3440 Location loc = (*pexpr)->location();
3441 Statement* s;
3442 if ((*pexpr)->call_expression() == NULL
3443 || (*pexpr)->call_expression()->result_count() < 2)
3445 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3446 loc);
3447 s = ts;
3448 *pexpr = Expression::make_temporary_reference(ts, loc);
3450 else
3452 // A call expression which returns multiple results needs to
3453 // be handled specially. We can't create a temporary
3454 // because there is no type to give it. Any actual uses of
3455 // the values will be done via Call_result_expressions.
3456 s = Statement::make_statement(*pexpr, true);
3459 block->insert_statement_before(*pindex, s);
3460 ++*pindex;
3463 if (init != orig_init)
3464 vds->var()->var_value()->set_init(init);
3466 return TRAVERSE_CONTINUE;
3469 // Implement the order of evaluation rules for the initializer of a
3470 // global variable.
3473 Order_eval::variable(Named_object* no)
3475 if (no->is_result_variable())
3476 return TRAVERSE_CONTINUE;
3477 Variable* var = no->var_value();
3478 Expression* init = var->init();
3479 if (!var->is_global() || init == NULL)
3480 return TRAVERSE_CONTINUE;
3482 Find_eval_ordering find_eval_ordering;
3483 Expression::traverse(&init, &find_eval_ordering);
3485 if (find_eval_ordering.size() <= 1)
3487 // If there is only one expression with a side-effect, we can
3488 // leave it in place.
3489 return TRAVERSE_SKIP_COMPONENTS;
3492 Expression* orig_init = init;
3494 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
3495 p != find_eval_ordering.end();
3496 ++p)
3498 Expression** pexpr = *p;
3499 Location loc = (*pexpr)->location();
3500 Statement* s;
3501 if ((*pexpr)->call_expression() == NULL
3502 || (*pexpr)->call_expression()->result_count() < 2)
3504 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr,
3505 loc);
3506 s = ts;
3507 *pexpr = Expression::make_temporary_reference(ts, loc);
3509 else
3511 // A call expression which returns multiple results needs to
3512 // be handled specially.
3513 s = Statement::make_statement(*pexpr, true);
3515 var->add_preinit_statement(this->gogo_, s);
3518 if (init != orig_init)
3519 var->set_init(init);
3521 return TRAVERSE_SKIP_COMPONENTS;
3524 // Use temporary variables to implement the order of evaluation rules.
3526 void
3527 Gogo::order_evaluations()
3529 Order_eval order_eval(this);
3530 this->traverse(&order_eval);
3533 // Traversal to flatten parse tree after order of evaluation rules are applied.
3535 class Flatten : public Traverse
3537 public:
3538 Flatten(Gogo* gogo, Named_object* function)
3539 : Traverse(traverse_variables
3540 | traverse_functions
3541 | traverse_statements
3542 | traverse_expressions),
3543 gogo_(gogo), function_(function), inserter_()
3546 void
3547 set_inserter(const Statement_inserter* inserter)
3548 { this->inserter_ = *inserter; }
3551 variable(Named_object*);
3554 function(Named_object*);
3557 statement(Block*, size_t* pindex, Statement*);
3560 expression(Expression**);
3562 private:
3563 // General IR.
3564 Gogo* gogo_;
3565 // The function we are traversing.
3566 Named_object* function_;
3567 // Current statement inserter for use by expressions.
3568 Statement_inserter inserter_;
3571 // Flatten variables.
3574 Flatten::variable(Named_object* no)
3576 if (!no->is_variable())
3577 return TRAVERSE_CONTINUE;
3579 if (no->is_variable() && no->var_value()->is_global())
3581 // Global variables can have loops in their initialization
3582 // expressions. This is handled in flatten_init_expression.
3583 no->var_value()->flatten_init_expression(this->gogo_, this->function_,
3584 &this->inserter_);
3585 return TRAVERSE_CONTINUE;
3588 go_assert(!no->var_value()->has_pre_init());
3590 return TRAVERSE_SKIP_COMPONENTS;
3593 // Flatten the body of a function. Record the function while flattening it,
3594 // so that we can pass it down when flattening an expression.
3597 Flatten::function(Named_object* no)
3599 go_assert(this->function_ == NULL);
3600 this->function_ = no;
3601 int t = no->func_value()->traverse(this);
3602 this->function_ = NULL;
3604 if (t == TRAVERSE_EXIT)
3605 return t;
3606 return TRAVERSE_SKIP_COMPONENTS;
3609 // Flatten statement parse trees.
3612 Flatten::statement(Block* block, size_t* pindex, Statement* sorig)
3614 // Because we explicitly traverse the statement's contents
3615 // ourselves, we want to skip block statements here. There is
3616 // nothing to flatten in a block statement.
3617 if (sorig->is_block_statement())
3618 return TRAVERSE_CONTINUE;
3620 Statement_inserter hold_inserter(this->inserter_);
3621 this->inserter_ = Statement_inserter(block, pindex);
3623 // Flatten the expressions first.
3624 int t = sorig->traverse_contents(this);
3625 if (t == TRAVERSE_EXIT)
3627 this->inserter_ = hold_inserter;
3628 return t;
3631 // Keep flattening until nothing changes.
3632 Statement* s = sorig;
3633 while (true)
3635 Statement* snew = s->flatten(this->gogo_, this->function_, block,
3636 &this->inserter_);
3637 if (snew == s)
3638 break;
3639 s = snew;
3640 t = s->traverse_contents(this);
3641 if (t == TRAVERSE_EXIT)
3643 this->inserter_ = hold_inserter;
3644 return t;
3648 if (s != sorig)
3649 block->replace_statement(*pindex, s);
3651 this->inserter_ = hold_inserter;
3652 return TRAVERSE_SKIP_COMPONENTS;
3655 // Flatten expression parse trees.
3658 Flatten::expression(Expression** pexpr)
3660 // Keep flattening until nothing changes.
3661 while (true)
3663 Expression* e = *pexpr;
3664 if (e->traverse_subexpressions(this) == TRAVERSE_EXIT)
3665 return TRAVERSE_EXIT;
3667 Expression* enew = e->flatten(this->gogo_, this->function_,
3668 &this->inserter_);
3669 if (enew == e)
3670 break;
3671 *pexpr = enew;
3673 return TRAVERSE_SKIP_COMPONENTS;
3676 // Flatten a block.
3678 void
3679 Gogo::flatten_block(Named_object* function, Block* block)
3681 Flatten flatten(this, function);
3682 block->traverse(&flatten);
3685 // Flatten an expression. INSERTER may be NULL, in which case the
3686 // expression had better not need to create any temporaries.
3688 void
3689 Gogo::flatten_expression(Named_object* function, Statement_inserter* inserter,
3690 Expression** pexpr)
3692 Flatten flatten(this, function);
3693 if (inserter != NULL)
3694 flatten.set_inserter(inserter);
3695 flatten.expression(pexpr);
3698 void
3699 Gogo::flatten()
3701 Flatten flatten(this, NULL);
3702 this->traverse(&flatten);
3705 // Traversal to convert calls to the predeclared recover function to
3706 // pass in an argument indicating whether it can recover from a panic
3707 // or not.
3709 class Convert_recover : public Traverse
3711 public:
3712 Convert_recover(Named_object* arg)
3713 : Traverse(traverse_expressions),
3714 arg_(arg)
3717 protected:
3719 expression(Expression**);
3721 private:
3722 // The argument to pass to the function.
3723 Named_object* arg_;
3726 // Convert calls to recover.
3729 Convert_recover::expression(Expression** pp)
3731 Call_expression* ce = (*pp)->call_expression();
3732 if (ce != NULL && ce->is_recover_call())
3733 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
3734 ce->location()));
3735 return TRAVERSE_CONTINUE;
3738 // Traversal for build_recover_thunks.
3740 class Build_recover_thunks : public Traverse
3742 public:
3743 Build_recover_thunks(Gogo* gogo)
3744 : Traverse(traverse_functions),
3745 gogo_(gogo)
3749 function(Named_object*);
3751 private:
3752 Expression*
3753 can_recover_arg(Location);
3755 // General IR.
3756 Gogo* gogo_;
3759 // If this function calls recover, turn it into a thunk.
3762 Build_recover_thunks::function(Named_object* orig_no)
3764 Function* orig_func = orig_no->func_value();
3765 if (!orig_func->calls_recover()
3766 || orig_func->is_recover_thunk()
3767 || orig_func->has_recover_thunk())
3768 return TRAVERSE_CONTINUE;
3770 Gogo* gogo = this->gogo_;
3771 Location location = orig_func->location();
3773 static int count;
3774 char buf[50];
3776 Function_type* orig_fntype = orig_func->type();
3777 Typed_identifier_list* new_params = new Typed_identifier_list();
3778 std::string receiver_name;
3779 if (orig_fntype->is_method())
3781 const Typed_identifier* receiver = orig_fntype->receiver();
3782 snprintf(buf, sizeof buf, "rt.%u", count);
3783 ++count;
3784 receiver_name = buf;
3785 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
3786 receiver->location()));
3788 const Typed_identifier_list* orig_params = orig_fntype->parameters();
3789 if (orig_params != NULL && !orig_params->empty())
3791 for (Typed_identifier_list::const_iterator p = orig_params->begin();
3792 p != orig_params->end();
3793 ++p)
3795 snprintf(buf, sizeof buf, "pt.%u", count);
3796 ++count;
3797 new_params->push_back(Typed_identifier(buf, p->type(),
3798 p->location()));
3801 snprintf(buf, sizeof buf, "pr.%u", count);
3802 ++count;
3803 std::string can_recover_name = buf;
3804 new_params->push_back(Typed_identifier(can_recover_name,
3805 Type::lookup_bool_type(),
3806 orig_fntype->location()));
3808 const Typed_identifier_list* orig_results = orig_fntype->results();
3809 Typed_identifier_list* new_results;
3810 if (orig_results == NULL || orig_results->empty())
3811 new_results = NULL;
3812 else
3814 new_results = new Typed_identifier_list();
3815 for (Typed_identifier_list::const_iterator p = orig_results->begin();
3816 p != orig_results->end();
3817 ++p)
3818 new_results->push_back(Typed_identifier("", p->type(), p->location()));
3821 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
3822 new_results,
3823 orig_fntype->location());
3824 if (orig_fntype->is_varargs())
3825 new_fntype->set_is_varargs();
3827 std::string name = orig_no->name();
3828 if (orig_fntype->is_method())
3829 name += "$" + orig_fntype->receiver()->type()->mangled_name(gogo);
3830 name += "$recover";
3831 Named_object *new_no = gogo->start_function(name, new_fntype, false,
3832 location);
3833 Function *new_func = new_no->func_value();
3834 if (orig_func->enclosing() != NULL)
3835 new_func->set_enclosing(orig_func->enclosing());
3837 // We build the code for the original function attached to the new
3838 // function, and then swap the original and new function bodies.
3839 // This means that existing references to the original function will
3840 // then refer to the new function. That makes this code a little
3841 // confusing, in that the reference to NEW_NO really refers to the
3842 // other function, not the one we are building.
3844 Expression* closure = NULL;
3845 if (orig_func->needs_closure())
3847 // For the new function we are creating, declare a new parameter
3848 // variable NEW_CLOSURE_NO and set it to be the closure variable
3849 // of the function. This will be set to the closure value
3850 // passed in by the caller. Then pass a reference to this
3851 // variable as the closure value when calling the original
3852 // function. In other words, simply pass the closure value
3853 // through the thunk we are creating.
3854 Named_object* orig_closure_no = orig_func->closure_var();
3855 Variable* orig_closure_var = orig_closure_no->var_value();
3856 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
3857 false, false, location);
3858 snprintf(buf, sizeof buf, "closure.%u", count);
3859 ++count;
3860 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
3861 new_var);
3862 new_func->set_closure_var(new_closure_no);
3863 closure = Expression::make_var_reference(new_closure_no, location);
3866 Expression* fn = Expression::make_func_reference(new_no, closure, location);
3868 Expression_list* args = new Expression_list();
3869 if (new_params != NULL)
3871 // Note that we skip the last parameter, which is the boolean
3872 // indicating whether recover can succed.
3873 for (Typed_identifier_list::const_iterator p = new_params->begin();
3874 p + 1 != new_params->end();
3875 ++p)
3877 Named_object* p_no = gogo->lookup(p->name(), NULL);
3878 go_assert(p_no != NULL
3879 && p_no->is_variable()
3880 && p_no->var_value()->is_parameter());
3881 args->push_back(Expression::make_var_reference(p_no, location));
3884 args->push_back(this->can_recover_arg(location));
3886 gogo->start_block(location);
3888 Call_expression* call = Expression::make_call(fn, args, false, location);
3890 // Any varargs call has already been lowered.
3891 call->set_varargs_are_lowered();
3893 Statement* s = Statement::make_return_from_call(call, location);
3894 s->determine_types();
3895 gogo->add_statement(s);
3897 Block* b = gogo->finish_block(location);
3899 gogo->add_block(b, location);
3901 // Lower the call in case it returns multiple results.
3902 gogo->lower_block(new_no, b);
3904 gogo->finish_function(location);
3906 // Swap the function bodies and types.
3907 new_func->swap_for_recover(orig_func);
3908 orig_func->set_is_recover_thunk();
3909 new_func->set_calls_recover();
3910 new_func->set_has_recover_thunk();
3912 Bindings* orig_bindings = orig_func->block()->bindings();
3913 Bindings* new_bindings = new_func->block()->bindings();
3914 if (orig_fntype->is_method())
3916 // We changed the receiver to be a regular parameter. We have
3917 // to update the binding accordingly in both functions.
3918 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
3919 go_assert(orig_rec_no != NULL
3920 && orig_rec_no->is_variable()
3921 && !orig_rec_no->var_value()->is_receiver());
3922 orig_rec_no->var_value()->set_is_receiver();
3924 std::string new_receiver_name(orig_fntype->receiver()->name());
3925 if (new_receiver_name.empty())
3927 // Find the receiver. It was named "r.NNN" in
3928 // Gogo::start_function.
3929 for (Bindings::const_definitions_iterator p =
3930 new_bindings->begin_definitions();
3931 p != new_bindings->end_definitions();
3932 ++p)
3934 const std::string& pname((*p)->name());
3935 if (pname[0] == 'r' && pname[1] == '.')
3937 new_receiver_name = pname;
3938 break;
3941 go_assert(!new_receiver_name.empty());
3943 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
3944 if (new_rec_no == NULL)
3945 go_assert(saw_errors());
3946 else
3948 go_assert(new_rec_no->is_variable()
3949 && new_rec_no->var_value()->is_receiver());
3950 new_rec_no->var_value()->set_is_not_receiver();
3954 // Because we flipped blocks but not types, the can_recover
3955 // parameter appears in the (now) old bindings as a parameter.
3956 // Change it to a local variable, whereupon it will be discarded.
3957 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
3958 go_assert(can_recover_no != NULL
3959 && can_recover_no->is_variable()
3960 && can_recover_no->var_value()->is_parameter());
3961 orig_bindings->remove_binding(can_recover_no);
3963 // Add the can_recover argument to the (now) new bindings, and
3964 // attach it to any recover statements.
3965 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
3966 false, true, false, location);
3967 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
3968 can_recover_var);
3969 Convert_recover convert_recover(can_recover_no);
3970 new_func->traverse(&convert_recover);
3972 // Update the function pointers in any named results.
3973 new_func->update_result_variables();
3974 orig_func->update_result_variables();
3976 return TRAVERSE_CONTINUE;
3979 // Return the expression to pass for the .can_recover parameter to the
3980 // new function. This indicates whether a call to recover may return
3981 // non-nil. The expression is
3982 // __go_can_recover(__builtin_return_address()).
3984 Expression*
3985 Build_recover_thunks::can_recover_arg(Location location)
3987 static Named_object* builtin_return_address;
3988 if (builtin_return_address == NULL)
3990 const Location bloc = Linemap::predeclared_location();
3992 Typed_identifier_list* param_types = new Typed_identifier_list();
3993 Type* uint_type = Type::lookup_integer_type("uint");
3994 param_types->push_back(Typed_identifier("l", uint_type, bloc));
3996 Typed_identifier_list* return_types = new Typed_identifier_list();
3997 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
3998 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
4000 Function_type* fntype = Type::make_function_type(NULL, param_types,
4001 return_types, bloc);
4002 builtin_return_address =
4003 Named_object::make_function_declaration("__builtin_return_address",
4004 NULL, fntype, bloc);
4005 const char* n = "__builtin_return_address";
4006 builtin_return_address->func_declaration_value()->set_asm_name(n);
4009 static Named_object* can_recover;
4010 if (can_recover == NULL)
4012 const Location bloc = Linemap::predeclared_location();
4013 Typed_identifier_list* param_types = new Typed_identifier_list();
4014 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4015 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
4016 Type* boolean_type = Type::lookup_bool_type();
4017 Typed_identifier_list* results = new Typed_identifier_list();
4018 results->push_back(Typed_identifier("", boolean_type, bloc));
4019 Function_type* fntype = Type::make_function_type(NULL, param_types,
4020 results, bloc);
4021 can_recover = Named_object::make_function_declaration("__go_can_recover",
4022 NULL, fntype,
4023 bloc);
4024 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
4027 Expression* fn = Expression::make_func_reference(builtin_return_address,
4028 NULL, location);
4030 mpz_t zval;
4031 mpz_init_set_ui(zval, 0UL);
4032 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
4033 mpz_clear(zval);
4034 Expression_list *args = new Expression_list();
4035 args->push_back(zexpr);
4037 Expression* call = Expression::make_call(fn, args, false, location);
4039 args = new Expression_list();
4040 args->push_back(call);
4042 fn = Expression::make_func_reference(can_recover, NULL, location);
4043 return Expression::make_call(fn, args, false, location);
4046 // Build thunks for functions which call recover. We build a new
4047 // function with an extra parameter, which is whether a call to
4048 // recover can succeed. We then move the body of this function to
4049 // that one. We then turn this function into a thunk which calls the
4050 // new one, passing the value of
4051 // __go_can_recover(__builtin_return_address()). The function will be
4052 // marked as not splitting the stack. This will cooperate with the
4053 // implementation of defer to make recover do the right thing.
4055 void
4056 Gogo::build_recover_thunks()
4058 Build_recover_thunks build_recover_thunks(this);
4059 this->traverse(&build_recover_thunks);
4062 // Build a call to the runtime error function.
4064 Expression*
4065 Gogo::runtime_error(int code, Location location)
4067 Type* int32_type = Type::lookup_integer_type("int32");
4068 mpz_t val;
4069 mpz_init_set_ui(val, code);
4070 Expression* code_expr = Expression::make_integer(&val, int32_type, location);
4071 mpz_clear(val);
4072 return Runtime::make_call(Runtime::RUNTIME_ERROR, location, 1, code_expr);
4075 // Look for named types to see whether we need to create an interface
4076 // method table.
4078 class Build_method_tables : public Traverse
4080 public:
4081 Build_method_tables(Gogo* gogo,
4082 const std::vector<Interface_type*>& interfaces)
4083 : Traverse(traverse_types),
4084 gogo_(gogo), interfaces_(interfaces)
4088 type(Type*);
4090 private:
4091 // The IR.
4092 Gogo* gogo_;
4093 // A list of locally defined interfaces which have hidden methods.
4094 const std::vector<Interface_type*>& interfaces_;
4097 // Build all required interface method tables for types. We need to
4098 // ensure that we have an interface method table for every interface
4099 // which has a hidden method, for every named type which implements
4100 // that interface. Normally we can just build interface method tables
4101 // as we need them. However, in some cases we can require an
4102 // interface method table for an interface defined in a different
4103 // package for a type defined in that package. If that interface and
4104 // type both use a hidden method, that is OK. However, we will not be
4105 // able to build that interface method table when we need it, because
4106 // the type's hidden method will be static. So we have to build it
4107 // here, and just refer it from other packages as needed.
4109 void
4110 Gogo::build_interface_method_tables()
4112 if (saw_errors())
4113 return;
4115 std::vector<Interface_type*> hidden_interfaces;
4116 hidden_interfaces.reserve(this->interface_types_.size());
4117 for (std::vector<Interface_type*>::const_iterator pi =
4118 this->interface_types_.begin();
4119 pi != this->interface_types_.end();
4120 ++pi)
4122 const Typed_identifier_list* methods = (*pi)->methods();
4123 if (methods == NULL)
4124 continue;
4125 for (Typed_identifier_list::const_iterator pm = methods->begin();
4126 pm != methods->end();
4127 ++pm)
4129 if (Gogo::is_hidden_name(pm->name()))
4131 hidden_interfaces.push_back(*pi);
4132 break;
4137 if (!hidden_interfaces.empty())
4139 // Now traverse the tree looking for all named types.
4140 Build_method_tables bmt(this, hidden_interfaces);
4141 this->traverse(&bmt);
4144 // We no longer need the list of interfaces.
4146 this->interface_types_.clear();
4149 // This is called for each type. For a named type, for each of the
4150 // interfaces with hidden methods that it implements, create the
4151 // method table.
4154 Build_method_tables::type(Type* type)
4156 Named_type* nt = type->named_type();
4157 Struct_type* st = type->struct_type();
4158 if (nt != NULL || st != NULL)
4160 Translate_context context(this->gogo_, NULL, NULL, NULL);
4161 for (std::vector<Interface_type*>::const_iterator p =
4162 this->interfaces_.begin();
4163 p != this->interfaces_.end();
4164 ++p)
4166 // We ask whether a pointer to the named type implements the
4167 // interface, because a pointer can implement more methods
4168 // than a value.
4169 if (nt != NULL)
4171 if ((*p)->implements_interface(Type::make_pointer_type(nt),
4172 NULL))
4174 nt->interface_method_table(*p, false)->get_backend(&context);
4175 nt->interface_method_table(*p, true)->get_backend(&context);
4178 else
4180 if ((*p)->implements_interface(Type::make_pointer_type(st),
4181 NULL))
4183 st->interface_method_table(*p, false)->get_backend(&context);
4184 st->interface_method_table(*p, true)->get_backend(&context);
4189 return TRAVERSE_CONTINUE;
4192 // Return an expression which allocates memory to hold values of type TYPE.
4194 Expression*
4195 Gogo::allocate_memory(Type* type, Location location)
4197 Btype* btype = type->get_backend(this);
4198 size_t size = this->backend()->type_size(btype);
4199 mpz_t size_val;
4200 mpz_init_set_ui(size_val, size);
4201 Type* uintptr = Type::lookup_integer_type("uintptr");
4202 Expression* size_expr =
4203 Expression::make_integer(&size_val, uintptr, location);
4205 // If the package imports unsafe, then it may play games with
4206 // pointers that look like integers.
4207 bool use_new_pointers = this->imported_unsafe_ || type->has_pointer();
4208 return Runtime::make_call((use_new_pointers
4209 ? Runtime::NEW
4210 : Runtime::NEW_NOPOINTERS),
4211 location, 1, size_expr);
4214 // Traversal class used to check for return statements.
4216 class Check_return_statements_traverse : public Traverse
4218 public:
4219 Check_return_statements_traverse()
4220 : Traverse(traverse_functions)
4224 function(Named_object*);
4227 // Check that a function has a return statement if it needs one.
4230 Check_return_statements_traverse::function(Named_object* no)
4232 Function* func = no->func_value();
4233 const Function_type* fntype = func->type();
4234 const Typed_identifier_list* results = fntype->results();
4236 // We only need a return statement if there is a return value.
4237 if (results == NULL || results->empty())
4238 return TRAVERSE_CONTINUE;
4240 if (func->block()->may_fall_through())
4241 error_at(func->block()->end_location(),
4242 "missing return at end of function");
4244 return TRAVERSE_CONTINUE;
4247 // Check return statements.
4249 void
4250 Gogo::check_return_statements()
4252 Check_return_statements_traverse traverse;
4253 this->traverse(&traverse);
4256 // Work out the package priority. It is one more than the maximum
4257 // priority of an imported package.
4260 Gogo::package_priority() const
4262 int priority = 0;
4263 for (Packages::const_iterator p = this->packages_.begin();
4264 p != this->packages_.end();
4265 ++p)
4266 if (p->second->priority() > priority)
4267 priority = p->second->priority();
4268 return priority + 1;
4271 // Export identifiers as requested.
4273 void
4274 Gogo::do_exports()
4276 // For now we always stream to a section. Later we may want to
4277 // support streaming to a separate file.
4278 Stream_to_section stream;
4280 Export exp(&stream);
4281 exp.register_builtin_types(this);
4282 exp.export_globals(this->package_name(),
4283 this->pkgpath(),
4284 this->package_priority(),
4285 this->imports_,
4286 (this->need_init_fn_ && !this->is_main_package()
4287 ? this->get_init_fn_name()
4288 : ""),
4289 this->imported_init_fns_,
4290 this->package_->bindings());
4293 // Find the blocks in order to convert named types defined in blocks.
4295 class Convert_named_types : public Traverse
4297 public:
4298 Convert_named_types(Gogo* gogo)
4299 : Traverse(traverse_blocks),
4300 gogo_(gogo)
4303 protected:
4305 block(Block* block);
4307 private:
4308 Gogo* gogo_;
4312 Convert_named_types::block(Block* block)
4314 this->gogo_->convert_named_types_in_bindings(block->bindings());
4315 return TRAVERSE_CONTINUE;
4318 // Convert all named types to the backend representation. Since named
4319 // types can refer to other types, this needs to be done in the right
4320 // sequence, which is handled by Named_type::convert. Here we arrange
4321 // to call that for each named type.
4323 void
4324 Gogo::convert_named_types()
4326 this->convert_named_types_in_bindings(this->globals_);
4327 for (Packages::iterator p = this->packages_.begin();
4328 p != this->packages_.end();
4329 ++p)
4331 Package* package = p->second;
4332 this->convert_named_types_in_bindings(package->bindings());
4335 Convert_named_types cnt(this);
4336 this->traverse(&cnt);
4338 // Make all the builtin named types used for type descriptors, and
4339 // then convert them. They will only be written out if they are
4340 // needed.
4341 Type::make_type_descriptor_type();
4342 Type::make_type_descriptor_ptr_type();
4343 Function_type::make_function_type_descriptor_type();
4344 Pointer_type::make_pointer_type_descriptor_type();
4345 Struct_type::make_struct_type_descriptor_type();
4346 Array_type::make_array_type_descriptor_type();
4347 Array_type::make_slice_type_descriptor_type();
4348 Map_type::make_map_type_descriptor_type();
4349 Map_type::make_map_descriptor_type();
4350 Channel_type::make_chan_type_descriptor_type();
4351 Interface_type::make_interface_type_descriptor_type();
4352 Expression::make_func_descriptor_type();
4353 Type::convert_builtin_named_types(this);
4355 Runtime::convert_types(this);
4357 this->named_types_are_converted_ = true;
4360 // Convert all names types in a set of bindings.
4362 void
4363 Gogo::convert_named_types_in_bindings(Bindings* bindings)
4365 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4366 p != bindings->end_definitions();
4367 ++p)
4369 if ((*p)->is_type())
4370 (*p)->type_value()->convert(this);
4374 // Class Function.
4376 Function::Function(Function_type* type, Function* enclosing, Block* block,
4377 Location location)
4378 : type_(type), enclosing_(enclosing), results_(NULL),
4379 closure_var_(NULL), block_(block), location_(location), labels_(),
4380 local_type_count_(0), descriptor_(NULL), fndecl_(NULL), defer_stack_(NULL),
4381 is_sink_(false), results_are_named_(false), nointerface_(false),
4382 is_unnamed_type_stub_method_(false), calls_recover_(false),
4383 is_recover_thunk_(false), has_recover_thunk_(false),
4384 in_unique_section_(false)
4388 // Create the named result variables.
4390 void
4391 Function::create_result_variables(Gogo* gogo)
4393 const Typed_identifier_list* results = this->type_->results();
4394 if (results == NULL || results->empty())
4395 return;
4397 if (!results->front().name().empty())
4398 this->results_are_named_ = true;
4400 this->results_ = new Results();
4401 this->results_->reserve(results->size());
4403 Block* block = this->block_;
4404 int index = 0;
4405 for (Typed_identifier_list::const_iterator p = results->begin();
4406 p != results->end();
4407 ++p, ++index)
4409 std::string name = p->name();
4410 if (name.empty() || Gogo::is_sink_name(name))
4412 static int result_counter;
4413 char buf[100];
4414 snprintf(buf, sizeof buf, "$ret%d", result_counter);
4415 ++result_counter;
4416 name = gogo->pack_hidden_name(buf, false);
4418 Result_variable* result = new Result_variable(p->type(), this, index,
4419 p->location());
4420 Named_object* no = block->bindings()->add_result_variable(name, result);
4421 if (no->is_result_variable())
4422 this->results_->push_back(no);
4423 else
4425 static int dummy_result_count;
4426 char buf[100];
4427 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
4428 ++dummy_result_count;
4429 name = gogo->pack_hidden_name(buf, false);
4430 no = block->bindings()->add_result_variable(name, result);
4431 go_assert(no->is_result_variable());
4432 this->results_->push_back(no);
4437 // Update the named result variables when cloning a function which
4438 // calls recover.
4440 void
4441 Function::update_result_variables()
4443 if (this->results_ == NULL)
4444 return;
4446 for (Results::iterator p = this->results_->begin();
4447 p != this->results_->end();
4448 ++p)
4449 (*p)->result_var_value()->set_function(this);
4452 // Return the closure variable, creating it if necessary.
4454 Named_object*
4455 Function::closure_var()
4457 if (this->closure_var_ == NULL)
4459 go_assert(this->descriptor_ == NULL);
4460 // We don't know the type of the variable yet. We add fields as
4461 // we find them.
4462 Location loc = this->type_->location();
4463 Struct_field_list* sfl = new Struct_field_list;
4464 Type* struct_type = Type::make_struct_type(sfl, loc);
4465 Variable* var = new Variable(Type::make_pointer_type(struct_type),
4466 NULL, false, false, false, loc);
4467 var->set_is_used();
4468 this->closure_var_ = Named_object::make_variable("$closure", NULL, var);
4469 // Note that the new variable is not in any binding contour.
4471 return this->closure_var_;
4474 // Set the type of the closure variable.
4476 void
4477 Function::set_closure_type()
4479 if (this->closure_var_ == NULL)
4480 return;
4481 Named_object* closure = this->closure_var_;
4482 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
4484 // The first field of a closure is always a pointer to the function
4485 // code.
4486 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
4487 st->push_field(Struct_field(Typed_identifier(".$f", voidptr_type,
4488 this->location_)));
4490 unsigned int index = 1;
4491 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
4492 p != this->closure_fields_.end();
4493 ++p, ++index)
4495 Named_object* no = p->first;
4496 char buf[20];
4497 snprintf(buf, sizeof buf, "%u", index);
4498 std::string n = no->name() + buf;
4499 Type* var_type;
4500 if (no->is_variable())
4501 var_type = no->var_value()->type();
4502 else
4503 var_type = no->result_var_value()->type();
4504 Type* field_type = Type::make_pointer_type(var_type);
4505 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
4509 // Return whether this function is a method.
4511 bool
4512 Function::is_method() const
4514 return this->type_->is_method();
4517 // Add a label definition.
4519 Label*
4520 Function::add_label_definition(Gogo* gogo, const std::string& label_name,
4521 Location location)
4523 Label* lnull = NULL;
4524 std::pair<Labels::iterator, bool> ins =
4525 this->labels_.insert(std::make_pair(label_name, lnull));
4526 Label* label;
4527 if (ins.second)
4529 // This is a new label.
4530 label = new Label(label_name);
4531 ins.first->second = label;
4533 else
4535 // The label was already in the hash table.
4536 label = ins.first->second;
4537 if (label->is_defined())
4539 error_at(location, "label %qs already defined",
4540 Gogo::message_name(label_name).c_str());
4541 inform(label->location(), "previous definition of %qs was here",
4542 Gogo::message_name(label_name).c_str());
4543 return new Label(label_name);
4547 label->define(location, gogo->bindings_snapshot(location));
4549 // Issue any errors appropriate for any previous goto's to this
4550 // label.
4551 const std::vector<Bindings_snapshot*>& refs(label->refs());
4552 for (std::vector<Bindings_snapshot*>::const_iterator p = refs.begin();
4553 p != refs.end();
4554 ++p)
4555 (*p)->check_goto_to(gogo->current_block());
4556 label->clear_refs();
4558 return label;
4561 // Add a reference to a label.
4563 Label*
4564 Function::add_label_reference(Gogo* gogo, const std::string& label_name,
4565 Location location, bool issue_goto_errors)
4567 Label* lnull = NULL;
4568 std::pair<Labels::iterator, bool> ins =
4569 this->labels_.insert(std::make_pair(label_name, lnull));
4570 Label* label;
4571 if (!ins.second)
4573 // The label was already in the hash table.
4574 label = ins.first->second;
4576 else
4578 go_assert(ins.first->second == NULL);
4579 label = new Label(label_name);
4580 ins.first->second = label;
4583 label->set_is_used();
4585 if (issue_goto_errors)
4587 Bindings_snapshot* snapshot = label->snapshot();
4588 if (snapshot != NULL)
4589 snapshot->check_goto_from(gogo->current_block(), location);
4590 else
4591 label->add_snapshot_ref(gogo->bindings_snapshot(location));
4594 return label;
4597 // Warn about labels that are defined but not used.
4599 void
4600 Function::check_labels() const
4602 for (Labels::const_iterator p = this->labels_.begin();
4603 p != this->labels_.end();
4604 p++)
4606 Label* label = p->second;
4607 if (!label->is_used())
4608 error_at(label->location(), "label %qs defined and not used",
4609 Gogo::message_name(label->name()).c_str());
4613 // Swap one function with another. This is used when building the
4614 // thunk we use to call a function which calls recover. It may not
4615 // work for any other case.
4617 void
4618 Function::swap_for_recover(Function *x)
4620 go_assert(this->enclosing_ == x->enclosing_);
4621 std::swap(this->results_, x->results_);
4622 std::swap(this->closure_var_, x->closure_var_);
4623 std::swap(this->block_, x->block_);
4624 go_assert(this->location_ == x->location_);
4625 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
4626 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
4629 // Traverse the tree.
4632 Function::traverse(Traverse* traverse)
4634 unsigned int traverse_mask = traverse->traverse_mask();
4636 if ((traverse_mask
4637 & (Traverse::traverse_types | Traverse::traverse_expressions))
4638 != 0)
4640 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
4641 return TRAVERSE_EXIT;
4644 // FIXME: We should check traverse_functions here if nested
4645 // functions are stored in block bindings.
4646 if (this->block_ != NULL
4647 && (traverse_mask
4648 & (Traverse::traverse_variables
4649 | Traverse::traverse_constants
4650 | Traverse::traverse_blocks
4651 | Traverse::traverse_statements
4652 | Traverse::traverse_expressions
4653 | Traverse::traverse_types)) != 0)
4655 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
4656 return TRAVERSE_EXIT;
4659 return TRAVERSE_CONTINUE;
4662 // Work out types for unspecified variables and constants.
4664 void
4665 Function::determine_types()
4667 if (this->block_ != NULL)
4668 this->block_->determine_types();
4671 // Return the function descriptor, the value you get when you refer to
4672 // the function in Go code without calling it.
4674 Expression*
4675 Function::descriptor(Gogo*, Named_object* no)
4677 go_assert(!this->is_method());
4678 go_assert(this->closure_var_ == NULL);
4679 if (this->descriptor_ == NULL)
4680 this->descriptor_ = Expression::make_func_descriptor(no);
4681 return this->descriptor_;
4684 // Get a pointer to the variable representing the defer stack for this
4685 // function, making it if necessary. The value of the variable is set
4686 // by the runtime routines to true if the function is returning,
4687 // rather than panicing through. A pointer to this variable is used
4688 // as a marker for the functions on the defer stack associated with
4689 // this function. A function-specific variable permits inlining a
4690 // function which uses defer.
4692 Expression*
4693 Function::defer_stack(Location location)
4695 if (this->defer_stack_ == NULL)
4697 Type* t = Type::lookup_bool_type();
4698 Expression* n = Expression::make_boolean(false, location);
4699 this->defer_stack_ = Statement::make_temporary(t, n, location);
4700 this->defer_stack_->set_is_address_taken();
4702 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
4703 location);
4704 return Expression::make_unary(OPERATOR_AND, ref, location);
4707 // Export the function.
4709 void
4710 Function::export_func(Export* exp, const std::string& name) const
4712 Function::export_func_with_type(exp, name, this->type_);
4715 // Export a function with a type.
4717 void
4718 Function::export_func_with_type(Export* exp, const std::string& name,
4719 const Function_type* fntype)
4721 exp->write_c_string("func ");
4723 if (fntype->is_method())
4725 exp->write_c_string("(");
4726 const Typed_identifier* receiver = fntype->receiver();
4727 exp->write_name(receiver->name());
4728 exp->write_c_string(" ");
4729 exp->write_type(receiver->type());
4730 exp->write_c_string(") ");
4733 exp->write_string(name);
4735 exp->write_c_string(" (");
4736 const Typed_identifier_list* parameters = fntype->parameters();
4737 if (parameters != NULL)
4739 bool is_varargs = fntype->is_varargs();
4740 bool first = true;
4741 for (Typed_identifier_list::const_iterator p = parameters->begin();
4742 p != parameters->end();
4743 ++p)
4745 if (first)
4746 first = false;
4747 else
4748 exp->write_c_string(", ");
4749 exp->write_name(p->name());
4750 exp->write_c_string(" ");
4751 if (!is_varargs || p + 1 != parameters->end())
4752 exp->write_type(p->type());
4753 else
4755 exp->write_c_string("...");
4756 exp->write_type(p->type()->array_type()->element_type());
4760 exp->write_c_string(")");
4762 const Typed_identifier_list* results = fntype->results();
4763 if (results != NULL)
4765 if (results->size() == 1 && results->begin()->name().empty())
4767 exp->write_c_string(" ");
4768 exp->write_type(results->begin()->type());
4770 else
4772 exp->write_c_string(" (");
4773 bool first = true;
4774 for (Typed_identifier_list::const_iterator p = results->begin();
4775 p != results->end();
4776 ++p)
4778 if (first)
4779 first = false;
4780 else
4781 exp->write_c_string(", ");
4782 exp->write_name(p->name());
4783 exp->write_c_string(" ");
4784 exp->write_type(p->type());
4786 exp->write_c_string(")");
4789 exp->write_c_string(";\n");
4792 // Import a function.
4794 void
4795 Function::import_func(Import* imp, std::string* pname,
4796 Typed_identifier** preceiver,
4797 Typed_identifier_list** pparameters,
4798 Typed_identifier_list** presults,
4799 bool* is_varargs)
4801 imp->require_c_string("func ");
4803 *preceiver = NULL;
4804 if (imp->peek_char() == '(')
4806 imp->require_c_string("(");
4807 std::string name = imp->read_name();
4808 imp->require_c_string(" ");
4809 Type* rtype = imp->read_type();
4810 *preceiver = new Typed_identifier(name, rtype, imp->location());
4811 imp->require_c_string(") ");
4814 *pname = imp->read_identifier();
4816 Typed_identifier_list* parameters;
4817 *is_varargs = false;
4818 imp->require_c_string(" (");
4819 if (imp->peek_char() == ')')
4820 parameters = NULL;
4821 else
4823 parameters = new Typed_identifier_list();
4824 while (true)
4826 std::string name = imp->read_name();
4827 imp->require_c_string(" ");
4829 if (imp->match_c_string("..."))
4831 imp->advance(3);
4832 *is_varargs = true;
4835 Type* ptype = imp->read_type();
4836 if (*is_varargs)
4837 ptype = Type::make_array_type(ptype, NULL);
4838 parameters->push_back(Typed_identifier(name, ptype,
4839 imp->location()));
4840 if (imp->peek_char() != ',')
4841 break;
4842 go_assert(!*is_varargs);
4843 imp->require_c_string(", ");
4846 imp->require_c_string(")");
4847 *pparameters = parameters;
4849 Typed_identifier_list* results;
4850 if (imp->peek_char() != ' ')
4851 results = NULL;
4852 else
4854 results = new Typed_identifier_list();
4855 imp->require_c_string(" ");
4856 if (imp->peek_char() != '(')
4858 Type* rtype = imp->read_type();
4859 results->push_back(Typed_identifier("", rtype, imp->location()));
4861 else
4863 imp->require_c_string("(");
4864 while (true)
4866 std::string name = imp->read_name();
4867 imp->require_c_string(" ");
4868 Type* rtype = imp->read_type();
4869 results->push_back(Typed_identifier(name, rtype,
4870 imp->location()));
4871 if (imp->peek_char() != ',')
4872 break;
4873 imp->require_c_string(", ");
4875 imp->require_c_string(")");
4878 imp->require_c_string(";\n");
4879 *presults = results;
4882 // Get the backend representation.
4884 Bfunction*
4885 Function::get_or_make_decl(Gogo* gogo, Named_object* no)
4887 if (this->fndecl_ == NULL)
4889 std::string asm_name;
4890 bool is_visible = false;
4891 if (no->package() != NULL)
4893 else if (this->enclosing_ != NULL || Gogo::is_thunk(no))
4895 else if (Gogo::unpack_hidden_name(no->name()) == "init"
4896 && !this->type_->is_method())
4898 else if (no->name() == gogo->get_init_fn_name())
4900 is_visible = true;
4901 asm_name = no->name();
4903 else if (Gogo::unpack_hidden_name(no->name()) == "main"
4904 && gogo->is_main_package())
4905 is_visible = true;
4906 // Methods have to be public even if they are hidden because
4907 // they can be pulled into type descriptors when using
4908 // anonymous fields.
4909 else if (!Gogo::is_hidden_name(no->name())
4910 || this->type_->is_method())
4912 if (!this->is_unnamed_type_stub_method_)
4913 is_visible = true;
4914 std::string pkgpath = gogo->pkgpath_symbol();
4915 if (this->type_->is_method()
4916 && Gogo::is_hidden_name(no->name())
4917 && Gogo::hidden_name_pkgpath(no->name()) != gogo->pkgpath())
4919 // This is a method we created for an unexported
4920 // method of an imported embedded type. We need to
4921 // use the pkgpath of the imported package to avoid
4922 // a possible name collision. See bug478 for a test
4923 // case.
4924 pkgpath = Gogo::hidden_name_pkgpath(no->name());
4925 pkgpath = Gogo::pkgpath_for_symbol(pkgpath);
4928 asm_name = pkgpath;
4929 asm_name.append(1, '.');
4930 asm_name.append(Gogo::unpack_hidden_name(no->name()));
4931 if (this->type_->is_method())
4933 asm_name.append(1, '.');
4934 Type* rtype = this->type_->receiver()->type();
4935 asm_name.append(rtype->mangled_name(gogo));
4939 // If a function calls the predeclared recover function, we
4940 // can't inline it, because recover behaves differently in a
4941 // function passed directly to defer. If this is a recover
4942 // thunk that we built to test whether a function can be
4943 // recovered, we can't inline it, because that will mess up
4944 // our return address comparison.
4945 bool is_inlinable = !(this->calls_recover_ || this->is_recover_thunk_);
4947 // If this is a thunk created to call a function which calls
4948 // the predeclared recover function, we need to disable
4949 // stack splitting for the thunk.
4950 bool disable_split_stack = this->is_recover_thunk_;
4952 // This should go into a unique section if that has been
4953 // requested elsewhere, or if this is a nointerface function.
4954 // We want to put a nointerface function into a unique section
4955 // because there is a good chance that the linker garbage
4956 // collection can discard it.
4957 bool in_unique_section = this->in_unique_section_ || this->nointerface_;
4959 Btype* functype = this->type_->get_backend_fntype(gogo);
4960 this->fndecl_ =
4961 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
4962 is_visible, false, is_inlinable,
4963 disable_split_stack, in_unique_section,
4964 this->location());
4966 return this->fndecl_;
4969 // Get the backend representation.
4971 Bfunction*
4972 Function_declaration::get_or_make_decl(Gogo* gogo, Named_object* no)
4974 if (this->fndecl_ == NULL)
4976 // Let Go code use an asm declaration to pick up a builtin
4977 // function.
4978 if (!this->asm_name_.empty())
4980 Bfunction* builtin_decl =
4981 gogo->backend()->lookup_builtin(this->asm_name_);
4982 if (builtin_decl != NULL)
4984 this->fndecl_ = builtin_decl;
4985 return this->fndecl_;
4989 std::string asm_name;
4990 if (this->asm_name_.empty())
4992 asm_name = (no->package() == NULL
4993 ? gogo->pkgpath_symbol()
4994 : no->package()->pkgpath_symbol());
4995 asm_name.append(1, '.');
4996 asm_name.append(Gogo::unpack_hidden_name(no->name()));
4997 if (this->fntype_->is_method())
4999 asm_name.append(1, '.');
5000 Type* rtype = this->fntype_->receiver()->type();
5001 asm_name.append(rtype->mangled_name(gogo));
5005 Btype* functype = this->fntype_->get_backend_fntype(gogo);
5006 this->fndecl_ =
5007 gogo->backend()->function(functype, no->get_id(gogo), asm_name,
5008 true, true, true, false, false,
5009 this->location());
5012 return this->fndecl_;
5015 // Build the descriptor for a function declaration. This won't
5016 // necessarily happen if the package has just a declaration for the
5017 // function and no other reference to it, but we may still need the
5018 // descriptor for references from other packages.
5019 void
5020 Function_declaration::build_backend_descriptor(Gogo* gogo)
5022 if (this->descriptor_ != NULL)
5024 Translate_context context(gogo, NULL, NULL, NULL);
5025 this->descriptor_->get_backend(&context);
5029 // Return the function's decl after it has been built.
5031 Bfunction*
5032 Function::get_decl() const
5034 go_assert(this->fndecl_ != NULL);
5035 return this->fndecl_;
5038 // Build the backend representation for the function code.
5040 void
5041 Function::build(Gogo* gogo, Named_object* named_function)
5043 Translate_context context(gogo, named_function, NULL, NULL);
5045 // A list of parameter variables for this function.
5046 std::vector<Bvariable*> param_vars;
5048 // Variables that need to be declared for this function and their
5049 // initial values.
5050 std::vector<Bvariable*> vars;
5051 std::vector<Bexpression*> var_inits;
5052 for (Bindings::const_definitions_iterator p =
5053 this->block_->bindings()->begin_definitions();
5054 p != this->block_->bindings()->end_definitions();
5055 ++p)
5057 Location loc = (*p)->location();
5058 if ((*p)->is_variable() && (*p)->var_value()->is_parameter())
5060 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5061 Bvariable* parm_bvar = bvar;
5063 // We always pass the receiver to a method as a pointer. If
5064 // the receiver is declared as a non-pointer type, then we
5065 // copy the value into a local variable.
5066 if ((*p)->var_value()->is_receiver()
5067 && (*p)->var_value()->type()->points_to() == NULL)
5069 std::string name = (*p)->name() + ".pointer";
5070 Type* var_type = (*p)->var_value()->type();
5071 Variable* parm_var =
5072 new Variable(Type::make_pointer_type(var_type), NULL, false,
5073 true, false, loc);
5074 Named_object* parm_no =
5075 Named_object::make_variable(name, NULL, parm_var);
5076 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5078 vars.push_back(bvar);
5079 Expression* parm_ref =
5080 Expression::make_var_reference(parm_no, loc);
5081 parm_ref = Expression::make_unary(OPERATOR_MULT, parm_ref, loc);
5082 if ((*p)->var_value()->is_in_heap())
5083 parm_ref = Expression::make_heap_expression(parm_ref, loc);
5084 var_inits.push_back(parm_ref->get_backend(&context));
5086 else if ((*p)->var_value()->is_in_heap())
5088 // If we take the address of a parameter, then we need
5089 // to copy it into the heap.
5090 std::string parm_name = (*p)->name() + ".param";
5091 Variable* parm_var = new Variable((*p)->var_value()->type(), NULL,
5092 false, true, false, loc);
5093 Named_object* parm_no =
5094 Named_object::make_variable(parm_name, NULL, parm_var);
5095 parm_bvar = parm_no->get_backend_variable(gogo, named_function);
5097 vars.push_back(bvar);
5098 Expression* var_ref =
5099 Expression::make_var_reference(parm_no, loc);
5100 var_ref = Expression::make_heap_expression(var_ref, loc);
5101 var_inits.push_back(var_ref->get_backend(&context));
5103 param_vars.push_back(parm_bvar);
5105 else if ((*p)->is_result_variable())
5107 Bvariable* bvar = (*p)->get_backend_variable(gogo, named_function);
5109 Type* type = (*p)->result_var_value()->type();
5110 Bexpression* init;
5111 if (!(*p)->result_var_value()->is_in_heap())
5113 Btype* btype = type->get_backend(gogo);
5114 init = gogo->backend()->zero_expression(btype);
5116 else
5117 init = Expression::make_allocation(type,
5118 loc)->get_backend(&context);
5120 vars.push_back(bvar);
5121 var_inits.push_back(init);
5124 if (!gogo->backend()->function_set_parameters(this->fndecl_, param_vars))
5126 go_assert(saw_errors());
5127 return;
5130 // If we need a closure variable, fetch it by calling a runtime
5131 // function. The caller will have called __go_set_closure before
5132 // the function call.
5133 if (this->closure_var_ != NULL)
5135 Bvariable* closure_bvar =
5136 this->closure_var_->get_backend_variable(gogo, named_function);
5137 vars.push_back(closure_bvar);
5139 Expression* closure =
5140 Runtime::make_call(Runtime::GET_CLOSURE, this->location_, 0);
5141 var_inits.push_back(closure->get_backend(&context));
5144 if (this->block_ != NULL)
5146 // Declare variables if necessary.
5147 Bblock* var_decls = NULL;
5149 Bstatement* defer_init = NULL;
5150 if (!vars.empty() || this->defer_stack_ != NULL)
5152 var_decls =
5153 gogo->backend()->block(this->fndecl_, NULL, vars,
5154 this->block_->start_location(),
5155 this->block_->end_location());
5157 if (this->defer_stack_ != NULL)
5159 Translate_context dcontext(gogo, named_function, this->block_,
5160 var_decls);
5161 defer_init = this->defer_stack_->get_backend(&dcontext);
5165 // Build the backend representation for all the statements in the
5166 // function.
5167 Translate_context context(gogo, named_function, NULL, NULL);
5168 Bblock* code_block = this->block_->get_backend(&context);
5170 // Initialize variables if necessary.
5171 std::vector<Bstatement*> init;
5172 go_assert(vars.size() == var_inits.size());
5173 for (size_t i = 0; i < vars.size(); ++i)
5175 Bstatement* init_stmt =
5176 gogo->backend()->init_statement(vars[i], var_inits[i]);
5177 init.push_back(init_stmt);
5179 Bstatement* var_init = gogo->backend()->statement_list(init);
5181 // Initialize all variables before executing this code block.
5182 Bstatement* code_stmt = gogo->backend()->block_statement(code_block);
5183 code_stmt = gogo->backend()->compound_statement(var_init, code_stmt);
5185 // If we have a defer stack, initialize it at the start of a
5186 // function.
5187 Bstatement* except = NULL;
5188 Bstatement* fini = NULL;
5189 if (defer_init != NULL)
5191 // Clean up the defer stack when we leave the function.
5192 this->build_defer_wrapper(gogo, named_function, &except, &fini);
5194 // Wrap the code for this function in an exception handler to handle
5195 // defer calls.
5196 code_stmt =
5197 gogo->backend()->exception_handler_statement(code_stmt,
5198 except, fini,
5199 this->location_);
5202 // Stick the code into the block we built for the receiver, if
5203 // we built one.
5204 if (var_decls != NULL)
5206 std::vector<Bstatement*> code_stmt_list(1, code_stmt);
5207 gogo->backend()->block_add_statements(var_decls, code_stmt_list);
5208 code_stmt = gogo->backend()->block_statement(var_decls);
5211 if (!gogo->backend()->function_set_body(this->fndecl_, code_stmt))
5213 go_assert(saw_errors());
5214 return;
5218 // If we created a descriptor for the function, make sure we emit it.
5219 if (this->descriptor_ != NULL)
5221 Translate_context context(gogo, NULL, NULL, NULL);
5222 this->descriptor_->get_backend(&context);
5226 // Build the wrappers around function code needed if the function has
5227 // any defer statements. This sets *EXCEPT to an exception handler
5228 // and *FINI to a finally handler.
5230 void
5231 Function::build_defer_wrapper(Gogo* gogo, Named_object* named_function,
5232 Bstatement** except, Bstatement** fini)
5234 Location end_loc = this->block_->end_location();
5236 // Add an exception handler. This is used if a panic occurs. Its
5237 // purpose is to stop the stack unwinding if a deferred function
5238 // calls recover. There are more details in
5239 // libgo/runtime/go-unwind.c.
5241 std::vector<Bstatement*> stmts;
5242 Expression* call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
5243 this->defer_stack(end_loc));
5244 Translate_context context(gogo, named_function, NULL, NULL);
5245 Bexpression* defer = call->get_backend(&context);
5246 stmts.push_back(gogo->backend()->expression_statement(defer));
5248 Bstatement* ret_bstmt = this->return_value(gogo, named_function, end_loc);
5249 if (ret_bstmt != NULL)
5250 stmts.push_back(ret_bstmt);
5252 go_assert(*except == NULL);
5253 *except = gogo->backend()->statement_list(stmts);
5255 call = Runtime::make_call(Runtime::CHECK_DEFER, end_loc, 1,
5256 this->defer_stack(end_loc));
5257 defer = call->get_backend(&context);
5259 call = Runtime::make_call(Runtime::UNDEFER, end_loc, 1,
5260 this->defer_stack(end_loc));
5261 Bexpression* undefer = call->get_backend(&context);
5262 Bstatement* function_defer =
5263 gogo->backend()->function_defer_statement(this->fndecl_, undefer, defer,
5264 end_loc);
5265 stmts = std::vector<Bstatement*>(1, function_defer);
5266 if (this->type_->results() != NULL
5267 && !this->type_->results()->empty()
5268 && !this->type_->results()->front().name().empty())
5270 // If the result variables are named, and we are returning from
5271 // this function rather than panicing through it, we need to
5272 // return them again, because they might have been changed by a
5273 // defer function. The runtime routines set the defer_stack
5274 // variable to true if we are returning from this function.
5276 ret_bstmt = this->return_value(gogo, named_function, end_loc);
5277 Bexpression* nil = Expression::make_nil(end_loc)->get_backend(&context);
5278 Bexpression* ret =
5279 gogo->backend()->compound_expression(ret_bstmt, nil, end_loc);
5280 Expression* ref =
5281 Expression::make_temporary_reference(this->defer_stack_, end_loc);
5282 Bexpression* bref = ref->get_backend(&context);
5283 ret = gogo->backend()->conditional_expression(NULL, bref, ret, NULL,
5284 end_loc);
5285 stmts.push_back(gogo->backend()->expression_statement(ret));
5288 go_assert(*fini == NULL);
5289 *fini = gogo->backend()->statement_list(stmts);
5292 // Return the statement that assigns values to this function's result struct.
5294 Bstatement*
5295 Function::return_value(Gogo* gogo, Named_object* named_function,
5296 Location location) const
5298 const Typed_identifier_list* results = this->type_->results();
5299 if (results == NULL || results->empty())
5300 return NULL;
5302 go_assert(this->results_ != NULL);
5303 if (this->results_->size() != results->size())
5305 go_assert(saw_errors());
5306 return gogo->backend()->error_statement();
5309 std::vector<Bexpression*> vals(results->size());
5310 for (size_t i = 0; i < vals.size(); ++i)
5312 Named_object* no = (*this->results_)[i];
5313 Bvariable* bvar = no->get_backend_variable(gogo, named_function);
5314 Bexpression* val = gogo->backend()->var_expression(bvar, location);
5315 if (no->result_var_value()->is_in_heap())
5317 Btype* bt = no->result_var_value()->type()->get_backend(gogo);
5318 val = gogo->backend()->indirect_expression(bt, val, true, location);
5320 vals[i] = val;
5322 return gogo->backend()->return_statement(this->fndecl_, vals, location);
5325 // Class Block.
5327 Block::Block(Block* enclosing, Location location)
5328 : enclosing_(enclosing), statements_(),
5329 bindings_(new Bindings(enclosing == NULL
5330 ? NULL
5331 : enclosing->bindings())),
5332 start_location_(location),
5333 end_location_(UNKNOWN_LOCATION)
5337 // Add a statement to a block.
5339 void
5340 Block::add_statement(Statement* statement)
5342 this->statements_.push_back(statement);
5345 // Add a statement to the front of a block. This is slow but is only
5346 // used for reference counts of parameters.
5348 void
5349 Block::add_statement_at_front(Statement* statement)
5351 this->statements_.insert(this->statements_.begin(), statement);
5354 // Replace a statement in a block.
5356 void
5357 Block::replace_statement(size_t index, Statement* s)
5359 go_assert(index < this->statements_.size());
5360 this->statements_[index] = s;
5363 // Add a statement before another statement.
5365 void
5366 Block::insert_statement_before(size_t index, Statement* s)
5368 go_assert(index < this->statements_.size());
5369 this->statements_.insert(this->statements_.begin() + index, s);
5372 // Add a statement after another statement.
5374 void
5375 Block::insert_statement_after(size_t index, Statement* s)
5377 go_assert(index < this->statements_.size());
5378 this->statements_.insert(this->statements_.begin() + index + 1, s);
5381 // Traverse the tree.
5384 Block::traverse(Traverse* traverse)
5386 unsigned int traverse_mask = traverse->traverse_mask();
5388 if ((traverse_mask & Traverse::traverse_blocks) != 0)
5390 int t = traverse->block(this);
5391 if (t == TRAVERSE_EXIT)
5392 return TRAVERSE_EXIT;
5393 else if (t == TRAVERSE_SKIP_COMPONENTS)
5394 return TRAVERSE_CONTINUE;
5397 if ((traverse_mask
5398 & (Traverse::traverse_variables
5399 | Traverse::traverse_constants
5400 | Traverse::traverse_expressions
5401 | Traverse::traverse_types)) != 0)
5403 const unsigned int e_or_t = (Traverse::traverse_expressions
5404 | Traverse::traverse_types);
5405 const unsigned int e_or_t_or_s = (e_or_t
5406 | Traverse::traverse_statements);
5407 for (Bindings::const_definitions_iterator pb =
5408 this->bindings_->begin_definitions();
5409 pb != this->bindings_->end_definitions();
5410 ++pb)
5412 int t = TRAVERSE_CONTINUE;
5413 switch ((*pb)->classification())
5415 case Named_object::NAMED_OBJECT_CONST:
5416 if ((traverse_mask & Traverse::traverse_constants) != 0)
5417 t = traverse->constant(*pb, false);
5418 if (t == TRAVERSE_CONTINUE
5419 && (traverse_mask & e_or_t) != 0)
5421 Type* tc = (*pb)->const_value()->type();
5422 if (tc != NULL
5423 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
5424 return TRAVERSE_EXIT;
5425 t = (*pb)->const_value()->traverse_expression(traverse);
5427 break;
5429 case Named_object::NAMED_OBJECT_VAR:
5430 case Named_object::NAMED_OBJECT_RESULT_VAR:
5431 if ((traverse_mask & Traverse::traverse_variables) != 0)
5432 t = traverse->variable(*pb);
5433 if (t == TRAVERSE_CONTINUE
5434 && (traverse_mask & e_or_t) != 0)
5436 if ((*pb)->is_result_variable()
5437 || (*pb)->var_value()->has_type())
5439 Type* tv = ((*pb)->is_variable()
5440 ? (*pb)->var_value()->type()
5441 : (*pb)->result_var_value()->type());
5442 if (tv != NULL
5443 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
5444 return TRAVERSE_EXIT;
5447 if (t == TRAVERSE_CONTINUE
5448 && (traverse_mask & e_or_t_or_s) != 0
5449 && (*pb)->is_variable())
5450 t = (*pb)->var_value()->traverse_expression(traverse,
5451 traverse_mask);
5452 break;
5454 case Named_object::NAMED_OBJECT_FUNC:
5455 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
5456 go_unreachable();
5458 case Named_object::NAMED_OBJECT_TYPE:
5459 if ((traverse_mask & e_or_t) != 0)
5460 t = Type::traverse((*pb)->type_value(), traverse);
5461 break;
5463 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
5464 case Named_object::NAMED_OBJECT_UNKNOWN:
5465 case Named_object::NAMED_OBJECT_ERRONEOUS:
5466 break;
5468 case Named_object::NAMED_OBJECT_PACKAGE:
5469 case Named_object::NAMED_OBJECT_SINK:
5470 go_unreachable();
5472 default:
5473 go_unreachable();
5476 if (t == TRAVERSE_EXIT)
5477 return TRAVERSE_EXIT;
5481 // No point in checking traverse_mask here--if we got here we always
5482 // want to walk the statements. The traversal can insert new
5483 // statements before or after the current statement. Inserting
5484 // statements before the current statement requires updating I via
5485 // the pointer; those statements will not be traversed. Any new
5486 // statements inserted after the current statement will be traversed
5487 // in their turn.
5488 for (size_t i = 0; i < this->statements_.size(); ++i)
5490 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
5491 return TRAVERSE_EXIT;
5494 return TRAVERSE_CONTINUE;
5497 // Work out types for unspecified variables and constants.
5499 void
5500 Block::determine_types()
5502 for (Bindings::const_definitions_iterator pb =
5503 this->bindings_->begin_definitions();
5504 pb != this->bindings_->end_definitions();
5505 ++pb)
5507 if ((*pb)->is_variable())
5508 (*pb)->var_value()->determine_type();
5509 else if ((*pb)->is_const())
5510 (*pb)->const_value()->determine_type();
5513 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
5514 ps != this->statements_.end();
5515 ++ps)
5516 (*ps)->determine_types();
5519 // Return true if the statements in this block may fall through.
5521 bool
5522 Block::may_fall_through() const
5524 if (this->statements_.empty())
5525 return true;
5526 return this->statements_.back()->may_fall_through();
5529 // Convert a block to the backend representation.
5531 Bblock*
5532 Block::get_backend(Translate_context* context)
5534 Gogo* gogo = context->gogo();
5535 Named_object* function = context->function();
5536 std::vector<Bvariable*> vars;
5537 vars.reserve(this->bindings_->size_definitions());
5538 for (Bindings::const_definitions_iterator pv =
5539 this->bindings_->begin_definitions();
5540 pv != this->bindings_->end_definitions();
5541 ++pv)
5543 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
5544 vars.push_back((*pv)->get_backend_variable(gogo, function));
5547 go_assert(function != NULL);
5548 Bfunction* bfunction =
5549 function->func_value()->get_or_make_decl(gogo, function);
5550 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
5551 vars, this->start_location_,
5552 this->end_location_);
5554 Translate_context subcontext(gogo, function, this, ret);
5555 std::vector<Bstatement*> bstatements;
5556 bstatements.reserve(this->statements_.size());
5557 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
5558 p != this->statements_.end();
5559 ++p)
5560 bstatements.push_back((*p)->get_backend(&subcontext));
5562 context->backend()->block_add_statements(ret, bstatements);
5564 return ret;
5567 // Class Bindings_snapshot.
5569 Bindings_snapshot::Bindings_snapshot(const Block* b, Location location)
5570 : block_(b), counts_(), location_(location)
5572 while (b != NULL)
5574 this->counts_.push_back(b->bindings()->size_definitions());
5575 b = b->enclosing();
5579 // Report errors appropriate for a goto from B to this.
5581 void
5582 Bindings_snapshot::check_goto_from(const Block* b, Location loc)
5584 size_t dummy;
5585 if (!this->check_goto_block(loc, b, this->block_, &dummy))
5586 return;
5587 this->check_goto_defs(loc, this->block_,
5588 this->block_->bindings()->size_definitions(),
5589 this->counts_[0]);
5592 // Report errors appropriate for a goto from this to B.
5594 void
5595 Bindings_snapshot::check_goto_to(const Block* b)
5597 size_t index;
5598 if (!this->check_goto_block(this->location_, this->block_, b, &index))
5599 return;
5600 this->check_goto_defs(this->location_, b, this->counts_[index],
5601 b->bindings()->size_definitions());
5604 // Report errors appropriate for a goto at LOC from BFROM to BTO.
5605 // Return true if all is well, false if we reported an error. If this
5606 // returns true, it sets *PINDEX to the number of blocks BTO is above
5607 // BFROM.
5609 bool
5610 Bindings_snapshot::check_goto_block(Location loc, const Block* bfrom,
5611 const Block* bto, size_t* pindex)
5613 // It is an error if BTO is not either BFROM or above BFROM.
5614 size_t index = 0;
5615 for (const Block* pb = bfrom; pb != bto; pb = pb->enclosing(), ++index)
5617 if (pb == NULL)
5619 error_at(loc, "goto jumps into block");
5620 inform(bto->start_location(), "goto target block starts here");
5621 return false;
5624 *pindex = index;
5625 return true;
5628 // Report errors appropriate for a goto at LOC ending at BLOCK, where
5629 // CFROM is the number of names defined at the point of the goto and
5630 // CTO is the number of names defined at the point of the label.
5632 void
5633 Bindings_snapshot::check_goto_defs(Location loc, const Block* block,
5634 size_t cfrom, size_t cto)
5636 if (cfrom < cto)
5638 Bindings::const_definitions_iterator p =
5639 block->bindings()->begin_definitions();
5640 for (size_t i = 0; i < cfrom; ++i)
5642 go_assert(p != block->bindings()->end_definitions());
5643 ++p;
5645 go_assert(p != block->bindings()->end_definitions());
5647 std::string n = (*p)->message_name();
5648 error_at(loc, "goto jumps over declaration of %qs", n.c_str());
5649 inform((*p)->location(), "%qs defined here", n.c_str());
5653 // Class Function_declaration.
5655 // Return the function descriptor.
5657 Expression*
5658 Function_declaration::descriptor(Gogo*, Named_object* no)
5660 go_assert(!this->fntype_->is_method());
5661 if (this->descriptor_ == NULL)
5662 this->descriptor_ = Expression::make_func_descriptor(no);
5663 return this->descriptor_;
5666 // Class Variable.
5668 Variable::Variable(Type* type, Expression* init, bool is_global,
5669 bool is_parameter, bool is_receiver,
5670 Location location)
5671 : type_(type), init_(init), preinit_(NULL), location_(location),
5672 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
5673 is_receiver_(is_receiver), is_varargs_parameter_(false), is_used_(false),
5674 is_address_taken_(false), is_non_escaping_address_taken_(false),
5675 seen_(false), init_is_lowered_(false), init_is_flattened_(false),
5676 type_from_init_tuple_(false), type_from_range_index_(false),
5677 type_from_range_value_(false), type_from_chan_element_(false),
5678 is_type_switch_var_(false), determined_type_(false),
5679 in_unique_section_(false)
5681 go_assert(type != NULL || init != NULL);
5682 go_assert(!is_parameter || init == NULL);
5685 // Traverse the initializer expression.
5688 Variable::traverse_expression(Traverse* traverse, unsigned int traverse_mask)
5690 if (this->preinit_ != NULL)
5692 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
5693 return TRAVERSE_EXIT;
5695 if (this->init_ != NULL
5696 && ((traverse_mask
5697 & (Traverse::traverse_expressions | Traverse::traverse_types))
5698 != 0))
5700 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
5701 return TRAVERSE_EXIT;
5703 return TRAVERSE_CONTINUE;
5706 // Lower the initialization expression after parsing is complete.
5708 void
5709 Variable::lower_init_expression(Gogo* gogo, Named_object* function,
5710 Statement_inserter* inserter)
5712 Named_object* dep = gogo->var_depends_on(this);
5713 if (dep != NULL && dep->is_variable())
5714 dep->var_value()->lower_init_expression(gogo, function, inserter);
5716 if (this->init_ != NULL && !this->init_is_lowered_)
5718 if (this->seen_)
5720 // We will give an error elsewhere, this is just to prevent
5721 // an infinite loop.
5722 return;
5724 this->seen_ = true;
5726 Statement_inserter global_inserter;
5727 if (this->is_global_)
5729 global_inserter = Statement_inserter(gogo, this);
5730 inserter = &global_inserter;
5733 gogo->lower_expression(function, inserter, &this->init_);
5735 this->seen_ = false;
5737 this->init_is_lowered_ = true;
5741 // Flatten the initialization expression after ordering evaluations.
5743 void
5744 Variable::flatten_init_expression(Gogo* gogo, Named_object* function,
5745 Statement_inserter* inserter)
5747 Named_object* dep = gogo->var_depends_on(this);
5748 if (dep != NULL && dep->is_variable())
5749 dep->var_value()->flatten_init_expression(gogo, function, inserter);
5751 if (this->init_ != NULL && !this->init_is_flattened_)
5753 if (this->seen_)
5755 // We will give an error elsewhere, this is just to prevent
5756 // an infinite loop.
5757 return;
5759 this->seen_ = true;
5761 Statement_inserter global_inserter;
5762 if (this->is_global_)
5764 global_inserter = Statement_inserter(gogo, this);
5765 inserter = &global_inserter;
5768 gogo->flatten_expression(function, inserter, &this->init_);
5770 this->seen_ = false;
5771 this->init_is_flattened_ = true;
5775 // Get the preinit block.
5777 Block*
5778 Variable::preinit_block(Gogo* gogo)
5780 go_assert(this->is_global_);
5781 if (this->preinit_ == NULL)
5782 this->preinit_ = new Block(NULL, this->location());
5784 // If a global variable has a preinitialization statement, then we
5785 // need to have an initialization function.
5786 gogo->set_need_init_fn();
5788 return this->preinit_;
5791 // Add a statement to be run before the initialization expression.
5793 void
5794 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
5796 Block* b = this->preinit_block(gogo);
5797 b->add_statement(s);
5798 b->set_end_location(s->location());
5801 // Whether this variable has a type.
5803 bool
5804 Variable::has_type() const
5806 if (this->type_ == NULL)
5807 return false;
5809 // A variable created in a type switch case nil does not actually
5810 // have a type yet. It will be changed to use the initializer's
5811 // type in determine_type.
5812 if (this->is_type_switch_var_
5813 && this->type_->is_nil_constant_as_type())
5814 return false;
5816 return true;
5819 // In an assignment which sets a variable to a tuple of EXPR, return
5820 // the type of the first element of the tuple.
5822 Type*
5823 Variable::type_from_tuple(Expression* expr, bool report_error) const
5825 if (expr->map_index_expression() != NULL)
5827 Map_type* mt = expr->map_index_expression()->get_map_type();
5828 if (mt == NULL)
5829 return Type::make_error_type();
5830 return mt->val_type();
5832 else if (expr->receive_expression() != NULL)
5834 Expression* channel = expr->receive_expression()->channel();
5835 Type* channel_type = channel->type();
5836 if (channel_type->channel_type() == NULL)
5837 return Type::make_error_type();
5838 return channel_type->channel_type()->element_type();
5840 else
5842 if (report_error)
5843 error_at(this->location(), "invalid tuple definition");
5844 return Type::make_error_type();
5848 // Given EXPR used in a range clause, return either the index type or
5849 // the value type of the range, depending upon GET_INDEX_TYPE.
5851 Type*
5852 Variable::type_from_range(Expression* expr, bool get_index_type,
5853 bool report_error) const
5855 Type* t = expr->type();
5856 if (t->array_type() != NULL
5857 || (t->points_to() != NULL
5858 && t->points_to()->array_type() != NULL
5859 && !t->points_to()->is_slice_type()))
5861 if (get_index_type)
5862 return Type::lookup_integer_type("int");
5863 else
5864 return t->deref()->array_type()->element_type();
5866 else if (t->is_string_type())
5868 if (get_index_type)
5869 return Type::lookup_integer_type("int");
5870 else
5871 return Type::lookup_integer_type("int32");
5873 else if (t->map_type() != NULL)
5875 if (get_index_type)
5876 return t->map_type()->key_type();
5877 else
5878 return t->map_type()->val_type();
5880 else if (t->channel_type() != NULL)
5882 if (get_index_type)
5883 return t->channel_type()->element_type();
5884 else
5886 if (report_error)
5887 error_at(this->location(),
5888 "invalid definition of value variable for channel range");
5889 return Type::make_error_type();
5892 else
5894 if (report_error)
5895 error_at(this->location(), "invalid type for range clause");
5896 return Type::make_error_type();
5900 // EXPR should be a channel. Return the channel's element type.
5902 Type*
5903 Variable::type_from_chan_element(Expression* expr, bool report_error) const
5905 Type* t = expr->type();
5906 if (t->channel_type() != NULL)
5907 return t->channel_type()->element_type();
5908 else
5910 if (report_error)
5911 error_at(this->location(), "expected channel");
5912 return Type::make_error_type();
5916 // Return the type of the Variable. This may be called before
5917 // Variable::determine_type is called, which means that we may need to
5918 // get the type from the initializer. FIXME: If we combine lowering
5919 // with type determination, then this should be unnecessary.
5921 Type*
5922 Variable::type()
5924 // A variable in a type switch with a nil case will have the wrong
5925 // type here. This gets fixed up in determine_type, below.
5926 Type* type = this->type_;
5927 Expression* init = this->init_;
5928 if (this->is_type_switch_var_
5929 && this->type_->is_nil_constant_as_type())
5931 Type_guard_expression* tge = this->init_->type_guard_expression();
5932 go_assert(tge != NULL);
5933 init = tge->expr();
5934 type = NULL;
5937 if (this->seen_)
5939 if (this->type_ == NULL || !this->type_->is_error_type())
5941 error_at(this->location_, "variable initializer refers to itself");
5942 this->type_ = Type::make_error_type();
5944 return this->type_;
5947 this->seen_ = true;
5949 if (type != NULL)
5951 else if (this->type_from_init_tuple_)
5952 type = this->type_from_tuple(init, false);
5953 else if (this->type_from_range_index_ || this->type_from_range_value_)
5954 type = this->type_from_range(init, this->type_from_range_index_, false);
5955 else if (this->type_from_chan_element_)
5956 type = this->type_from_chan_element(init, false);
5957 else
5959 go_assert(init != NULL);
5960 type = init->type();
5961 go_assert(type != NULL);
5963 // Variables should not have abstract types.
5964 if (type->is_abstract())
5965 type = type->make_non_abstract_type();
5967 if (type->is_void_type())
5968 type = Type::make_error_type();
5971 this->seen_ = false;
5973 return type;
5976 // Fetch the type from a const pointer, in which case it should have
5977 // been set already.
5979 Type*
5980 Variable::type() const
5982 go_assert(this->type_ != NULL);
5983 return this->type_;
5986 // Set the type if necessary.
5988 void
5989 Variable::determine_type()
5991 if (this->determined_type_)
5992 return;
5993 this->determined_type_ = true;
5995 if (this->preinit_ != NULL)
5996 this->preinit_->determine_types();
5998 // A variable in a type switch with a nil case will have the wrong
5999 // type here. It will have an initializer which is a type guard.
6000 // We want to initialize it to the value without the type guard, and
6001 // use the type of that value as well.
6002 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
6004 Type_guard_expression* tge = this->init_->type_guard_expression();
6005 go_assert(tge != NULL);
6006 this->type_ = NULL;
6007 this->init_ = tge->expr();
6010 if (this->init_ == NULL)
6011 go_assert(this->type_ != NULL && !this->type_->is_abstract());
6012 else if (this->type_from_init_tuple_)
6014 Expression *init = this->init_;
6015 init->determine_type_no_context();
6016 this->type_ = this->type_from_tuple(init, true);
6017 this->init_ = NULL;
6019 else if (this->type_from_range_index_ || this->type_from_range_value_)
6021 Expression* init = this->init_;
6022 init->determine_type_no_context();
6023 this->type_ = this->type_from_range(init, this->type_from_range_index_,
6024 true);
6025 this->init_ = NULL;
6027 else if (this->type_from_chan_element_)
6029 Expression* init = this->init_;
6030 init->determine_type_no_context();
6031 this->type_ = this->type_from_chan_element(init, true);
6032 this->init_ = NULL;
6034 else
6036 Type_context context(this->type_, false);
6037 this->init_->determine_type(&context);
6038 if (this->type_ == NULL)
6040 Type* type = this->init_->type();
6041 go_assert(type != NULL);
6042 if (type->is_abstract())
6043 type = type->make_non_abstract_type();
6045 if (type->is_void_type())
6047 error_at(this->location_, "variable has no type");
6048 type = Type::make_error_type();
6050 else if (type->is_nil_type())
6052 error_at(this->location_, "variable defined to nil type");
6053 type = Type::make_error_type();
6055 else if (type->is_call_multiple_result_type())
6057 error_at(this->location_,
6058 "single variable set to multiple-value function call");
6059 type = Type::make_error_type();
6062 this->type_ = type;
6067 // Get the initial value of a variable. This does not
6068 // consider whether the variable is in the heap--it returns the
6069 // initial value as though it were always stored in the stack.
6071 Bexpression*
6072 Variable::get_init(Gogo* gogo, Named_object* function)
6074 go_assert(this->preinit_ == NULL);
6075 Location loc = this->location();
6076 if (this->init_ == NULL)
6078 go_assert(!this->is_parameter_);
6079 if (this->is_global_ || this->is_in_heap())
6080 return NULL;
6081 Btype* btype = this->type()->get_backend(gogo);
6082 return gogo->backend()->zero_expression(btype);
6084 else
6086 Translate_context context(gogo, function, NULL, NULL);
6087 Expression* init = Expression::make_cast(this->type(), this->init_, loc);
6088 return init->get_backend(&context);
6092 // Get the initial value of a variable when a block is required.
6093 // VAR_DECL is the decl to set; it may be NULL for a sink variable.
6095 Bstatement*
6096 Variable::get_init_block(Gogo* gogo, Named_object* function,
6097 Bvariable* var_decl)
6099 go_assert(this->preinit_ != NULL);
6101 // We want to add the variable assignment to the end of the preinit
6102 // block.
6104 Translate_context context(gogo, function, NULL, NULL);
6105 Bblock* bblock = this->preinit_->get_backend(&context);
6107 // It's possible to have pre-init statements without an initializer
6108 // if the pre-init statements set the variable.
6109 Bstatement* decl_init = NULL;
6110 if (this->init_ != NULL)
6112 if (var_decl == NULL)
6114 Bexpression* init_bexpr = this->init_->get_backend(&context);
6115 decl_init = gogo->backend()->expression_statement(init_bexpr);
6117 else
6119 Location loc = this->location();
6120 Expression* val_expr =
6121 Expression::make_cast(this->type(), this->init_, loc);
6122 Bexpression* val = val_expr->get_backend(&context);
6123 Bexpression* var_ref = gogo->backend()->var_expression(var_decl, loc);
6124 decl_init = gogo->backend()->assignment_statement(var_ref, val, loc);
6127 Bstatement* block_stmt = gogo->backend()->block_statement(bblock);
6128 if (decl_init != NULL)
6129 block_stmt = gogo->backend()->compound_statement(block_stmt, decl_init);
6130 return block_stmt;
6133 // Export the variable
6135 void
6136 Variable::export_var(Export* exp, const std::string& name) const
6138 go_assert(this->is_global_);
6139 exp->write_c_string("var ");
6140 exp->write_string(name);
6141 exp->write_c_string(" ");
6142 exp->write_type(this->type());
6143 exp->write_c_string(";\n");
6146 // Import a variable.
6148 void
6149 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
6151 imp->require_c_string("var ");
6152 *pname = imp->read_identifier();
6153 imp->require_c_string(" ");
6154 *ptype = imp->read_type();
6155 imp->require_c_string(";\n");
6158 // Convert a variable to the backend representation.
6160 Bvariable*
6161 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
6162 const Package* package, const std::string& name)
6164 if (this->backend_ == NULL)
6166 Backend* backend = gogo->backend();
6167 Type* type = this->type_;
6168 if (type->is_error_type()
6169 || (type->is_undefined()
6170 && (!this->is_global_ || package == NULL)))
6171 this->backend_ = backend->error_variable();
6172 else
6174 bool is_parameter = this->is_parameter_;
6175 if (this->is_receiver_ && type->points_to() == NULL)
6176 is_parameter = false;
6177 if (this->is_in_heap())
6179 is_parameter = false;
6180 type = Type::make_pointer_type(type);
6183 std::string n = Gogo::unpack_hidden_name(name);
6184 Btype* btype = type->get_backend(gogo);
6186 Bvariable* bvar;
6187 if (gogo->is_zero_value(this))
6188 bvar = gogo->backend_zero_value();
6189 else if (this->is_global_)
6190 bvar = backend->global_variable((package == NULL
6191 ? gogo->package_name()
6192 : package->package_name()),
6193 (package == NULL
6194 ? gogo->pkgpath_symbol()
6195 : package->pkgpath_symbol()),
6197 btype,
6198 package != NULL,
6199 Gogo::is_hidden_name(name),
6200 this->in_unique_section_,
6201 this->location_);
6202 else if (function == NULL)
6204 go_assert(saw_errors());
6205 bvar = backend->error_variable();
6207 else
6209 Bfunction* bfunction = function->func_value()->get_decl();
6210 bool is_address_taken = (this->is_non_escaping_address_taken_
6211 && !this->is_in_heap());
6212 if (is_parameter)
6213 bvar = backend->parameter_variable(bfunction, n, btype,
6214 is_address_taken,
6215 this->location_);
6216 else
6217 bvar = backend->local_variable(bfunction, n, btype,
6218 is_address_taken,
6219 this->location_);
6221 this->backend_ = bvar;
6224 return this->backend_;
6227 // Class Result_variable.
6229 // Convert a result variable to the backend representation.
6231 Bvariable*
6232 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
6233 const std::string& name)
6235 if (this->backend_ == NULL)
6237 Backend* backend = gogo->backend();
6238 Type* type = this->type_;
6239 if (type->is_error())
6240 this->backend_ = backend->error_variable();
6241 else
6243 if (this->is_in_heap())
6244 type = Type::make_pointer_type(type);
6245 Btype* btype = type->get_backend(gogo);
6246 Bfunction* bfunction = function->func_value()->get_decl();
6247 std::string n = Gogo::unpack_hidden_name(name);
6248 bool is_address_taken = (this->is_non_escaping_address_taken_
6249 && !this->is_in_heap());
6250 this->backend_ = backend->local_variable(bfunction, n, btype,
6251 is_address_taken,
6252 this->location_);
6255 return this->backend_;
6258 // Class Named_constant.
6260 // Traverse the initializer expression.
6263 Named_constant::traverse_expression(Traverse* traverse)
6265 return Expression::traverse(&this->expr_, traverse);
6268 // Determine the type of the constant.
6270 void
6271 Named_constant::determine_type()
6273 if (this->type_ != NULL)
6275 Type_context context(this->type_, false);
6276 this->expr_->determine_type(&context);
6278 else
6280 // A constant may have an abstract type.
6281 Type_context context(NULL, true);
6282 this->expr_->determine_type(&context);
6283 this->type_ = this->expr_->type();
6284 go_assert(this->type_ != NULL);
6288 // Indicate that we found and reported an error for this constant.
6290 void
6291 Named_constant::set_error()
6293 this->type_ = Type::make_error_type();
6294 this->expr_ = Expression::make_error(this->location_);
6297 // Export a constant.
6299 void
6300 Named_constant::export_const(Export* exp, const std::string& name) const
6302 exp->write_c_string("const ");
6303 exp->write_string(name);
6304 exp->write_c_string(" ");
6305 if (!this->type_->is_abstract())
6307 exp->write_type(this->type_);
6308 exp->write_c_string(" ");
6310 exp->write_c_string("= ");
6311 this->expr()->export_expression(exp);
6312 exp->write_c_string(";\n");
6315 // Import a constant.
6317 void
6318 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
6319 Expression** pexpr)
6321 imp->require_c_string("const ");
6322 *pname = imp->read_identifier();
6323 imp->require_c_string(" ");
6324 if (imp->peek_char() == '=')
6325 *ptype = NULL;
6326 else
6328 *ptype = imp->read_type();
6329 imp->require_c_string(" ");
6331 imp->require_c_string("= ");
6332 *pexpr = Expression::import_expression(imp);
6333 imp->require_c_string(";\n");
6336 // Get the backend representation.
6338 Bexpression*
6339 Named_constant::get_backend(Gogo* gogo, Named_object* const_no)
6341 if (this->bconst_ == NULL)
6343 Translate_context subcontext(gogo, NULL, NULL, NULL);
6344 Type* type = this->type();
6345 Location loc = this->location();
6347 Expression* const_ref = Expression::make_const_reference(const_no, loc);
6348 Bexpression* const_decl = const_ref->get_backend(&subcontext);
6349 if (type != NULL && type->is_numeric_type())
6351 Btype* btype = type->get_backend(gogo);
6352 std::string name = const_no->get_id(gogo);
6353 const_decl =
6354 gogo->backend()->named_constant_expression(btype, name,
6355 const_decl, loc);
6357 this->bconst_ = const_decl;
6359 return this->bconst_;
6362 // Add a method.
6364 Named_object*
6365 Type_declaration::add_method(const std::string& name, Function* function)
6367 Named_object* ret = Named_object::make_function(name, NULL, function);
6368 this->methods_.push_back(ret);
6369 return ret;
6372 // Add a method declaration.
6374 Named_object*
6375 Type_declaration::add_method_declaration(const std::string& name,
6376 Package* package,
6377 Function_type* type,
6378 Location location)
6380 Named_object* ret = Named_object::make_function_declaration(name, package,
6381 type, location);
6382 this->methods_.push_back(ret);
6383 return ret;
6386 // Return whether any methods ere defined.
6388 bool
6389 Type_declaration::has_methods() const
6391 return !this->methods_.empty();
6394 // Define methods for the real type.
6396 void
6397 Type_declaration::define_methods(Named_type* nt)
6399 for (std::vector<Named_object*>::const_iterator p = this->methods_.begin();
6400 p != this->methods_.end();
6401 ++p)
6402 nt->add_existing_method(*p);
6405 // We are using the type. Return true if we should issue a warning.
6407 bool
6408 Type_declaration::using_type()
6410 bool ret = !this->issued_warning_;
6411 this->issued_warning_ = true;
6412 return ret;
6415 // Class Unknown_name.
6417 // Set the real named object.
6419 void
6420 Unknown_name::set_real_named_object(Named_object* no)
6422 go_assert(this->real_named_object_ == NULL);
6423 go_assert(!no->is_unknown());
6424 this->real_named_object_ = no;
6427 // Class Named_object.
6429 Named_object::Named_object(const std::string& name,
6430 const Package* package,
6431 Classification classification)
6432 : name_(name), package_(package), classification_(classification)
6434 if (Gogo::is_sink_name(name))
6435 go_assert(classification == NAMED_OBJECT_SINK);
6438 // Make an unknown name. This is used by the parser. The name must
6439 // be resolved later. Unknown names are only added in the current
6440 // package.
6442 Named_object*
6443 Named_object::make_unknown_name(const std::string& name,
6444 Location location)
6446 Named_object* named_object = new Named_object(name, NULL,
6447 NAMED_OBJECT_UNKNOWN);
6448 Unknown_name* value = new Unknown_name(location);
6449 named_object->u_.unknown_value = value;
6450 return named_object;
6453 // Make a constant.
6455 Named_object*
6456 Named_object::make_constant(const Typed_identifier& tid,
6457 const Package* package, Expression* expr,
6458 int iota_value)
6460 Named_object* named_object = new Named_object(tid.name(), package,
6461 NAMED_OBJECT_CONST);
6462 Named_constant* named_constant = new Named_constant(tid.type(), expr,
6463 iota_value,
6464 tid.location());
6465 named_object->u_.const_value = named_constant;
6466 return named_object;
6469 // Make a named type.
6471 Named_object*
6472 Named_object::make_type(const std::string& name, const Package* package,
6473 Type* type, Location location)
6475 Named_object* named_object = new Named_object(name, package,
6476 NAMED_OBJECT_TYPE);
6477 Named_type* named_type = Type::make_named_type(named_object, type, location);
6478 named_object->u_.type_value = named_type;
6479 return named_object;
6482 // Make a type declaration.
6484 Named_object*
6485 Named_object::make_type_declaration(const std::string& name,
6486 const Package* package,
6487 Location location)
6489 Named_object* named_object = new Named_object(name, package,
6490 NAMED_OBJECT_TYPE_DECLARATION);
6491 Type_declaration* type_declaration = new Type_declaration(location);
6492 named_object->u_.type_declaration = type_declaration;
6493 return named_object;
6496 // Make a variable.
6498 Named_object*
6499 Named_object::make_variable(const std::string& name, const Package* package,
6500 Variable* variable)
6502 Named_object* named_object = new Named_object(name, package,
6503 NAMED_OBJECT_VAR);
6504 named_object->u_.var_value = variable;
6505 return named_object;
6508 // Make a result variable.
6510 Named_object*
6511 Named_object::make_result_variable(const std::string& name,
6512 Result_variable* result)
6514 Named_object* named_object = new Named_object(name, NULL,
6515 NAMED_OBJECT_RESULT_VAR);
6516 named_object->u_.result_var_value = result;
6517 return named_object;
6520 // Make a sink. This is used for the special blank identifier _.
6522 Named_object*
6523 Named_object::make_sink()
6525 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
6528 // Make a named function.
6530 Named_object*
6531 Named_object::make_function(const std::string& name, const Package* package,
6532 Function* function)
6534 Named_object* named_object = new Named_object(name, package,
6535 NAMED_OBJECT_FUNC);
6536 named_object->u_.func_value = function;
6537 return named_object;
6540 // Make a function declaration.
6542 Named_object*
6543 Named_object::make_function_declaration(const std::string& name,
6544 const Package* package,
6545 Function_type* fntype,
6546 Location location)
6548 Named_object* named_object = new Named_object(name, package,
6549 NAMED_OBJECT_FUNC_DECLARATION);
6550 Function_declaration *func_decl = new Function_declaration(fntype, location);
6551 named_object->u_.func_declaration_value = func_decl;
6552 return named_object;
6555 // Make a package.
6557 Named_object*
6558 Named_object::make_package(const std::string& alias, Package* package)
6560 Named_object* named_object = new Named_object(alias, NULL,
6561 NAMED_OBJECT_PACKAGE);
6562 named_object->u_.package_value = package;
6563 return named_object;
6566 // Return the name to use in an error message.
6568 std::string
6569 Named_object::message_name() const
6571 if (this->package_ == NULL)
6572 return Gogo::message_name(this->name_);
6573 std::string ret;
6574 if (this->package_->has_package_name())
6575 ret = this->package_->package_name();
6576 else
6577 ret = this->package_->pkgpath();
6578 ret = Gogo::message_name(ret);
6579 ret += '.';
6580 ret += Gogo::message_name(this->name_);
6581 return ret;
6584 // Set the type when a declaration is defined.
6586 void
6587 Named_object::set_type_value(Named_type* named_type)
6589 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
6590 Type_declaration* td = this->u_.type_declaration;
6591 td->define_methods(named_type);
6592 unsigned int index;
6593 Named_object* in_function = td->in_function(&index);
6594 if (in_function != NULL)
6595 named_type->set_in_function(in_function, index);
6596 delete td;
6597 this->classification_ = NAMED_OBJECT_TYPE;
6598 this->u_.type_value = named_type;
6601 // Define a function which was previously declared.
6603 void
6604 Named_object::set_function_value(Function* function)
6606 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
6607 if (this->func_declaration_value()->has_descriptor())
6609 Expression* descriptor =
6610 this->func_declaration_value()->descriptor(NULL, NULL);
6611 function->set_descriptor(descriptor);
6613 this->classification_ = NAMED_OBJECT_FUNC;
6614 // FIXME: We should free the old value.
6615 this->u_.func_value = function;
6618 // Declare an unknown object as a type declaration.
6620 void
6621 Named_object::declare_as_type()
6623 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
6624 Unknown_name* unk = this->u_.unknown_value;
6625 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
6626 this->u_.type_declaration = new Type_declaration(unk->location());
6627 delete unk;
6630 // Return the location of a named object.
6632 Location
6633 Named_object::location() const
6635 switch (this->classification_)
6637 default:
6638 case NAMED_OBJECT_UNINITIALIZED:
6639 go_unreachable();
6641 case NAMED_OBJECT_ERRONEOUS:
6642 return Linemap::unknown_location();
6644 case NAMED_OBJECT_UNKNOWN:
6645 return this->unknown_value()->location();
6647 case NAMED_OBJECT_CONST:
6648 return this->const_value()->location();
6650 case NAMED_OBJECT_TYPE:
6651 return this->type_value()->location();
6653 case NAMED_OBJECT_TYPE_DECLARATION:
6654 return this->type_declaration_value()->location();
6656 case NAMED_OBJECT_VAR:
6657 return this->var_value()->location();
6659 case NAMED_OBJECT_RESULT_VAR:
6660 return this->result_var_value()->location();
6662 case NAMED_OBJECT_SINK:
6663 go_unreachable();
6665 case NAMED_OBJECT_FUNC:
6666 return this->func_value()->location();
6668 case NAMED_OBJECT_FUNC_DECLARATION:
6669 return this->func_declaration_value()->location();
6671 case NAMED_OBJECT_PACKAGE:
6672 return this->package_value()->location();
6676 // Export a named object.
6678 void
6679 Named_object::export_named_object(Export* exp) const
6681 switch (this->classification_)
6683 default:
6684 case NAMED_OBJECT_UNINITIALIZED:
6685 case NAMED_OBJECT_UNKNOWN:
6686 go_unreachable();
6688 case NAMED_OBJECT_ERRONEOUS:
6689 break;
6691 case NAMED_OBJECT_CONST:
6692 this->const_value()->export_const(exp, this->name_);
6693 break;
6695 case NAMED_OBJECT_TYPE:
6696 this->type_value()->export_named_type(exp, this->name_);
6697 break;
6699 case NAMED_OBJECT_TYPE_DECLARATION:
6700 error_at(this->type_declaration_value()->location(),
6701 "attempt to export %<%s%> which was declared but not defined",
6702 this->message_name().c_str());
6703 break;
6705 case NAMED_OBJECT_FUNC_DECLARATION:
6706 this->func_declaration_value()->export_func(exp, this->name_);
6707 break;
6709 case NAMED_OBJECT_VAR:
6710 this->var_value()->export_var(exp, this->name_);
6711 break;
6713 case NAMED_OBJECT_RESULT_VAR:
6714 case NAMED_OBJECT_SINK:
6715 go_unreachable();
6717 case NAMED_OBJECT_FUNC:
6718 this->func_value()->export_func(exp, this->name_);
6719 break;
6723 // Convert a variable to the backend representation.
6725 Bvariable*
6726 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
6728 if (this->classification_ == NAMED_OBJECT_VAR)
6729 return this->var_value()->get_backend_variable(gogo, function,
6730 this->package_, this->name_);
6731 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
6732 return this->result_var_value()->get_backend_variable(gogo, function,
6733 this->name_);
6734 else
6735 go_unreachable();
6739 // Return the external identifier for this object.
6741 std::string
6742 Named_object::get_id(Gogo* gogo)
6744 go_assert(!this->is_variable() && !this->is_result_variable());
6745 std::string decl_name;
6746 if (this->is_function_declaration()
6747 && !this->func_declaration_value()->asm_name().empty())
6748 decl_name = this->func_declaration_value()->asm_name();
6749 else if (this->is_type()
6750 && Linemap::is_predeclared_location(this->type_value()->location()))
6752 // We don't need the package name for builtin types.
6753 decl_name = Gogo::unpack_hidden_name(this->name_);
6755 else
6757 std::string package_name;
6758 if (this->package_ == NULL)
6759 package_name = gogo->package_name();
6760 else
6761 package_name = this->package_->package_name();
6763 // Note that this will be misleading if this is an unexported
6764 // method generated for an embedded imported type. In that case
6765 // the unexported method should have the package name of the
6766 // package from which it is imported, but we are going to give
6767 // it our package name. Fixing this would require knowing the
6768 // package name, but we only know the package path. It might be
6769 // better to use package paths here anyhow. This doesn't affect
6770 // the assembler code, because we always set that name in
6771 // Function::get_or_make_decl anyhow. FIXME.
6773 decl_name = package_name + '.' + Gogo::unpack_hidden_name(this->name_);
6775 Function_type* fntype;
6776 if (this->is_function())
6777 fntype = this->func_value()->type();
6778 else if (this->is_function_declaration())
6779 fntype = this->func_declaration_value()->type();
6780 else
6781 fntype = NULL;
6782 if (fntype != NULL && fntype->is_method())
6784 decl_name.push_back('.');
6785 decl_name.append(fntype->receiver()->type()->mangled_name(gogo));
6788 if (this->is_type())
6790 unsigned int index;
6791 const Named_object* in_function = this->type_value()->in_function(&index);
6792 if (in_function != NULL)
6794 decl_name += '$' + Gogo::unpack_hidden_name(in_function->name());
6795 if (index > 0)
6797 char buf[30];
6798 snprintf(buf, sizeof buf, "%u", index);
6799 decl_name += '$';
6800 decl_name += buf;
6804 return decl_name;
6807 // Get the backend representation for this named object.
6809 void
6810 Named_object::get_backend(Gogo* gogo, std::vector<Bexpression*>& const_decls,
6811 std::vector<Btype*>& type_decls,
6812 std::vector<Bfunction*>& func_decls)
6814 switch (this->classification_)
6816 case NAMED_OBJECT_CONST:
6817 if (!Gogo::is_erroneous_name(this->name_))
6818 const_decls.push_back(this->u_.const_value->get_backend(gogo, this));
6819 break;
6821 case NAMED_OBJECT_TYPE:
6823 Named_type* named_type = this->u_.type_value;
6824 if (!Gogo::is_erroneous_name(this->name_))
6825 type_decls.push_back(named_type->get_backend(gogo));
6827 // We need to produce a type descriptor for every named
6828 // type, and for a pointer to every named type, since
6829 // other files or packages might refer to them. We need
6830 // to do this even for hidden types, because they might
6831 // still be returned by some function. Simply calling the
6832 // type_descriptor method is enough to create the type
6833 // descriptor, even though we don't do anything with it.
6834 if (this->package_ == NULL)
6836 named_type->
6837 type_descriptor_pointer(gogo, Linemap::predeclared_location());
6838 Type* pn = Type::make_pointer_type(named_type);
6839 pn->type_descriptor_pointer(gogo, Linemap::predeclared_location());
6842 break;
6844 case NAMED_OBJECT_TYPE_DECLARATION:
6845 error("reference to undefined type %qs",
6846 this->message_name().c_str());
6847 return;
6849 case NAMED_OBJECT_VAR:
6850 case NAMED_OBJECT_RESULT_VAR:
6851 case NAMED_OBJECT_SINK:
6852 go_unreachable();
6854 case NAMED_OBJECT_FUNC:
6856 Function* func = this->u_.func_value;
6857 if (!Gogo::is_erroneous_name(this->name_))
6858 func_decls.push_back(func->get_or_make_decl(gogo, this));
6860 if (func->block() != NULL)
6861 func->build(gogo, this);
6863 break;
6865 case NAMED_OBJECT_ERRONEOUS:
6866 break;
6868 default:
6869 go_unreachable();
6873 // Class Bindings.
6875 Bindings::Bindings(Bindings* enclosing)
6876 : enclosing_(enclosing), named_objects_(), bindings_()
6880 // Clear imports.
6882 void
6883 Bindings::clear_file_scope(Gogo* gogo)
6885 Contour::iterator p = this->bindings_.begin();
6886 while (p != this->bindings_.end())
6888 bool keep;
6889 if (p->second->package() != NULL)
6890 keep = false;
6891 else if (p->second->is_package())
6892 keep = false;
6893 else if (p->second->is_function()
6894 && !p->second->func_value()->type()->is_method()
6895 && Gogo::unpack_hidden_name(p->second->name()) == "init")
6896 keep = false;
6897 else
6898 keep = true;
6900 if (keep)
6901 ++p;
6902 else
6904 gogo->add_file_block_name(p->second->name(), p->second->location());
6905 p = this->bindings_.erase(p);
6910 // Look up a symbol.
6912 Named_object*
6913 Bindings::lookup(const std::string& name) const
6915 Contour::const_iterator p = this->bindings_.find(name);
6916 if (p != this->bindings_.end())
6917 return p->second->resolve();
6918 else if (this->enclosing_ != NULL)
6919 return this->enclosing_->lookup(name);
6920 else
6921 return NULL;
6924 // Look up a symbol locally.
6926 Named_object*
6927 Bindings::lookup_local(const std::string& name) const
6929 Contour::const_iterator p = this->bindings_.find(name);
6930 if (p == this->bindings_.end())
6931 return NULL;
6932 return p->second;
6935 // Remove an object from a set of bindings. This is used for a
6936 // special case in thunks for functions which call recover.
6938 void
6939 Bindings::remove_binding(Named_object* no)
6941 Contour::iterator pb = this->bindings_.find(no->name());
6942 go_assert(pb != this->bindings_.end());
6943 this->bindings_.erase(pb);
6944 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
6945 pn != this->named_objects_.end();
6946 ++pn)
6948 if (*pn == no)
6950 this->named_objects_.erase(pn);
6951 return;
6954 go_unreachable();
6957 // Add a method to the list of objects. This is not added to the
6958 // lookup table. This is so that we have a single list of objects
6959 // declared at the top level, which we walk through when it's time to
6960 // convert to trees.
6962 void
6963 Bindings::add_method(Named_object* method)
6965 this->named_objects_.push_back(method);
6968 // Add a generic Named_object to a Contour.
6970 Named_object*
6971 Bindings::add_named_object_to_contour(Contour* contour,
6972 Named_object* named_object)
6974 go_assert(named_object == named_object->resolve());
6975 const std::string& name(named_object->name());
6976 go_assert(!Gogo::is_sink_name(name));
6978 std::pair<Contour::iterator, bool> ins =
6979 contour->insert(std::make_pair(name, named_object));
6980 if (!ins.second)
6982 // The name was already there.
6983 if (named_object->package() != NULL
6984 && ins.first->second->package() == named_object->package()
6985 && (ins.first->second->classification()
6986 == named_object->classification()))
6988 // This is a second import of the same object.
6989 return ins.first->second;
6991 ins.first->second = this->new_definition(ins.first->second,
6992 named_object);
6993 return ins.first->second;
6995 else
6997 // Don't push declarations on the list. We push them on when
6998 // and if we find the definitions. That way we genericize the
6999 // functions in order.
7000 if (!named_object->is_type_declaration()
7001 && !named_object->is_function_declaration()
7002 && !named_object->is_unknown())
7003 this->named_objects_.push_back(named_object);
7004 return named_object;
7008 // We had an existing named object OLD_OBJECT, and we've seen a new
7009 // one NEW_OBJECT with the same name. FIXME: This does not free the
7010 // new object when we don't need it.
7012 Named_object*
7013 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
7015 if (new_object->is_erroneous() && !old_object->is_erroneous())
7016 return new_object;
7018 std::string reason;
7019 switch (old_object->classification())
7021 default:
7022 case Named_object::NAMED_OBJECT_UNINITIALIZED:
7023 go_unreachable();
7025 case Named_object::NAMED_OBJECT_ERRONEOUS:
7026 return old_object;
7028 case Named_object::NAMED_OBJECT_UNKNOWN:
7030 Named_object* real = old_object->unknown_value()->real_named_object();
7031 if (real != NULL)
7032 return this->new_definition(real, new_object);
7033 go_assert(!new_object->is_unknown());
7034 old_object->unknown_value()->set_real_named_object(new_object);
7035 if (!new_object->is_type_declaration()
7036 && !new_object->is_function_declaration())
7037 this->named_objects_.push_back(new_object);
7038 return new_object;
7041 case Named_object::NAMED_OBJECT_CONST:
7042 break;
7044 case Named_object::NAMED_OBJECT_TYPE:
7045 if (new_object->is_type_declaration())
7046 return old_object;
7047 break;
7049 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7050 if (new_object->is_type_declaration())
7051 return old_object;
7052 if (new_object->is_type())
7054 old_object->set_type_value(new_object->type_value());
7055 new_object->type_value()->set_named_object(old_object);
7056 this->named_objects_.push_back(old_object);
7057 return old_object;
7059 break;
7061 case Named_object::NAMED_OBJECT_VAR:
7062 case Named_object::NAMED_OBJECT_RESULT_VAR:
7063 // We have already given an error in the parser for cases where
7064 // one parameter or result variable redeclares another one.
7065 if ((new_object->is_variable()
7066 && new_object->var_value()->is_parameter())
7067 || new_object->is_result_variable())
7068 return old_object;
7069 break;
7071 case Named_object::NAMED_OBJECT_SINK:
7072 go_unreachable();
7074 case Named_object::NAMED_OBJECT_FUNC:
7075 if (new_object->is_function_declaration())
7077 if (!new_object->func_declaration_value()->asm_name().empty())
7078 sorry("__asm__ for function definitions");
7079 Function_type* old_type = old_object->func_value()->type();
7080 Function_type* new_type =
7081 new_object->func_declaration_value()->type();
7082 if (old_type->is_valid_redeclaration(new_type, &reason))
7083 return old_object;
7085 break;
7087 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7089 Function_type* old_type = old_object->func_declaration_value()->type();
7090 if (new_object->is_function_declaration())
7092 Function_type* new_type =
7093 new_object->func_declaration_value()->type();
7094 if (old_type->is_valid_redeclaration(new_type, &reason))
7095 return old_object;
7097 if (new_object->is_function())
7099 Function_type* new_type = new_object->func_value()->type();
7100 if (old_type->is_valid_redeclaration(new_type, &reason))
7102 if (!old_object->func_declaration_value()->asm_name().empty())
7103 sorry("__asm__ for function definitions");
7104 old_object->set_function_value(new_object->func_value());
7105 this->named_objects_.push_back(old_object);
7106 return old_object;
7110 break;
7112 case Named_object::NAMED_OBJECT_PACKAGE:
7113 break;
7116 std::string n = old_object->message_name();
7117 if (reason.empty())
7118 error_at(new_object->location(), "redefinition of %qs", n.c_str());
7119 else
7120 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
7121 reason.c_str());
7123 inform(old_object->location(), "previous definition of %qs was here",
7124 n.c_str());
7126 return old_object;
7129 // Add a named type.
7131 Named_object*
7132 Bindings::add_named_type(Named_type* named_type)
7134 return this->add_named_object(named_type->named_object());
7137 // Add a function.
7139 Named_object*
7140 Bindings::add_function(const std::string& name, const Package* package,
7141 Function* function)
7143 return this->add_named_object(Named_object::make_function(name, package,
7144 function));
7147 // Add a function declaration.
7149 Named_object*
7150 Bindings::add_function_declaration(const std::string& name,
7151 const Package* package,
7152 Function_type* type,
7153 Location location)
7155 Named_object* no = Named_object::make_function_declaration(name, package,
7156 type, location);
7157 return this->add_named_object(no);
7160 // Define a type which was previously declared.
7162 void
7163 Bindings::define_type(Named_object* no, Named_type* type)
7165 no->set_type_value(type);
7166 this->named_objects_.push_back(no);
7169 // Mark all local variables as used. This is used for some types of
7170 // parse error.
7172 void
7173 Bindings::mark_locals_used()
7175 for (std::vector<Named_object*>::iterator p = this->named_objects_.begin();
7176 p != this->named_objects_.end();
7177 ++p)
7178 if ((*p)->is_variable())
7179 (*p)->var_value()->set_is_used();
7182 // Traverse bindings.
7185 Bindings::traverse(Traverse* traverse, bool is_global)
7187 unsigned int traverse_mask = traverse->traverse_mask();
7189 // We don't use an iterator because we permit the traversal to add
7190 // new global objects.
7191 const unsigned int e_or_t = (Traverse::traverse_expressions
7192 | Traverse::traverse_types);
7193 const unsigned int e_or_t_or_s = (e_or_t
7194 | Traverse::traverse_statements);
7195 for (size_t i = 0; i < this->named_objects_.size(); ++i)
7197 Named_object* p = this->named_objects_[i];
7198 int t = TRAVERSE_CONTINUE;
7199 switch (p->classification())
7201 case Named_object::NAMED_OBJECT_CONST:
7202 if ((traverse_mask & Traverse::traverse_constants) != 0)
7203 t = traverse->constant(p, is_global);
7204 if (t == TRAVERSE_CONTINUE
7205 && (traverse_mask & e_or_t) != 0)
7207 Type* tc = p->const_value()->type();
7208 if (tc != NULL
7209 && Type::traverse(tc, traverse) == TRAVERSE_EXIT)
7210 return TRAVERSE_EXIT;
7211 t = p->const_value()->traverse_expression(traverse);
7213 break;
7215 case Named_object::NAMED_OBJECT_VAR:
7216 case Named_object::NAMED_OBJECT_RESULT_VAR:
7217 if ((traverse_mask & Traverse::traverse_variables) != 0)
7218 t = traverse->variable(p);
7219 if (t == TRAVERSE_CONTINUE
7220 && (traverse_mask & e_or_t) != 0)
7222 if (p->is_result_variable()
7223 || p->var_value()->has_type())
7225 Type* tv = (p->is_variable()
7226 ? p->var_value()->type()
7227 : p->result_var_value()->type());
7228 if (tv != NULL
7229 && Type::traverse(tv, traverse) == TRAVERSE_EXIT)
7230 return TRAVERSE_EXIT;
7233 if (t == TRAVERSE_CONTINUE
7234 && (traverse_mask & e_or_t_or_s) != 0
7235 && p->is_variable())
7236 t = p->var_value()->traverse_expression(traverse, traverse_mask);
7237 break;
7239 case Named_object::NAMED_OBJECT_FUNC:
7240 if ((traverse_mask & Traverse::traverse_functions) != 0)
7241 t = traverse->function(p);
7243 if (t == TRAVERSE_CONTINUE
7244 && (traverse_mask
7245 & (Traverse::traverse_variables
7246 | Traverse::traverse_constants
7247 | Traverse::traverse_functions
7248 | Traverse::traverse_blocks
7249 | Traverse::traverse_statements
7250 | Traverse::traverse_expressions
7251 | Traverse::traverse_types)) != 0)
7252 t = p->func_value()->traverse(traverse);
7253 break;
7255 case Named_object::NAMED_OBJECT_PACKAGE:
7256 // These are traversed in Gogo::traverse.
7257 go_assert(is_global);
7258 break;
7260 case Named_object::NAMED_OBJECT_TYPE:
7261 if ((traverse_mask & e_or_t) != 0)
7262 t = Type::traverse(p->type_value(), traverse);
7263 break;
7265 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
7266 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
7267 case Named_object::NAMED_OBJECT_UNKNOWN:
7268 case Named_object::NAMED_OBJECT_ERRONEOUS:
7269 break;
7271 case Named_object::NAMED_OBJECT_SINK:
7272 default:
7273 go_unreachable();
7276 if (t == TRAVERSE_EXIT)
7277 return TRAVERSE_EXIT;
7280 // If we need to traverse types, check the function declarations,
7281 // which have types. Also check any methods of a type declaration.
7282 if ((traverse_mask & e_or_t) != 0)
7284 for (Bindings::const_declarations_iterator p =
7285 this->begin_declarations();
7286 p != this->end_declarations();
7287 ++p)
7289 if (p->second->is_function_declaration())
7291 if (Type::traverse(p->second->func_declaration_value()->type(),
7292 traverse)
7293 == TRAVERSE_EXIT)
7294 return TRAVERSE_EXIT;
7296 else if (p->second->is_type_declaration())
7298 const std::vector<Named_object*>* methods =
7299 p->second->type_declaration_value()->methods();
7300 for (std::vector<Named_object*>::const_iterator pm =
7301 methods->begin();
7302 pm != methods->end();
7303 pm++)
7305 Named_object* no = *pm;
7306 Type *t;
7307 if (no->is_function())
7308 t = no->func_value()->type();
7309 else if (no->is_function_declaration())
7310 t = no->func_declaration_value()->type();
7311 else
7312 continue;
7313 if (Type::traverse(t, traverse) == TRAVERSE_EXIT)
7314 return TRAVERSE_EXIT;
7320 return TRAVERSE_CONTINUE;
7323 // Class Label.
7325 // Clear any references to this label.
7327 void
7328 Label::clear_refs()
7330 for (std::vector<Bindings_snapshot*>::iterator p = this->refs_.begin();
7331 p != this->refs_.end();
7332 ++p)
7333 delete *p;
7334 this->refs_.clear();
7337 // Get the backend representation for a label.
7339 Blabel*
7340 Label::get_backend_label(Translate_context* context)
7342 if (this->blabel_ == NULL)
7344 Function* function = context->function()->func_value();
7345 Bfunction* bfunction = function->get_decl();
7346 this->blabel_ = context->backend()->label(bfunction, this->name_,
7347 this->location_);
7349 return this->blabel_;
7352 // Return an expression for the address of this label.
7354 Bexpression*
7355 Label::get_addr(Translate_context* context, Location location)
7357 Blabel* label = this->get_backend_label(context);
7358 return context->backend()->label_address(label, location);
7361 // Class Unnamed_label.
7363 // Get the backend representation for an unnamed label.
7365 Blabel*
7366 Unnamed_label::get_blabel(Translate_context* context)
7368 if (this->blabel_ == NULL)
7370 Function* function = context->function()->func_value();
7371 Bfunction* bfunction = function->get_decl();
7372 this->blabel_ = context->backend()->label(bfunction, "",
7373 this->location_);
7375 return this->blabel_;
7378 // Return a statement which defines this unnamed label.
7380 Bstatement*
7381 Unnamed_label::get_definition(Translate_context* context)
7383 Blabel* blabel = this->get_blabel(context);
7384 return context->backend()->label_definition_statement(blabel);
7387 // Return a goto statement to this unnamed label.
7389 Bstatement*
7390 Unnamed_label::get_goto(Translate_context* context, Location location)
7392 Blabel* blabel = this->get_blabel(context);
7393 return context->backend()->goto_statement(blabel, location);
7396 // Class Package.
7398 Package::Package(const std::string& pkgpath, Location location)
7399 : pkgpath_(pkgpath), pkgpath_symbol_(Gogo::pkgpath_for_symbol(pkgpath)),
7400 package_name_(), bindings_(new Bindings(NULL)), priority_(0),
7401 location_(location), used_(false), is_imported_(false),
7402 uses_sink_alias_(false)
7404 go_assert(!pkgpath.empty());
7408 // Set the package name.
7410 void
7411 Package::set_package_name(const std::string& package_name, Location location)
7413 go_assert(!package_name.empty());
7414 if (this->package_name_.empty())
7415 this->package_name_ = package_name;
7416 else if (this->package_name_ != package_name)
7417 error_at(location,
7418 "saw two different packages with the same package path %s: %s, %s",
7419 this->pkgpath_.c_str(), this->package_name_.c_str(),
7420 package_name.c_str());
7423 // Set the priority. We may see multiple priorities for an imported
7424 // package; we want to use the largest one.
7426 void
7427 Package::set_priority(int priority)
7429 if (priority > this->priority_)
7430 this->priority_ = priority;
7433 // Determine types of constants. Everything else in a package
7434 // (variables, function declarations) should already have a fixed
7435 // type. Constants may have abstract types.
7437 void
7438 Package::determine_types()
7440 Bindings* bindings = this->bindings_;
7441 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
7442 p != bindings->end_definitions();
7443 ++p)
7445 if ((*p)->is_const())
7446 (*p)->const_value()->determine_type();
7450 // Class Traverse.
7452 // Destructor.
7454 Traverse::~Traverse()
7456 if (this->types_seen_ != NULL)
7457 delete this->types_seen_;
7458 if (this->expressions_seen_ != NULL)
7459 delete this->expressions_seen_;
7462 // Record that we are looking at a type, and return true if we have
7463 // already seen it.
7465 bool
7466 Traverse::remember_type(const Type* type)
7468 if (type->is_error_type())
7469 return true;
7470 go_assert((this->traverse_mask() & traverse_types) != 0
7471 || (this->traverse_mask() & traverse_expressions) != 0);
7472 // We mostly only have to remember named types. But it turns out
7473 // that an interface type can refer to itself without using a name
7474 // by relying on interface inheritance, as in
7475 // type I interface { F() interface{I} }
7476 if (type->classification() != Type::TYPE_NAMED
7477 && type->classification() != Type::TYPE_INTERFACE)
7478 return false;
7479 if (this->types_seen_ == NULL)
7480 this->types_seen_ = new Types_seen();
7481 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
7482 return !ins.second;
7485 // Record that we are looking at an expression, and return true if we
7486 // have already seen it.
7488 bool
7489 Traverse::remember_expression(const Expression* expression)
7491 go_assert((this->traverse_mask() & traverse_types) != 0
7492 || (this->traverse_mask() & traverse_expressions) != 0);
7493 if (this->expressions_seen_ == NULL)
7494 this->expressions_seen_ = new Expressions_seen();
7495 std::pair<Expressions_seen::iterator, bool> ins =
7496 this->expressions_seen_->insert(expression);
7497 return !ins.second;
7500 // The default versions of these functions should never be called: the
7501 // traversal mask indicates which functions may be called.
7504 Traverse::variable(Named_object*)
7506 go_unreachable();
7510 Traverse::constant(Named_object*, bool)
7512 go_unreachable();
7516 Traverse::function(Named_object*)
7518 go_unreachable();
7522 Traverse::block(Block*)
7524 go_unreachable();
7528 Traverse::statement(Block*, size_t*, Statement*)
7530 go_unreachable();
7534 Traverse::expression(Expression**)
7536 go_unreachable();
7540 Traverse::type(Type*)
7542 go_unreachable();
7545 // Class Statement_inserter.
7547 void
7548 Statement_inserter::insert(Statement* s)
7550 if (this->block_ != NULL)
7552 go_assert(this->pindex_ != NULL);
7553 this->block_->insert_statement_before(*this->pindex_, s);
7554 ++*this->pindex_;
7556 else if (this->var_ != NULL)
7557 this->var_->add_preinit_statement(this->gogo_, s);
7558 else
7559 go_assert(saw_errors());