Use backend interface for zero initialization.
[official-gcc.git] / gcc / go / gofrontend / gogo.cc
blobc3c014e5962ece63a0fcb3febe4b1c541bc07ccb
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 "go-c.h"
10 #include "go-dump.h"
11 #include "lex.h"
12 #include "types.h"
13 #include "statements.h"
14 #include "expressions.h"
15 #include "dataflow.h"
16 #include "runtime.h"
17 #include "import.h"
18 #include "export.h"
19 #include "backend.h"
20 #include "gogo.h"
22 // Class Gogo.
24 Gogo::Gogo(Backend* backend, int int_type_size, int pointer_size)
25 : backend_(backend),
26 package_(NULL),
27 functions_(),
28 globals_(new Bindings(NULL)),
29 imports_(),
30 imported_unsafe_(false),
31 packages_(),
32 map_descriptors_(NULL),
33 type_descriptor_decls_(NULL),
34 init_functions_(),
35 need_init_fn_(false),
36 init_fn_name_(),
37 imported_init_fns_(),
38 unique_prefix_(),
39 unique_prefix_specified_(false),
40 interface_types_(),
41 named_types_are_converted_(false)
43 const source_location loc = BUILTINS_LOCATION;
45 Named_type* uint8_type = Type::make_integer_type("uint8", true, 8,
46 RUNTIME_TYPE_KIND_UINT8);
47 this->add_named_type(uint8_type);
48 this->add_named_type(Type::make_integer_type("uint16", true, 16,
49 RUNTIME_TYPE_KIND_UINT16));
50 this->add_named_type(Type::make_integer_type("uint32", true, 32,
51 RUNTIME_TYPE_KIND_UINT32));
52 this->add_named_type(Type::make_integer_type("uint64", true, 64,
53 RUNTIME_TYPE_KIND_UINT64));
55 this->add_named_type(Type::make_integer_type("int8", false, 8,
56 RUNTIME_TYPE_KIND_INT8));
57 this->add_named_type(Type::make_integer_type("int16", false, 16,
58 RUNTIME_TYPE_KIND_INT16));
59 this->add_named_type(Type::make_integer_type("int32", false, 32,
60 RUNTIME_TYPE_KIND_INT32));
61 this->add_named_type(Type::make_integer_type("int64", false, 64,
62 RUNTIME_TYPE_KIND_INT64));
64 this->add_named_type(Type::make_float_type("float32", 32,
65 RUNTIME_TYPE_KIND_FLOAT32));
66 this->add_named_type(Type::make_float_type("float64", 64,
67 RUNTIME_TYPE_KIND_FLOAT64));
69 this->add_named_type(Type::make_complex_type("complex64", 64,
70 RUNTIME_TYPE_KIND_COMPLEX64));
71 this->add_named_type(Type::make_complex_type("complex128", 128,
72 RUNTIME_TYPE_KIND_COMPLEX128));
74 if (int_type_size < 32)
75 int_type_size = 32;
76 this->add_named_type(Type::make_integer_type("uint", true,
77 int_type_size,
78 RUNTIME_TYPE_KIND_UINT));
79 Named_type* int_type = Type::make_integer_type("int", false, int_type_size,
80 RUNTIME_TYPE_KIND_INT);
81 this->add_named_type(int_type);
83 // "byte" is an alias for "uint8". Construct a Named_object which
84 // points to UINT8_TYPE. Note that this breaks the normal pairing
85 // in which a Named_object points to a Named_type which points back
86 // to the same Named_object.
87 Named_object* byte_type = this->declare_type("byte", loc);
88 byte_type->set_type_value(uint8_type);
90 this->add_named_type(Type::make_integer_type("uintptr", true,
91 pointer_size,
92 RUNTIME_TYPE_KIND_UINTPTR));
94 this->add_named_type(Type::make_named_bool_type());
96 this->add_named_type(Type::make_named_string_type());
98 this->globals_->add_constant(Typed_identifier("true",
99 Type::make_boolean_type(),
100 loc),
101 NULL,
102 Expression::make_boolean(true, loc),
104 this->globals_->add_constant(Typed_identifier("false",
105 Type::make_boolean_type(),
106 loc),
107 NULL,
108 Expression::make_boolean(false, loc),
111 this->globals_->add_constant(Typed_identifier("nil", Type::make_nil_type(),
112 loc),
113 NULL,
114 Expression::make_nil(loc),
117 Type* abstract_int_type = Type::make_abstract_integer_type();
118 this->globals_->add_constant(Typed_identifier("iota", abstract_int_type,
119 loc),
120 NULL,
121 Expression::make_iota(),
124 Function_type* new_type = Type::make_function_type(NULL, NULL, NULL, loc);
125 new_type->set_is_varargs();
126 new_type->set_is_builtin();
127 this->globals_->add_function_declaration("new", NULL, new_type, loc);
129 Function_type* make_type = Type::make_function_type(NULL, NULL, NULL, loc);
130 make_type->set_is_varargs();
131 make_type->set_is_builtin();
132 this->globals_->add_function_declaration("make", NULL, make_type, loc);
134 Typed_identifier_list* len_result = new Typed_identifier_list();
135 len_result->push_back(Typed_identifier("", int_type, loc));
136 Function_type* len_type = Type::make_function_type(NULL, NULL, len_result,
137 loc);
138 len_type->set_is_builtin();
139 this->globals_->add_function_declaration("len", NULL, len_type, loc);
141 Typed_identifier_list* cap_result = new Typed_identifier_list();
142 cap_result->push_back(Typed_identifier("", int_type, loc));
143 Function_type* cap_type = Type::make_function_type(NULL, NULL, len_result,
144 loc);
145 cap_type->set_is_builtin();
146 this->globals_->add_function_declaration("cap", NULL, cap_type, loc);
148 Function_type* print_type = Type::make_function_type(NULL, NULL, NULL, loc);
149 print_type->set_is_varargs();
150 print_type->set_is_builtin();
151 this->globals_->add_function_declaration("print", NULL, print_type, loc);
153 print_type = Type::make_function_type(NULL, NULL, NULL, loc);
154 print_type->set_is_varargs();
155 print_type->set_is_builtin();
156 this->globals_->add_function_declaration("println", NULL, print_type, loc);
158 Type *empty = Type::make_interface_type(NULL, loc);
159 Typed_identifier_list* panic_parms = new Typed_identifier_list();
160 panic_parms->push_back(Typed_identifier("e", empty, loc));
161 Function_type *panic_type = Type::make_function_type(NULL, panic_parms,
162 NULL, loc);
163 panic_type->set_is_builtin();
164 this->globals_->add_function_declaration("panic", NULL, panic_type, loc);
166 Typed_identifier_list* recover_result = new Typed_identifier_list();
167 recover_result->push_back(Typed_identifier("", empty, loc));
168 Function_type* recover_type = Type::make_function_type(NULL, NULL,
169 recover_result,
170 loc);
171 recover_type->set_is_builtin();
172 this->globals_->add_function_declaration("recover", NULL, recover_type, loc);
174 Function_type* close_type = Type::make_function_type(NULL, NULL, NULL, loc);
175 close_type->set_is_varargs();
176 close_type->set_is_builtin();
177 this->globals_->add_function_declaration("close", NULL, close_type, loc);
179 Typed_identifier_list* copy_result = new Typed_identifier_list();
180 copy_result->push_back(Typed_identifier("", int_type, loc));
181 Function_type* copy_type = Type::make_function_type(NULL, NULL,
182 copy_result, loc);
183 copy_type->set_is_varargs();
184 copy_type->set_is_builtin();
185 this->globals_->add_function_declaration("copy", NULL, copy_type, loc);
187 Function_type* append_type = Type::make_function_type(NULL, NULL, NULL, loc);
188 append_type->set_is_varargs();
189 append_type->set_is_builtin();
190 this->globals_->add_function_declaration("append", NULL, append_type, loc);
192 Function_type* complex_type = Type::make_function_type(NULL, NULL, NULL, loc);
193 complex_type->set_is_varargs();
194 complex_type->set_is_builtin();
195 this->globals_->add_function_declaration("complex", NULL, complex_type, loc);
197 Function_type* real_type = Type::make_function_type(NULL, NULL, NULL, loc);
198 real_type->set_is_varargs();
199 real_type->set_is_builtin();
200 this->globals_->add_function_declaration("real", NULL, real_type, loc);
202 Function_type* imag_type = Type::make_function_type(NULL, NULL, NULL, loc);
203 imag_type->set_is_varargs();
204 imag_type->set_is_builtin();
205 this->globals_->add_function_declaration("imag", NULL, imag_type, loc);
208 // Munge name for use in an error message.
210 std::string
211 Gogo::message_name(const std::string& name)
213 return go_localize_identifier(Gogo::unpack_hidden_name(name).c_str());
216 // Get the package name.
218 const std::string&
219 Gogo::package_name() const
221 go_assert(this->package_ != NULL);
222 return this->package_->name();
225 // Set the package name.
227 void
228 Gogo::set_package_name(const std::string& package_name,
229 source_location location)
231 if (this->package_ != NULL && this->package_->name() != package_name)
233 error_at(location, "expected package %<%s%>",
234 Gogo::message_name(this->package_->name()).c_str());
235 return;
238 // If the user did not specify a unique prefix, we always use "go".
239 // This in effect requires that the package name be unique.
240 if (this->unique_prefix_.empty())
241 this->unique_prefix_ = "go";
243 this->package_ = this->register_package(package_name, this->unique_prefix_,
244 location);
246 // We used to permit people to qualify symbols with the current
247 // package name (e.g., P.x), but we no longer do.
248 // this->globals_->add_package(package_name, this->package_);
250 if (this->is_main_package())
252 // Declare "main" as a function which takes no parameters and
253 // returns no value.
254 this->declare_function("main",
255 Type::make_function_type(NULL, NULL, NULL,
256 BUILTINS_LOCATION),
257 BUILTINS_LOCATION);
261 // Return whether this is the "main" package. This is not true if
262 // -fgo-prefix was used.
264 bool
265 Gogo::is_main_package() const
267 return this->package_name() == "main" && !this->unique_prefix_specified_;
270 // Import a package.
272 void
273 Gogo::import_package(const std::string& filename,
274 const std::string& local_name,
275 bool is_local_name_exported,
276 source_location location)
278 if (filename == "unsafe")
280 this->import_unsafe(local_name, is_local_name_exported, location);
281 return;
284 Imports::const_iterator p = this->imports_.find(filename);
285 if (p != this->imports_.end())
287 Package* package = p->second;
288 package->set_location(location);
289 package->set_is_imported();
290 std::string ln = local_name;
291 bool is_ln_exported = is_local_name_exported;
292 if (ln.empty())
294 ln = package->name();
295 is_ln_exported = Lex::is_exported_name(ln);
297 if (ln == ".")
299 Bindings* bindings = package->bindings();
300 for (Bindings::const_declarations_iterator p =
301 bindings->begin_declarations();
302 p != bindings->end_declarations();
303 ++p)
304 this->add_named_object(p->second);
306 else if (ln == "_")
307 package->set_uses_sink_alias();
308 else
310 ln = this->pack_hidden_name(ln, is_ln_exported);
311 this->package_->bindings()->add_package(ln, package);
313 return;
316 Import::Stream* stream = Import::open_package(filename, location);
317 if (stream == NULL)
319 error_at(location, "import file %qs not found", filename.c_str());
320 return;
323 Import imp(stream, location);
324 imp.register_builtin_types(this);
325 Package* package = imp.import(this, local_name, is_local_name_exported);
326 if (package != NULL)
328 if (package->name() == this->package_name()
329 && package->unique_prefix() == this->unique_prefix())
330 error_at(location,
331 ("imported package uses same package name and prefix "
332 "as package being compiled (see -fgo-prefix option)"));
334 this->imports_.insert(std::make_pair(filename, package));
335 package->set_is_imported();
338 delete stream;
341 // Add an import control function for an imported package to the list.
343 void
344 Gogo::add_import_init_fn(const std::string& package_name,
345 const std::string& init_name, int prio)
347 for (std::set<Import_init>::const_iterator p =
348 this->imported_init_fns_.begin();
349 p != this->imported_init_fns_.end();
350 ++p)
352 if (p->init_name() == init_name
353 && (p->package_name() != package_name || p->priority() != prio))
355 error("duplicate package initialization name %qs",
356 Gogo::message_name(init_name).c_str());
357 inform(UNKNOWN_LOCATION, "used by package %qs at priority %d",
358 Gogo::message_name(p->package_name()).c_str(),
359 p->priority());
360 inform(UNKNOWN_LOCATION, " and by package %qs at priority %d",
361 Gogo::message_name(package_name).c_str(), prio);
362 return;
366 this->imported_init_fns_.insert(Import_init(package_name, init_name,
367 prio));
370 // Return whether we are at the global binding level.
372 bool
373 Gogo::in_global_scope() const
375 return this->functions_.empty();
378 // Return the current binding contour.
380 Bindings*
381 Gogo::current_bindings()
383 if (!this->functions_.empty())
384 return this->functions_.back().blocks.back()->bindings();
385 else if (this->package_ != NULL)
386 return this->package_->bindings();
387 else
388 return this->globals_;
391 const Bindings*
392 Gogo::current_bindings() const
394 if (!this->functions_.empty())
395 return this->functions_.back().blocks.back()->bindings();
396 else if (this->package_ != NULL)
397 return this->package_->bindings();
398 else
399 return this->globals_;
402 // Return the current block.
404 Block*
405 Gogo::current_block()
407 if (this->functions_.empty())
408 return NULL;
409 else
410 return this->functions_.back().blocks.back();
413 // Look up a name in the current binding contour. If PFUNCTION is not
414 // NULL, set it to the function in which the name is defined, or NULL
415 // if the name is defined in global scope.
417 Named_object*
418 Gogo::lookup(const std::string& name, Named_object** pfunction) const
420 if (pfunction != NULL)
421 *pfunction = NULL;
423 if (Gogo::is_sink_name(name))
424 return Named_object::make_sink();
426 for (Open_functions::const_reverse_iterator p = this->functions_.rbegin();
427 p != this->functions_.rend();
428 ++p)
430 Named_object* ret = p->blocks.back()->bindings()->lookup(name);
431 if (ret != NULL)
433 if (pfunction != NULL)
434 *pfunction = p->function;
435 return ret;
439 if (this->package_ != NULL)
441 Named_object* ret = this->package_->bindings()->lookup(name);
442 if (ret != NULL)
444 if (ret->package() != NULL)
445 ret->package()->set_used();
446 return ret;
450 // We do not look in the global namespace. If we did, the global
451 // namespace would effectively hide names which were defined in
452 // package scope which we have not yet seen. Instead,
453 // define_global_names is called after parsing is over to connect
454 // undefined names at package scope with names defined at global
455 // scope.
457 return NULL;
460 // Look up a name in the current block, without searching enclosing
461 // blocks.
463 Named_object*
464 Gogo::lookup_in_block(const std::string& name) const
466 go_assert(!this->functions_.empty());
467 go_assert(!this->functions_.back().blocks.empty());
468 return this->functions_.back().blocks.back()->bindings()->lookup_local(name);
471 // Look up a name in the global namespace.
473 Named_object*
474 Gogo::lookup_global(const char* name) const
476 return this->globals_->lookup(name);
479 // Add an imported package.
481 Package*
482 Gogo::add_imported_package(const std::string& real_name,
483 const std::string& alias_arg,
484 bool is_alias_exported,
485 const std::string& unique_prefix,
486 source_location location,
487 bool* padd_to_globals)
489 // FIXME: Now that we compile packages as a whole, should we permit
490 // importing the current package?
491 if (this->package_name() == real_name
492 && this->unique_prefix() == unique_prefix)
494 *padd_to_globals = false;
495 if (!alias_arg.empty() && alias_arg != ".")
497 std::string alias = this->pack_hidden_name(alias_arg,
498 is_alias_exported);
499 this->package_->bindings()->add_package(alias, this->package_);
501 return this->package_;
503 else if (alias_arg == ".")
505 *padd_to_globals = true;
506 return this->register_package(real_name, unique_prefix, location);
508 else if (alias_arg == "_")
510 Package* ret = this->register_package(real_name, unique_prefix, location);
511 ret->set_uses_sink_alias();
512 return ret;
514 else
516 *padd_to_globals = false;
517 std::string alias = alias_arg;
518 if (alias.empty())
520 alias = real_name;
521 is_alias_exported = Lex::is_exported_name(alias);
523 alias = this->pack_hidden_name(alias, is_alias_exported);
524 Named_object* no = this->add_package(real_name, alias, unique_prefix,
525 location);
526 if (!no->is_package())
527 return NULL;
528 return no->package_value();
532 // Add a package.
534 Named_object*
535 Gogo::add_package(const std::string& real_name, const std::string& alias,
536 const std::string& unique_prefix, source_location location)
538 go_assert(this->in_global_scope());
540 // Register the package. Note that we might have already seen it in
541 // an earlier import.
542 Package* package = this->register_package(real_name, unique_prefix, location);
544 return this->package_->bindings()->add_package(alias, package);
547 // Register a package. This package may or may not be imported. This
548 // returns the Package structure for the package, creating if it
549 // necessary.
551 Package*
552 Gogo::register_package(const std::string& package_name,
553 const std::string& unique_prefix,
554 source_location location)
556 go_assert(!unique_prefix.empty() && !package_name.empty());
557 std::string name = unique_prefix + '.' + package_name;
558 Package* package = NULL;
559 std::pair<Packages::iterator, bool> ins =
560 this->packages_.insert(std::make_pair(name, package));
561 if (!ins.second)
563 // We have seen this package name before.
564 package = ins.first->second;
565 go_assert(package != NULL);
566 go_assert(package->name() == package_name
567 && package->unique_prefix() == unique_prefix);
568 if (package->location() == UNKNOWN_LOCATION)
569 package->set_location(location);
571 else
573 // First time we have seen this package name.
574 package = new Package(package_name, unique_prefix, location);
575 go_assert(ins.first->second == NULL);
576 ins.first->second = package;
579 return package;
582 // Start compiling a function.
584 Named_object*
585 Gogo::start_function(const std::string& name, Function_type* type,
586 bool add_method_to_type, source_location location)
588 bool at_top_level = this->functions_.empty();
590 Block* block = new Block(NULL, location);
592 Function* enclosing = (at_top_level
593 ? NULL
594 : this->functions_.back().function->func_value());
596 Function* function = new Function(type, enclosing, block, location);
598 if (type->is_method())
600 const Typed_identifier* receiver = type->receiver();
601 Variable* this_param = new Variable(receiver->type(), NULL, false,
602 true, true, location);
603 std::string name = receiver->name();
604 if (name.empty())
606 // We need to give receivers a name since they wind up in
607 // DECL_ARGUMENTS. FIXME.
608 static unsigned int count;
609 char buf[50];
610 snprintf(buf, sizeof buf, "r.%u", count);
611 ++count;
612 name = buf;
614 block->bindings()->add_variable(name, NULL, this_param);
617 const Typed_identifier_list* parameters = type->parameters();
618 bool is_varargs = type->is_varargs();
619 if (parameters != NULL)
621 for (Typed_identifier_list::const_iterator p = parameters->begin();
622 p != parameters->end();
623 ++p)
625 Variable* param = new Variable(p->type(), NULL, false, true, false,
626 location);
627 if (is_varargs && p + 1 == parameters->end())
628 param->set_is_varargs_parameter();
630 std::string name = p->name();
631 if (name.empty() || Gogo::is_sink_name(name))
633 // We need to give parameters a name since they wind up
634 // in DECL_ARGUMENTS. FIXME.
635 static unsigned int count;
636 char buf[50];
637 snprintf(buf, sizeof buf, "p.%u", count);
638 ++count;
639 name = buf;
641 block->bindings()->add_variable(name, NULL, param);
645 function->create_result_variables(this);
647 const std::string* pname;
648 std::string nested_name;
649 bool is_init = false;
650 if (Gogo::unpack_hidden_name(name) == "init" && !type->is_method())
652 if ((type->parameters() != NULL && !type->parameters()->empty())
653 || (type->results() != NULL && !type->results()->empty()))
654 error_at(location,
655 "func init must have no arguments and no return values");
656 // There can be multiple "init" functions, so give them each a
657 // different name.
658 static int init_count;
659 char buf[30];
660 snprintf(buf, sizeof buf, ".$init%d", init_count);
661 ++init_count;
662 nested_name = buf;
663 pname = &nested_name;
664 is_init = true;
666 else if (!name.empty())
667 pname = &name;
668 else
670 // Invent a name for a nested function.
671 static int nested_count;
672 char buf[30];
673 snprintf(buf, sizeof buf, ".$nested%d", nested_count);
674 ++nested_count;
675 nested_name = buf;
676 pname = &nested_name;
679 Named_object* ret;
680 if (Gogo::is_sink_name(*pname))
682 static int sink_count;
683 char buf[30];
684 snprintf(buf, sizeof buf, ".$sink%d", sink_count);
685 ++sink_count;
686 ret = Named_object::make_function(buf, NULL, function);
688 else if (!type->is_method())
690 ret = this->package_->bindings()->add_function(*pname, NULL, function);
691 if (!ret->is_function() || ret->func_value() != function)
693 // Redefinition error. Invent a name to avoid knockon
694 // errors.
695 static int redefinition_count;
696 char buf[30];
697 snprintf(buf, sizeof buf, ".$redefined%d", redefinition_count);
698 ++redefinition_count;
699 ret = this->package_->bindings()->add_function(buf, NULL, function);
702 else
704 if (!add_method_to_type)
705 ret = Named_object::make_function(name, NULL, function);
706 else
708 go_assert(at_top_level);
709 Type* rtype = type->receiver()->type();
711 // We want to look through the pointer created by the
712 // parser, without getting an error if the type is not yet
713 // defined.
714 if (rtype->classification() == Type::TYPE_POINTER)
715 rtype = rtype->points_to();
717 if (rtype->is_error_type())
718 ret = Named_object::make_function(name, NULL, function);
719 else if (rtype->named_type() != NULL)
721 ret = rtype->named_type()->add_method(name, function);
722 if (!ret->is_function())
724 // Redefinition error.
725 ret = Named_object::make_function(name, NULL, function);
728 else if (rtype->forward_declaration_type() != NULL)
730 Named_object* type_no =
731 rtype->forward_declaration_type()->named_object();
732 if (type_no->is_unknown())
734 // If we are seeing methods it really must be a
735 // type. Declare it as such. An alternative would
736 // be to support lists of methods for unknown
737 // expressions. Either way the error messages if
738 // this is not a type are going to get confusing.
739 Named_object* declared =
740 this->declare_package_type(type_no->name(),
741 type_no->location());
742 go_assert(declared
743 == type_no->unknown_value()->real_named_object());
745 ret = rtype->forward_declaration_type()->add_method(name,
746 function);
748 else
749 go_unreachable();
751 this->package_->bindings()->add_method(ret);
754 this->functions_.resize(this->functions_.size() + 1);
755 Open_function& of(this->functions_.back());
756 of.function = ret;
757 of.blocks.push_back(block);
759 if (is_init)
761 this->init_functions_.push_back(ret);
762 this->need_init_fn_ = true;
765 return ret;
768 // Finish compiling a function.
770 void
771 Gogo::finish_function(source_location location)
773 this->finish_block(location);
774 go_assert(this->functions_.back().blocks.empty());
775 this->functions_.pop_back();
778 // Return the current function.
780 Named_object*
781 Gogo::current_function() const
783 go_assert(!this->functions_.empty());
784 return this->functions_.back().function;
787 // Start a new block.
789 void
790 Gogo::start_block(source_location location)
792 go_assert(!this->functions_.empty());
793 Block* block = new Block(this->current_block(), location);
794 this->functions_.back().blocks.push_back(block);
797 // Finish a block.
799 Block*
800 Gogo::finish_block(source_location location)
802 go_assert(!this->functions_.empty());
803 go_assert(!this->functions_.back().blocks.empty());
804 Block* block = this->functions_.back().blocks.back();
805 this->functions_.back().blocks.pop_back();
806 block->set_end_location(location);
807 return block;
810 // Add an unknown name.
812 Named_object*
813 Gogo::add_unknown_name(const std::string& name, source_location location)
815 return this->package_->bindings()->add_unknown_name(name, location);
818 // Declare a function.
820 Named_object*
821 Gogo::declare_function(const std::string& name, Function_type* type,
822 source_location location)
824 if (!type->is_method())
825 return this->current_bindings()->add_function_declaration(name, NULL, type,
826 location);
827 else
829 // We don't bother to add this to the list of global
830 // declarations.
831 Type* rtype = type->receiver()->type();
833 // We want to look through the pointer created by the
834 // parser, without getting an error if the type is not yet
835 // defined.
836 if (rtype->classification() == Type::TYPE_POINTER)
837 rtype = rtype->points_to();
839 if (rtype->is_error_type())
840 return NULL;
841 else if (rtype->named_type() != NULL)
842 return rtype->named_type()->add_method_declaration(name, NULL, type,
843 location);
844 else if (rtype->forward_declaration_type() != NULL)
846 Forward_declaration_type* ftype = rtype->forward_declaration_type();
847 return ftype->add_method_declaration(name, type, location);
849 else
850 go_unreachable();
854 // Add a label definition.
856 Label*
857 Gogo::add_label_definition(const std::string& label_name,
858 source_location location)
860 go_assert(!this->functions_.empty());
861 Function* func = this->functions_.back().function->func_value();
862 Label* label = func->add_label_definition(label_name, location);
863 this->add_statement(Statement::make_label_statement(label, location));
864 return label;
867 // Add a label reference.
869 Label*
870 Gogo::add_label_reference(const std::string& label_name)
872 go_assert(!this->functions_.empty());
873 Function* func = this->functions_.back().function->func_value();
874 return func->add_label_reference(label_name);
877 // Add a statement.
879 void
880 Gogo::add_statement(Statement* statement)
882 go_assert(!this->functions_.empty()
883 && !this->functions_.back().blocks.empty());
884 this->functions_.back().blocks.back()->add_statement(statement);
887 // Add a block.
889 void
890 Gogo::add_block(Block* block, source_location location)
892 go_assert(!this->functions_.empty()
893 && !this->functions_.back().blocks.empty());
894 Statement* statement = Statement::make_block_statement(block, location);
895 this->functions_.back().blocks.back()->add_statement(statement);
898 // Add a constant.
900 Named_object*
901 Gogo::add_constant(const Typed_identifier& tid, Expression* expr,
902 int iota_value)
904 return this->current_bindings()->add_constant(tid, NULL, expr, iota_value);
907 // Add a type.
909 void
910 Gogo::add_type(const std::string& name, Type* type, source_location location)
912 Named_object* no = this->current_bindings()->add_type(name, NULL, type,
913 location);
914 if (!this->in_global_scope() && no->is_type())
915 no->type_value()->set_in_function(this->functions_.back().function);
918 // Add a named type.
920 void
921 Gogo::add_named_type(Named_type* type)
923 go_assert(this->in_global_scope());
924 this->current_bindings()->add_named_type(type);
927 // Declare a type.
929 Named_object*
930 Gogo::declare_type(const std::string& name, source_location location)
932 Bindings* bindings = this->current_bindings();
933 Named_object* no = bindings->add_type_declaration(name, NULL, location);
934 if (!this->in_global_scope() && no->is_type_declaration())
936 Named_object* f = this->functions_.back().function;
937 no->type_declaration_value()->set_in_function(f);
939 return no;
942 // Declare a type at the package level.
944 Named_object*
945 Gogo::declare_package_type(const std::string& name, source_location location)
947 return this->package_->bindings()->add_type_declaration(name, NULL, location);
950 // Define a type which was already declared.
952 void
953 Gogo::define_type(Named_object* no, Named_type* type)
955 this->current_bindings()->define_type(no, type);
958 // Add a variable.
960 Named_object*
961 Gogo::add_variable(const std::string& name, Variable* variable)
963 Named_object* no = this->current_bindings()->add_variable(name, NULL,
964 variable);
966 // In a function the middle-end wants to see a DECL_EXPR node.
967 if (no != NULL
968 && no->is_variable()
969 && !no->var_value()->is_parameter()
970 && !this->functions_.empty())
971 this->add_statement(Statement::make_variable_declaration(no));
973 return no;
976 // Add a sink--a reference to the blank identifier _.
978 Named_object*
979 Gogo::add_sink()
981 return Named_object::make_sink();
984 // Add a named object.
986 void
987 Gogo::add_named_object(Named_object* no)
989 this->current_bindings()->add_named_object(no);
992 // Record that we've seen an interface type.
994 void
995 Gogo::record_interface_type(Interface_type* itype)
997 this->interface_types_.push_back(itype);
1000 // Return a name for a thunk object.
1002 std::string
1003 Gogo::thunk_name()
1005 static int thunk_count;
1006 char thunk_name[50];
1007 snprintf(thunk_name, sizeof thunk_name, "$thunk%d", thunk_count);
1008 ++thunk_count;
1009 return thunk_name;
1012 // Return whether a function is a thunk.
1014 bool
1015 Gogo::is_thunk(const Named_object* no)
1017 return no->name().compare(0, 6, "$thunk") == 0;
1020 // Define the global names. We do this only after parsing all the
1021 // input files, because the program might define the global names
1022 // itself.
1024 void
1025 Gogo::define_global_names()
1027 for (Bindings::const_declarations_iterator p =
1028 this->globals_->begin_declarations();
1029 p != this->globals_->end_declarations();
1030 ++p)
1032 Named_object* global_no = p->second;
1033 std::string name(Gogo::pack_hidden_name(global_no->name(), false));
1034 Named_object* no = this->package_->bindings()->lookup(name);
1035 if (no == NULL)
1036 continue;
1037 no = no->resolve();
1038 if (no->is_type_declaration())
1040 if (global_no->is_type())
1042 if (no->type_declaration_value()->has_methods())
1043 error_at(no->location(),
1044 "may not define methods for global type");
1045 no->set_type_value(global_no->type_value());
1047 else
1049 error_at(no->location(), "expected type");
1050 Type* errtype = Type::make_error_type();
1051 Named_object* err = Named_object::make_type("error", NULL,
1052 errtype,
1053 BUILTINS_LOCATION);
1054 no->set_type_value(err->type_value());
1057 else if (no->is_unknown())
1058 no->unknown_value()->set_real_named_object(global_no);
1062 // Clear out names in file scope.
1064 void
1065 Gogo::clear_file_scope()
1067 this->package_->bindings()->clear_file_scope();
1069 // Warn about packages which were imported but not used.
1070 for (Packages::iterator p = this->packages_.begin();
1071 p != this->packages_.end();
1072 ++p)
1074 Package* package = p->second;
1075 if (package != this->package_
1076 && package->is_imported()
1077 && !package->used()
1078 && !package->uses_sink_alias()
1079 && !saw_errors())
1080 error_at(package->location(), "imported and not used: %s",
1081 Gogo::message_name(package->name()).c_str());
1082 package->clear_is_imported();
1083 package->clear_uses_sink_alias();
1084 package->clear_used();
1088 // Traverse the tree.
1090 void
1091 Gogo::traverse(Traverse* traverse)
1093 // Traverse the current package first for consistency. The other
1094 // packages will only contain imported types, constants, and
1095 // declarations.
1096 if (this->package_->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1097 return;
1098 for (Packages::const_iterator p = this->packages_.begin();
1099 p != this->packages_.end();
1100 ++p)
1102 if (p->second != this->package_)
1104 if (p->second->bindings()->traverse(traverse, true) == TRAVERSE_EXIT)
1105 break;
1110 // Traversal class used to verify types.
1112 class Verify_types : public Traverse
1114 public:
1115 Verify_types()
1116 : Traverse(traverse_types)
1120 type(Type*);
1123 // Verify that a type is correct.
1126 Verify_types::type(Type* t)
1128 if (!t->verify())
1129 return TRAVERSE_SKIP_COMPONENTS;
1130 return TRAVERSE_CONTINUE;
1133 // Verify that all types are correct.
1135 void
1136 Gogo::verify_types()
1138 Verify_types traverse;
1139 this->traverse(&traverse);
1142 // Traversal class used to lower parse tree.
1144 class Lower_parse_tree : public Traverse
1146 public:
1147 Lower_parse_tree(Gogo* gogo, Named_object* function)
1148 : Traverse(traverse_variables
1149 | traverse_constants
1150 | traverse_functions
1151 | traverse_statements
1152 | traverse_expressions),
1153 gogo_(gogo), function_(function), iota_value_(-1)
1157 variable(Named_object*);
1160 constant(Named_object*, bool);
1163 function(Named_object*);
1166 statement(Block*, size_t* pindex, Statement*);
1169 expression(Expression**);
1171 private:
1172 // General IR.
1173 Gogo* gogo_;
1174 // The function we are traversing.
1175 Named_object* function_;
1176 // Value to use for the predeclared constant iota.
1177 int iota_value_;
1180 // Lower variables. We handle variables specially to break loops in
1181 // which a variable initialization expression refers to itself. The
1182 // loop breaking is in lower_init_expression.
1185 Lower_parse_tree::variable(Named_object* no)
1187 if (no->is_variable())
1188 no->var_value()->lower_init_expression(this->gogo_, this->function_);
1189 return TRAVERSE_CONTINUE;
1192 // Lower constants. We handle constants specially so that we can set
1193 // the right value for the predeclared constant iota. This works in
1194 // conjunction with the way we lower Const_expression objects.
1197 Lower_parse_tree::constant(Named_object* no, bool)
1199 Named_constant* nc = no->const_value();
1201 // Don't get into trouble if the constant's initializer expression
1202 // refers to the constant itself.
1203 if (nc->lowering())
1204 return TRAVERSE_CONTINUE;
1205 nc->set_lowering();
1207 go_assert(this->iota_value_ == -1);
1208 this->iota_value_ = nc->iota_value();
1209 nc->traverse_expression(this);
1210 this->iota_value_ = -1;
1212 nc->clear_lowering();
1214 // We will traverse the expression a second time, but that will be
1215 // fast.
1217 return TRAVERSE_CONTINUE;
1220 // Lower function closure types. Record the function while lowering
1221 // it, so that we can pass it down when lowering an expression.
1224 Lower_parse_tree::function(Named_object* no)
1226 no->func_value()->set_closure_type();
1228 go_assert(this->function_ == NULL);
1229 this->function_ = no;
1230 int t = no->func_value()->traverse(this);
1231 this->function_ = NULL;
1233 if (t == TRAVERSE_EXIT)
1234 return t;
1235 return TRAVERSE_SKIP_COMPONENTS;
1238 // Lower statement parse trees.
1241 Lower_parse_tree::statement(Block* block, size_t* pindex, Statement* sorig)
1243 // Lower the expressions first.
1244 int t = sorig->traverse_contents(this);
1245 if (t == TRAVERSE_EXIT)
1246 return t;
1248 // Keep lowering until nothing changes.
1249 Statement* s = sorig;
1250 while (true)
1252 Statement* snew = s->lower(this->gogo_, this->function_, block);
1253 if (snew == s)
1254 break;
1255 s = snew;
1256 t = s->traverse_contents(this);
1257 if (t == TRAVERSE_EXIT)
1258 return t;
1261 if (s != sorig)
1262 block->replace_statement(*pindex, s);
1264 return TRAVERSE_SKIP_COMPONENTS;
1267 // Lower expression parse trees.
1270 Lower_parse_tree::expression(Expression** pexpr)
1272 // We have to lower all subexpressions first, so that we can get
1273 // their type if necessary. This is awkward, because we don't have
1274 // a postorder traversal pass.
1275 if ((*pexpr)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1276 return TRAVERSE_EXIT;
1277 // Keep lowering until nothing changes.
1278 while (true)
1280 Expression* e = *pexpr;
1281 Expression* enew = e->lower(this->gogo_, this->function_,
1282 this->iota_value_);
1283 if (enew == e)
1284 break;
1285 *pexpr = enew;
1287 return TRAVERSE_SKIP_COMPONENTS;
1290 // Lower the parse tree. This is called after the parse is complete,
1291 // when all names should be resolved.
1293 void
1294 Gogo::lower_parse_tree()
1296 Lower_parse_tree lower_parse_tree(this, NULL);
1297 this->traverse(&lower_parse_tree);
1300 // Lower a block.
1302 void
1303 Gogo::lower_block(Named_object* function, Block* block)
1305 Lower_parse_tree lower_parse_tree(this, function);
1306 block->traverse(&lower_parse_tree);
1309 // Lower an expression.
1311 void
1312 Gogo::lower_expression(Named_object* function, Expression** pexpr)
1314 Lower_parse_tree lower_parse_tree(this, function);
1315 lower_parse_tree.expression(pexpr);
1318 // Lower a constant. This is called when lowering a reference to a
1319 // constant. We have to make sure that the constant has already been
1320 // lowered.
1322 void
1323 Gogo::lower_constant(Named_object* no)
1325 go_assert(no->is_const());
1326 Lower_parse_tree lower(this, NULL);
1327 lower.constant(no, false);
1330 // Look for interface types to finalize methods of inherited
1331 // interfaces.
1333 class Finalize_methods : public Traverse
1335 public:
1336 Finalize_methods(Gogo* gogo)
1337 : Traverse(traverse_types),
1338 gogo_(gogo)
1342 type(Type*);
1344 private:
1345 Gogo* gogo_;
1348 // Finalize the methods of an interface type.
1351 Finalize_methods::type(Type* t)
1353 // Check the classification so that we don't finalize the methods
1354 // twice for a named interface type.
1355 switch (t->classification())
1357 case Type::TYPE_INTERFACE:
1358 t->interface_type()->finalize_methods();
1359 break;
1361 case Type::TYPE_NAMED:
1363 // We have to finalize the methods of the real type first.
1364 // But if the real type is a struct type, then we only want to
1365 // finalize the methods of the field types, not of the struct
1366 // type itself. We don't want to add methods to the struct,
1367 // since it has a name.
1368 Type* rt = t->named_type()->real_type();
1369 if (rt->classification() != Type::TYPE_STRUCT)
1371 if (Type::traverse(rt, this) == TRAVERSE_EXIT)
1372 return TRAVERSE_EXIT;
1374 else
1376 if (rt->struct_type()->traverse_field_types(this) == TRAVERSE_EXIT)
1377 return TRAVERSE_EXIT;
1380 t->named_type()->finalize_methods(this->gogo_);
1382 return TRAVERSE_SKIP_COMPONENTS;
1385 case Type::TYPE_STRUCT:
1386 t->struct_type()->finalize_methods(this->gogo_);
1387 break;
1389 default:
1390 break;
1393 return TRAVERSE_CONTINUE;
1396 // Finalize method lists and build stub methods for types.
1398 void
1399 Gogo::finalize_methods()
1401 Finalize_methods finalize(this);
1402 this->traverse(&finalize);
1405 // Set types for unspecified variables and constants.
1407 void
1408 Gogo::determine_types()
1410 Bindings* bindings = this->current_bindings();
1411 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
1412 p != bindings->end_definitions();
1413 ++p)
1415 if ((*p)->is_function())
1416 (*p)->func_value()->determine_types();
1417 else if ((*p)->is_variable())
1418 (*p)->var_value()->determine_type();
1419 else if ((*p)->is_const())
1420 (*p)->const_value()->determine_type();
1422 // See if a variable requires us to build an initialization
1423 // function. We know that we will see all global variables
1424 // here.
1425 if (!this->need_init_fn_ && (*p)->is_variable())
1427 Variable* variable = (*p)->var_value();
1429 // If this is a global variable which requires runtime
1430 // initialization, we need an initialization function.
1431 if (!variable->is_global())
1433 else if (variable->init() == NULL)
1435 else if (variable->type()->interface_type() != NULL)
1436 this->need_init_fn_ = true;
1437 else if (variable->init()->is_constant())
1439 else if (!variable->init()->is_composite_literal())
1440 this->need_init_fn_ = true;
1441 else if (variable->init()->is_nonconstant_composite_literal())
1442 this->need_init_fn_ = true;
1444 // If this is a global variable which holds a pointer value,
1445 // then we need an initialization function to register it as a
1446 // GC root.
1447 if (variable->is_global() && variable->type()->has_pointer())
1448 this->need_init_fn_ = true;
1452 // Determine the types of constants in packages.
1453 for (Packages::const_iterator p = this->packages_.begin();
1454 p != this->packages_.end();
1455 ++p)
1456 p->second->determine_types();
1459 // Traversal class used for type checking.
1461 class Check_types_traverse : public Traverse
1463 public:
1464 Check_types_traverse(Gogo* gogo)
1465 : Traverse(traverse_variables
1466 | traverse_constants
1467 | traverse_functions
1468 | traverse_statements
1469 | traverse_expressions),
1470 gogo_(gogo)
1474 variable(Named_object*);
1477 constant(Named_object*, bool);
1480 function(Named_object*);
1483 statement(Block*, size_t* pindex, Statement*);
1486 expression(Expression**);
1488 private:
1489 // General IR.
1490 Gogo* gogo_;
1493 // Check that a variable initializer has the right type.
1496 Check_types_traverse::variable(Named_object* named_object)
1498 if (named_object->is_variable())
1500 Variable* var = named_object->var_value();
1502 // Give error if variable type is not defined.
1503 var->type()->base();
1505 Expression* init = var->init();
1506 std::string reason;
1507 if (init != NULL
1508 && !Type::are_assignable(var->type(), init->type(), &reason))
1510 if (reason.empty())
1511 error_at(var->location(), "incompatible type in initialization");
1512 else
1513 error_at(var->location(),
1514 "incompatible type in initialization (%s)",
1515 reason.c_str());
1516 var->clear_init();
1519 return TRAVERSE_CONTINUE;
1522 // Check that a constant initializer has the right type.
1525 Check_types_traverse::constant(Named_object* named_object, bool)
1527 Named_constant* constant = named_object->const_value();
1528 Type* ctype = constant->type();
1529 if (ctype->integer_type() == NULL
1530 && ctype->float_type() == NULL
1531 && ctype->complex_type() == NULL
1532 && !ctype->is_boolean_type()
1533 && !ctype->is_string_type())
1535 if (ctype->is_nil_type())
1536 error_at(constant->location(), "const initializer cannot be nil");
1537 else if (!ctype->is_error())
1538 error_at(constant->location(), "invalid constant type");
1539 constant->set_error();
1541 else if (!constant->expr()->is_constant())
1543 error_at(constant->expr()->location(), "expression is not constant");
1544 constant->set_error();
1546 else if (!Type::are_assignable(constant->type(), constant->expr()->type(),
1547 NULL))
1549 error_at(constant->location(),
1550 "initialization expression has wrong type");
1551 constant->set_error();
1553 return TRAVERSE_CONTINUE;
1556 // There are no types to check in a function, but this is where we
1557 // issue warnings about labels which are defined but not referenced.
1560 Check_types_traverse::function(Named_object* no)
1562 no->func_value()->check_labels();
1563 return TRAVERSE_CONTINUE;
1566 // Check that types are valid in a statement.
1569 Check_types_traverse::statement(Block*, size_t*, Statement* s)
1571 s->check_types(this->gogo_);
1572 return TRAVERSE_CONTINUE;
1575 // Check that types are valid in an expression.
1578 Check_types_traverse::expression(Expression** expr)
1580 (*expr)->check_types(this->gogo_);
1581 return TRAVERSE_CONTINUE;
1584 // Check that types are valid.
1586 void
1587 Gogo::check_types()
1589 Check_types_traverse traverse(this);
1590 this->traverse(&traverse);
1593 // Check the types in a single block.
1595 void
1596 Gogo::check_types_in_block(Block* block)
1598 Check_types_traverse traverse(this);
1599 block->traverse(&traverse);
1602 // A traversal class used to find a single shortcut operator within an
1603 // expression.
1605 class Find_shortcut : public Traverse
1607 public:
1608 Find_shortcut()
1609 : Traverse(traverse_blocks
1610 | traverse_statements
1611 | traverse_expressions),
1612 found_(NULL)
1615 // A pointer to the expression which was found, or NULL if none was
1616 // found.
1617 Expression**
1618 found() const
1619 { return this->found_; }
1621 protected:
1623 block(Block*)
1624 { return TRAVERSE_SKIP_COMPONENTS; }
1627 statement(Block*, size_t*, Statement*)
1628 { return TRAVERSE_SKIP_COMPONENTS; }
1631 expression(Expression**);
1633 private:
1634 Expression** found_;
1637 // Find a shortcut expression.
1640 Find_shortcut::expression(Expression** pexpr)
1642 Expression* expr = *pexpr;
1643 Binary_expression* be = expr->binary_expression();
1644 if (be == NULL)
1645 return TRAVERSE_CONTINUE;
1646 Operator op = be->op();
1647 if (op != OPERATOR_OROR && op != OPERATOR_ANDAND)
1648 return TRAVERSE_CONTINUE;
1649 go_assert(this->found_ == NULL);
1650 this->found_ = pexpr;
1651 return TRAVERSE_EXIT;
1654 // A traversal class used to turn shortcut operators into explicit if
1655 // statements.
1657 class Shortcuts : public Traverse
1659 public:
1660 Shortcuts(Gogo* gogo)
1661 : Traverse(traverse_variables
1662 | traverse_statements),
1663 gogo_(gogo)
1666 protected:
1668 variable(Named_object*);
1671 statement(Block*, size_t*, Statement*);
1673 private:
1674 // Convert a shortcut operator.
1675 Statement*
1676 convert_shortcut(Block* enclosing, Expression** pshortcut);
1678 // The IR.
1679 Gogo* gogo_;
1682 // Remove shortcut operators in a single statement.
1685 Shortcuts::statement(Block* block, size_t* pindex, Statement* s)
1687 // FIXME: This approach doesn't work for switch statements, because
1688 // we add the new statements before the whole switch when we need to
1689 // instead add them just before the switch expression. The right
1690 // fix is probably to lower switch statements with nonconstant cases
1691 // to a series of conditionals.
1692 if (s->switch_statement() != NULL)
1693 return TRAVERSE_CONTINUE;
1695 while (true)
1697 Find_shortcut find_shortcut;
1699 // If S is a variable declaration, then ordinary traversal won't
1700 // do anything. We want to explicitly traverse the
1701 // initialization expression if there is one.
1702 Variable_declaration_statement* vds = s->variable_declaration_statement();
1703 Expression* init = NULL;
1704 if (vds == NULL)
1705 s->traverse_contents(&find_shortcut);
1706 else
1708 init = vds->var()->var_value()->init();
1709 if (init == NULL)
1710 return TRAVERSE_CONTINUE;
1711 init->traverse(&init, &find_shortcut);
1713 Expression** pshortcut = find_shortcut.found();
1714 if (pshortcut == NULL)
1715 return TRAVERSE_CONTINUE;
1717 Statement* snew = this->convert_shortcut(block, pshortcut);
1718 block->insert_statement_before(*pindex, snew);
1719 ++*pindex;
1721 if (pshortcut == &init)
1722 vds->var()->var_value()->set_init(init);
1726 // Remove shortcut operators in the initializer of a global variable.
1729 Shortcuts::variable(Named_object* no)
1731 if (no->is_result_variable())
1732 return TRAVERSE_CONTINUE;
1733 Variable* var = no->var_value();
1734 Expression* init = var->init();
1735 if (!var->is_global() || init == NULL)
1736 return TRAVERSE_CONTINUE;
1738 while (true)
1740 Find_shortcut find_shortcut;
1741 init->traverse(&init, &find_shortcut);
1742 Expression** pshortcut = find_shortcut.found();
1743 if (pshortcut == NULL)
1744 return TRAVERSE_CONTINUE;
1746 Statement* snew = this->convert_shortcut(NULL, pshortcut);
1747 var->add_preinit_statement(this->gogo_, snew);
1748 if (pshortcut == &init)
1749 var->set_init(init);
1753 // Given an expression which uses a shortcut operator, return a
1754 // statement which implements it, and update *PSHORTCUT accordingly.
1756 Statement*
1757 Shortcuts::convert_shortcut(Block* enclosing, Expression** pshortcut)
1759 Binary_expression* shortcut = (*pshortcut)->binary_expression();
1760 Expression* left = shortcut->left();
1761 Expression* right = shortcut->right();
1762 source_location loc = shortcut->location();
1764 Block* retblock = new Block(enclosing, loc);
1765 retblock->set_end_location(loc);
1767 Temporary_statement* ts = Statement::make_temporary(Type::lookup_bool_type(),
1768 left, loc);
1769 retblock->add_statement(ts);
1771 Block* block = new Block(retblock, loc);
1772 block->set_end_location(loc);
1773 Expression* tmpref = Expression::make_temporary_reference(ts, loc);
1774 Statement* assign = Statement::make_assignment(tmpref, right, loc);
1775 block->add_statement(assign);
1777 Expression* cond = Expression::make_temporary_reference(ts, loc);
1778 if (shortcut->binary_expression()->op() == OPERATOR_OROR)
1779 cond = Expression::make_unary(OPERATOR_NOT, cond, loc);
1781 Statement* if_statement = Statement::make_if_statement(cond, block, NULL,
1782 loc);
1783 retblock->add_statement(if_statement);
1785 *pshortcut = Expression::make_temporary_reference(ts, loc);
1787 delete shortcut;
1789 // Now convert any shortcut operators in LEFT and RIGHT.
1790 Shortcuts shortcuts(this->gogo_);
1791 retblock->traverse(&shortcuts);
1793 return Statement::make_block_statement(retblock, loc);
1796 // Turn shortcut operators into explicit if statements. Doing this
1797 // considerably simplifies the order of evaluation rules.
1799 void
1800 Gogo::remove_shortcuts()
1802 Shortcuts shortcuts(this);
1803 this->traverse(&shortcuts);
1806 // A traversal class which finds all the expressions which must be
1807 // evaluated in order within a statement or larger expression. This
1808 // is used to implement the rules about order of evaluation.
1810 class Find_eval_ordering : public Traverse
1812 private:
1813 typedef std::vector<Expression**> Expression_pointers;
1815 public:
1816 Find_eval_ordering()
1817 : Traverse(traverse_blocks
1818 | traverse_statements
1819 | traverse_expressions),
1820 exprs_()
1823 size_t
1824 size() const
1825 { return this->exprs_.size(); }
1827 typedef Expression_pointers::const_iterator const_iterator;
1829 const_iterator
1830 begin() const
1831 { return this->exprs_.begin(); }
1833 const_iterator
1834 end() const
1835 { return this->exprs_.end(); }
1837 protected:
1839 block(Block*)
1840 { return TRAVERSE_SKIP_COMPONENTS; }
1843 statement(Block*, size_t*, Statement*)
1844 { return TRAVERSE_SKIP_COMPONENTS; }
1847 expression(Expression**);
1849 private:
1850 // A list of pointers to expressions with side-effects.
1851 Expression_pointers exprs_;
1854 // If an expression must be evaluated in order, put it on the list.
1857 Find_eval_ordering::expression(Expression** expression_pointer)
1859 // We have to look at subexpressions before this one.
1860 if ((*expression_pointer)->traverse_subexpressions(this) == TRAVERSE_EXIT)
1861 return TRAVERSE_EXIT;
1862 if ((*expression_pointer)->must_eval_in_order())
1863 this->exprs_.push_back(expression_pointer);
1864 return TRAVERSE_SKIP_COMPONENTS;
1867 // A traversal class for ordering evaluations.
1869 class Order_eval : public Traverse
1871 public:
1872 Order_eval(Gogo* gogo)
1873 : Traverse(traverse_variables
1874 | traverse_statements),
1875 gogo_(gogo)
1879 variable(Named_object*);
1882 statement(Block*, size_t*, Statement*);
1884 private:
1885 // The IR.
1886 Gogo* gogo_;
1889 // Implement the order of evaluation rules for a statement.
1892 Order_eval::statement(Block* block, size_t* pindex, Statement* s)
1894 // FIXME: This approach doesn't work for switch statements, because
1895 // we add the new statements before the whole switch when we need to
1896 // instead add them just before the switch expression. The right
1897 // fix is probably to lower switch statements with nonconstant cases
1898 // to a series of conditionals.
1899 if (s->switch_statement() != NULL)
1900 return TRAVERSE_CONTINUE;
1902 Find_eval_ordering find_eval_ordering;
1904 // If S is a variable declaration, then ordinary traversal won't do
1905 // anything. We want to explicitly traverse the initialization
1906 // expression if there is one.
1907 Variable_declaration_statement* vds = s->variable_declaration_statement();
1908 Expression* init = NULL;
1909 Expression* orig_init = NULL;
1910 if (vds == NULL)
1911 s->traverse_contents(&find_eval_ordering);
1912 else
1914 init = vds->var()->var_value()->init();
1915 if (init == NULL)
1916 return TRAVERSE_CONTINUE;
1917 orig_init = init;
1919 // It might seem that this could be
1920 // init->traverse_subexpressions. Unfortunately that can fail
1921 // in a case like
1922 // var err os.Error
1923 // newvar, err := call(arg())
1924 // Here newvar will have an init of call result 0 of
1925 // call(arg()). If we only traverse subexpressions, we will
1926 // only find arg(), and we won't bother to move anything out.
1927 // Then we get to the assignment to err, we will traverse the
1928 // whole statement, and this time we will find both call() and
1929 // arg(), and so we will move them out. This will cause them to
1930 // be put into temporary variables before the assignment to err
1931 // but after the declaration of newvar. To avoid that problem,
1932 // we traverse the entire expression here.
1933 Expression::traverse(&init, &find_eval_ordering);
1936 if (find_eval_ordering.size() <= 1)
1938 // If there is only one expression with a side-effect, we can
1939 // leave it in place.
1940 return TRAVERSE_CONTINUE;
1943 bool is_thunk = s->thunk_statement() != NULL;
1944 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1945 p != find_eval_ordering.end();
1946 ++p)
1948 Expression** pexpr = *p;
1950 // The last expression in a thunk will be the call passed to go
1951 // or defer, which we must not evaluate early.
1952 if (is_thunk && p + 1 == find_eval_ordering.end())
1953 break;
1955 source_location loc = (*pexpr)->location();
1956 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1957 block->insert_statement_before(*pindex, ts);
1958 ++*pindex;
1960 *pexpr = Expression::make_temporary_reference(ts, loc);
1963 if (init != orig_init)
1964 vds->var()->var_value()->set_init(init);
1966 return TRAVERSE_CONTINUE;
1969 // Implement the order of evaluation rules for the initializer of a
1970 // global variable.
1973 Order_eval::variable(Named_object* no)
1975 if (no->is_result_variable())
1976 return TRAVERSE_CONTINUE;
1977 Variable* var = no->var_value();
1978 Expression* init = var->init();
1979 if (!var->is_global() || init == NULL)
1980 return TRAVERSE_CONTINUE;
1982 Find_eval_ordering find_eval_ordering;
1983 init->traverse_subexpressions(&find_eval_ordering);
1985 if (find_eval_ordering.size() <= 1)
1987 // If there is only one expression with a side-effect, we can
1988 // leave it in place.
1989 return TRAVERSE_SKIP_COMPONENTS;
1992 for (Find_eval_ordering::const_iterator p = find_eval_ordering.begin();
1993 p != find_eval_ordering.end();
1994 ++p)
1996 Expression** pexpr = *p;
1997 source_location loc = (*pexpr)->location();
1998 Temporary_statement* ts = Statement::make_temporary(NULL, *pexpr, loc);
1999 var->add_preinit_statement(this->gogo_, ts);
2000 *pexpr = Expression::make_temporary_reference(ts, loc);
2003 return TRAVERSE_SKIP_COMPONENTS;
2006 // Use temporary variables to implement the order of evaluation rules.
2008 void
2009 Gogo::order_evaluations()
2011 Order_eval order_eval(this);
2012 this->traverse(&order_eval);
2015 // Traversal to convert calls to the predeclared recover function to
2016 // pass in an argument indicating whether it can recover from a panic
2017 // or not.
2019 class Convert_recover : public Traverse
2021 public:
2022 Convert_recover(Named_object* arg)
2023 : Traverse(traverse_expressions),
2024 arg_(arg)
2027 protected:
2029 expression(Expression**);
2031 private:
2032 // The argument to pass to the function.
2033 Named_object* arg_;
2036 // Convert calls to recover.
2039 Convert_recover::expression(Expression** pp)
2041 Call_expression* ce = (*pp)->call_expression();
2042 if (ce != NULL && ce->is_recover_call())
2043 ce->set_recover_arg(Expression::make_var_reference(this->arg_,
2044 ce->location()));
2045 return TRAVERSE_CONTINUE;
2048 // Traversal for build_recover_thunks.
2050 class Build_recover_thunks : public Traverse
2052 public:
2053 Build_recover_thunks(Gogo* gogo)
2054 : Traverse(traverse_functions),
2055 gogo_(gogo)
2059 function(Named_object*);
2061 private:
2062 Expression*
2063 can_recover_arg(source_location);
2065 // General IR.
2066 Gogo* gogo_;
2069 // If this function calls recover, turn it into a thunk.
2072 Build_recover_thunks::function(Named_object* orig_no)
2074 Function* orig_func = orig_no->func_value();
2075 if (!orig_func->calls_recover()
2076 || orig_func->is_recover_thunk()
2077 || orig_func->has_recover_thunk())
2078 return TRAVERSE_CONTINUE;
2080 Gogo* gogo = this->gogo_;
2081 source_location location = orig_func->location();
2083 static int count;
2084 char buf[50];
2086 Function_type* orig_fntype = orig_func->type();
2087 Typed_identifier_list* new_params = new Typed_identifier_list();
2088 std::string receiver_name;
2089 if (orig_fntype->is_method())
2091 const Typed_identifier* receiver = orig_fntype->receiver();
2092 snprintf(buf, sizeof buf, "rt.%u", count);
2093 ++count;
2094 receiver_name = buf;
2095 new_params->push_back(Typed_identifier(receiver_name, receiver->type(),
2096 receiver->location()));
2098 const Typed_identifier_list* orig_params = orig_fntype->parameters();
2099 if (orig_params != NULL && !orig_params->empty())
2101 for (Typed_identifier_list::const_iterator p = orig_params->begin();
2102 p != orig_params->end();
2103 ++p)
2105 snprintf(buf, sizeof buf, "pt.%u", count);
2106 ++count;
2107 new_params->push_back(Typed_identifier(buf, p->type(),
2108 p->location()));
2111 snprintf(buf, sizeof buf, "pr.%u", count);
2112 ++count;
2113 std::string can_recover_name = buf;
2114 new_params->push_back(Typed_identifier(can_recover_name,
2115 Type::lookup_bool_type(),
2116 orig_fntype->location()));
2118 const Typed_identifier_list* orig_results = orig_fntype->results();
2119 Typed_identifier_list* new_results;
2120 if (orig_results == NULL || orig_results->empty())
2121 new_results = NULL;
2122 else
2124 new_results = new Typed_identifier_list();
2125 for (Typed_identifier_list::const_iterator p = orig_results->begin();
2126 p != orig_results->end();
2127 ++p)
2128 new_results->push_back(Typed_identifier("", p->type(), p->location()));
2131 Function_type *new_fntype = Type::make_function_type(NULL, new_params,
2132 new_results,
2133 orig_fntype->location());
2134 if (orig_fntype->is_varargs())
2135 new_fntype->set_is_varargs();
2137 std::string name = orig_no->name() + "$recover";
2138 Named_object *new_no = gogo->start_function(name, new_fntype, false,
2139 location);
2140 Function *new_func = new_no->func_value();
2141 if (orig_func->enclosing() != NULL)
2142 new_func->set_enclosing(orig_func->enclosing());
2144 // We build the code for the original function attached to the new
2145 // function, and then swap the original and new function bodies.
2146 // This means that existing references to the original function will
2147 // then refer to the new function. That makes this code a little
2148 // confusing, in that the reference to NEW_NO really refers to the
2149 // other function, not the one we are building.
2151 Expression* closure = NULL;
2152 if (orig_func->needs_closure())
2154 Named_object* orig_closure_no = orig_func->closure_var();
2155 Variable* orig_closure_var = orig_closure_no->var_value();
2156 Variable* new_var = new Variable(orig_closure_var->type(), NULL, false,
2157 true, false, location);
2158 snprintf(buf, sizeof buf, "closure.%u", count);
2159 ++count;
2160 Named_object* new_closure_no = Named_object::make_variable(buf, NULL,
2161 new_var);
2162 new_func->set_closure_var(new_closure_no);
2163 closure = Expression::make_var_reference(new_closure_no, location);
2166 Expression* fn = Expression::make_func_reference(new_no, closure, location);
2168 Expression_list* args = new Expression_list();
2169 if (new_params != NULL)
2171 // Note that we skip the last parameter, which is the boolean
2172 // indicating whether recover can succed.
2173 for (Typed_identifier_list::const_iterator p = new_params->begin();
2174 p + 1 != new_params->end();
2175 ++p)
2177 Named_object* p_no = gogo->lookup(p->name(), NULL);
2178 go_assert(p_no != NULL
2179 && p_no->is_variable()
2180 && p_no->var_value()->is_parameter());
2181 args->push_back(Expression::make_var_reference(p_no, location));
2184 args->push_back(this->can_recover_arg(location));
2186 Call_expression* call = Expression::make_call(fn, args, false, location);
2188 Statement* s;
2189 if (orig_fntype->results() == NULL || orig_fntype->results()->empty())
2190 s = Statement::make_statement(call);
2191 else
2193 Expression_list* vals = new Expression_list();
2194 size_t rc = orig_fntype->results()->size();
2195 if (rc == 1)
2196 vals->push_back(call);
2197 else
2199 for (size_t i = 0; i < rc; ++i)
2200 vals->push_back(Expression::make_call_result(call, i));
2202 s = Statement::make_return_statement(vals, location);
2204 s->determine_types();
2205 gogo->add_statement(s);
2207 gogo->finish_function(location);
2209 // Swap the function bodies and types.
2210 new_func->swap_for_recover(orig_func);
2211 orig_func->set_is_recover_thunk();
2212 new_func->set_calls_recover();
2213 new_func->set_has_recover_thunk();
2215 Bindings* orig_bindings = orig_func->block()->bindings();
2216 Bindings* new_bindings = new_func->block()->bindings();
2217 if (orig_fntype->is_method())
2219 // We changed the receiver to be a regular parameter. We have
2220 // to update the binding accordingly in both functions.
2221 Named_object* orig_rec_no = orig_bindings->lookup_local(receiver_name);
2222 go_assert(orig_rec_no != NULL
2223 && orig_rec_no->is_variable()
2224 && !orig_rec_no->var_value()->is_receiver());
2225 orig_rec_no->var_value()->set_is_receiver();
2227 const std::string& new_receiver_name(orig_fntype->receiver()->name());
2228 Named_object* new_rec_no = new_bindings->lookup_local(new_receiver_name);
2229 if (new_rec_no == NULL)
2230 go_assert(saw_errors());
2231 else
2233 go_assert(new_rec_no->is_variable()
2234 && new_rec_no->var_value()->is_receiver());
2235 new_rec_no->var_value()->set_is_not_receiver();
2239 // Because we flipped blocks but not types, the can_recover
2240 // parameter appears in the (now) old bindings as a parameter.
2241 // Change it to a local variable, whereupon it will be discarded.
2242 Named_object* can_recover_no = orig_bindings->lookup_local(can_recover_name);
2243 go_assert(can_recover_no != NULL
2244 && can_recover_no->is_variable()
2245 && can_recover_no->var_value()->is_parameter());
2246 orig_bindings->remove_binding(can_recover_no);
2248 // Add the can_recover argument to the (now) new bindings, and
2249 // attach it to any recover statements.
2250 Variable* can_recover_var = new Variable(Type::lookup_bool_type(), NULL,
2251 false, true, false, location);
2252 can_recover_no = new_bindings->add_variable(can_recover_name, NULL,
2253 can_recover_var);
2254 Convert_recover convert_recover(can_recover_no);
2255 new_func->traverse(&convert_recover);
2257 // Update the function pointers in any named results.
2258 new_func->update_result_variables();
2259 orig_func->update_result_variables();
2261 return TRAVERSE_CONTINUE;
2264 // Return the expression to pass for the .can_recover parameter to the
2265 // new function. This indicates whether a call to recover may return
2266 // non-nil. The expression is
2267 // __go_can_recover(__builtin_return_address()).
2269 Expression*
2270 Build_recover_thunks::can_recover_arg(source_location location)
2272 static Named_object* builtin_return_address;
2273 if (builtin_return_address == NULL)
2275 const source_location bloc = BUILTINS_LOCATION;
2277 Typed_identifier_list* param_types = new Typed_identifier_list();
2278 Type* uint_type = Type::lookup_integer_type("uint");
2279 param_types->push_back(Typed_identifier("l", uint_type, bloc));
2281 Typed_identifier_list* return_types = new Typed_identifier_list();
2282 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2283 return_types->push_back(Typed_identifier("", voidptr_type, bloc));
2285 Function_type* fntype = Type::make_function_type(NULL, param_types,
2286 return_types, bloc);
2287 builtin_return_address =
2288 Named_object::make_function_declaration("__builtin_return_address",
2289 NULL, fntype, bloc);
2290 const char* n = "__builtin_return_address";
2291 builtin_return_address->func_declaration_value()->set_asm_name(n);
2294 static Named_object* can_recover;
2295 if (can_recover == NULL)
2297 const source_location bloc = BUILTINS_LOCATION;
2298 Typed_identifier_list* param_types = new Typed_identifier_list();
2299 Type* voidptr_type = Type::make_pointer_type(Type::make_void_type());
2300 param_types->push_back(Typed_identifier("a", voidptr_type, bloc));
2301 Type* boolean_type = Type::lookup_bool_type();
2302 Typed_identifier_list* results = new Typed_identifier_list();
2303 results->push_back(Typed_identifier("", boolean_type, bloc));
2304 Function_type* fntype = Type::make_function_type(NULL, param_types,
2305 results, bloc);
2306 can_recover = Named_object::make_function_declaration("__go_can_recover",
2307 NULL, fntype,
2308 bloc);
2309 can_recover->func_declaration_value()->set_asm_name("__go_can_recover");
2312 Expression* fn = Expression::make_func_reference(builtin_return_address,
2313 NULL, location);
2315 mpz_t zval;
2316 mpz_init_set_ui(zval, 0UL);
2317 Expression* zexpr = Expression::make_integer(&zval, NULL, location);
2318 mpz_clear(zval);
2319 Expression_list *args = new Expression_list();
2320 args->push_back(zexpr);
2322 Expression* call = Expression::make_call(fn, args, false, location);
2324 args = new Expression_list();
2325 args->push_back(call);
2327 fn = Expression::make_func_reference(can_recover, NULL, location);
2328 return Expression::make_call(fn, args, false, location);
2331 // Build thunks for functions which call recover. We build a new
2332 // function with an extra parameter, which is whether a call to
2333 // recover can succeed. We then move the body of this function to
2334 // that one. We then turn this function into a thunk which calls the
2335 // new one, passing the value of
2336 // __go_can_recover(__builtin_return_address()). The function will be
2337 // marked as not splitting the stack. This will cooperate with the
2338 // implementation of defer to make recover do the right thing.
2340 void
2341 Gogo::build_recover_thunks()
2343 Build_recover_thunks build_recover_thunks(this);
2344 this->traverse(&build_recover_thunks);
2347 // Look for named types to see whether we need to create an interface
2348 // method table.
2350 class Build_method_tables : public Traverse
2352 public:
2353 Build_method_tables(Gogo* gogo,
2354 const std::vector<Interface_type*>& interfaces)
2355 : Traverse(traverse_types),
2356 gogo_(gogo), interfaces_(interfaces)
2360 type(Type*);
2362 private:
2363 // The IR.
2364 Gogo* gogo_;
2365 // A list of locally defined interfaces which have hidden methods.
2366 const std::vector<Interface_type*>& interfaces_;
2369 // Build all required interface method tables for types. We need to
2370 // ensure that we have an interface method table for every interface
2371 // which has a hidden method, for every named type which implements
2372 // that interface. Normally we can just build interface method tables
2373 // as we need them. However, in some cases we can require an
2374 // interface method table for an interface defined in a different
2375 // package for a type defined in that package. If that interface and
2376 // type both use a hidden method, that is OK. However, we will not be
2377 // able to build that interface method table when we need it, because
2378 // the type's hidden method will be static. So we have to build it
2379 // here, and just refer it from other packages as needed.
2381 void
2382 Gogo::build_interface_method_tables()
2384 std::vector<Interface_type*> hidden_interfaces;
2385 hidden_interfaces.reserve(this->interface_types_.size());
2386 for (std::vector<Interface_type*>::const_iterator pi =
2387 this->interface_types_.begin();
2388 pi != this->interface_types_.end();
2389 ++pi)
2391 const Typed_identifier_list* methods = (*pi)->methods();
2392 if (methods == NULL)
2393 continue;
2394 for (Typed_identifier_list::const_iterator pm = methods->begin();
2395 pm != methods->end();
2396 ++pm)
2398 if (Gogo::is_hidden_name(pm->name()))
2400 hidden_interfaces.push_back(*pi);
2401 break;
2406 if (!hidden_interfaces.empty())
2408 // Now traverse the tree looking for all named types.
2409 Build_method_tables bmt(this, hidden_interfaces);
2410 this->traverse(&bmt);
2413 // We no longer need the list of interfaces.
2415 this->interface_types_.clear();
2418 // This is called for each type. For a named type, for each of the
2419 // interfaces with hidden methods that it implements, create the
2420 // method table.
2423 Build_method_tables::type(Type* type)
2425 Named_type* nt = type->named_type();
2426 if (nt != NULL)
2428 for (std::vector<Interface_type*>::const_iterator p =
2429 this->interfaces_.begin();
2430 p != this->interfaces_.end();
2431 ++p)
2433 // We ask whether a pointer to the named type implements the
2434 // interface, because a pointer can implement more methods
2435 // than a value.
2436 if ((*p)->implements_interface(Type::make_pointer_type(nt), NULL))
2438 nt->interface_method_table(this->gogo_, *p, false);
2439 nt->interface_method_table(this->gogo_, *p, true);
2443 return TRAVERSE_CONTINUE;
2446 // Traversal class used to check for return statements.
2448 class Check_return_statements_traverse : public Traverse
2450 public:
2451 Check_return_statements_traverse()
2452 : Traverse(traverse_functions)
2456 function(Named_object*);
2459 // Check that a function has a return statement if it needs one.
2462 Check_return_statements_traverse::function(Named_object* no)
2464 Function* func = no->func_value();
2465 const Function_type* fntype = func->type();
2466 const Typed_identifier_list* results = fntype->results();
2468 // We only need a return statement if there is a return value.
2469 if (results == NULL || results->empty())
2470 return TRAVERSE_CONTINUE;
2472 if (func->block()->may_fall_through())
2473 error_at(func->location(), "control reaches end of non-void function");
2475 return TRAVERSE_CONTINUE;
2478 // Check return statements.
2480 void
2481 Gogo::check_return_statements()
2483 Check_return_statements_traverse traverse;
2484 this->traverse(&traverse);
2487 // Get the unique prefix to use before all exported symbols. This
2488 // must be unique across the entire link.
2490 const std::string&
2491 Gogo::unique_prefix() const
2493 go_assert(!this->unique_prefix_.empty());
2494 return this->unique_prefix_;
2497 // Set the unique prefix to use before all exported symbols. This
2498 // comes from the command line option -fgo-prefix=XXX.
2500 void
2501 Gogo::set_unique_prefix(const std::string& arg)
2503 go_assert(this->unique_prefix_.empty());
2504 this->unique_prefix_ = arg;
2505 this->unique_prefix_specified_ = true;
2508 // Work out the package priority. It is one more than the maximum
2509 // priority of an imported package.
2512 Gogo::package_priority() const
2514 int priority = 0;
2515 for (Packages::const_iterator p = this->packages_.begin();
2516 p != this->packages_.end();
2517 ++p)
2518 if (p->second->priority() > priority)
2519 priority = p->second->priority();
2520 return priority + 1;
2523 // Export identifiers as requested.
2525 void
2526 Gogo::do_exports()
2528 // For now we always stream to a section. Later we may want to
2529 // support streaming to a separate file.
2530 Stream_to_section stream;
2532 Export exp(&stream);
2533 exp.register_builtin_types(this);
2534 exp.export_globals(this->package_name(),
2535 this->unique_prefix(),
2536 this->package_priority(),
2537 (this->need_init_fn_ && !this->is_main_package()
2538 ? this->get_init_fn_name()
2539 : ""),
2540 this->imported_init_fns_,
2541 this->package_->bindings());
2544 // Find the blocks in order to convert named types defined in blocks.
2546 class Convert_named_types : public Traverse
2548 public:
2549 Convert_named_types(Gogo* gogo)
2550 : Traverse(traverse_blocks),
2551 gogo_(gogo)
2554 protected:
2556 block(Block* block);
2558 private:
2559 Gogo* gogo_;
2563 Convert_named_types::block(Block* block)
2565 this->gogo_->convert_named_types_in_bindings(block->bindings());
2566 return TRAVERSE_CONTINUE;
2569 // Convert all named types to the backend representation. Since named
2570 // types can refer to other types, this needs to be done in the right
2571 // sequence, which is handled by Named_type::convert. Here we arrange
2572 // to call that for each named type.
2574 void
2575 Gogo::convert_named_types()
2577 this->convert_named_types_in_bindings(this->globals_);
2578 for (Packages::iterator p = this->packages_.begin();
2579 p != this->packages_.end();
2580 ++p)
2582 Package* package = p->second;
2583 this->convert_named_types_in_bindings(package->bindings());
2586 Convert_named_types cnt(this);
2587 this->traverse(&cnt);
2589 // Make all the builtin named types used for type descriptors, and
2590 // then convert them. They will only be written out if they are
2591 // needed.
2592 Type::make_type_descriptor_type();
2593 Type::make_type_descriptor_ptr_type();
2594 Function_type::make_function_type_descriptor_type();
2595 Pointer_type::make_pointer_type_descriptor_type();
2596 Struct_type::make_struct_type_descriptor_type();
2597 Array_type::make_array_type_descriptor_type();
2598 Array_type::make_slice_type_descriptor_type();
2599 Map_type::make_map_type_descriptor_type();
2600 Channel_type::make_chan_type_descriptor_type();
2601 Interface_type::make_interface_type_descriptor_type();
2602 Type::convert_builtin_named_types(this);
2604 Runtime::convert_types(this);
2606 Function_type::convert_types(this);
2608 this->named_types_are_converted_ = true;
2611 // Convert all names types in a set of bindings.
2613 void
2614 Gogo::convert_named_types_in_bindings(Bindings* bindings)
2616 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
2617 p != bindings->end_definitions();
2618 ++p)
2620 if ((*p)->is_type())
2621 (*p)->type_value()->convert(this);
2625 // Class Function.
2627 Function::Function(Function_type* type, Function* enclosing, Block* block,
2628 source_location location)
2629 : type_(type), enclosing_(enclosing), results_(NULL),
2630 closure_var_(NULL), block_(block), location_(location), fndecl_(NULL),
2631 defer_stack_(NULL), results_are_named_(false), calls_recover_(false),
2632 is_recover_thunk_(false), has_recover_thunk_(false)
2636 // Create the named result variables.
2638 void
2639 Function::create_result_variables(Gogo* gogo)
2641 const Typed_identifier_list* results = this->type_->results();
2642 if (results == NULL || results->empty())
2643 return;
2645 if (!results->front().name().empty())
2646 this->results_are_named_ = true;
2648 this->results_ = new Results();
2649 this->results_->reserve(results->size());
2651 Block* block = this->block_;
2652 int index = 0;
2653 for (Typed_identifier_list::const_iterator p = results->begin();
2654 p != results->end();
2655 ++p, ++index)
2657 std::string name = p->name();
2658 if (name.empty() || Gogo::is_sink_name(name))
2660 static int result_counter;
2661 char buf[100];
2662 snprintf(buf, sizeof buf, "$ret%d", result_counter);
2663 ++result_counter;
2664 name = gogo->pack_hidden_name(buf, false);
2666 Result_variable* result = new Result_variable(p->type(), this, index,
2667 p->location());
2668 Named_object* no = block->bindings()->add_result_variable(name, result);
2669 if (no->is_result_variable())
2670 this->results_->push_back(no);
2671 else
2673 static int dummy_result_count;
2674 char buf[100];
2675 snprintf(buf, sizeof buf, "$dret%d", dummy_result_count);
2676 ++dummy_result_count;
2677 name = gogo->pack_hidden_name(buf, false);
2678 no = block->bindings()->add_result_variable(name, result);
2679 go_assert(no->is_result_variable());
2680 this->results_->push_back(no);
2685 // Update the named result variables when cloning a function which
2686 // calls recover.
2688 void
2689 Function::update_result_variables()
2691 if (this->results_ == NULL)
2692 return;
2694 for (Results::iterator p = this->results_->begin();
2695 p != this->results_->end();
2696 ++p)
2697 (*p)->result_var_value()->set_function(this);
2700 // Return the closure variable, creating it if necessary.
2702 Named_object*
2703 Function::closure_var()
2705 if (this->closure_var_ == NULL)
2707 // We don't know the type of the variable yet. We add fields as
2708 // we find them.
2709 source_location loc = this->type_->location();
2710 Struct_field_list* sfl = new Struct_field_list;
2711 Type* struct_type = Type::make_struct_type(sfl, loc);
2712 Variable* var = new Variable(Type::make_pointer_type(struct_type),
2713 NULL, false, true, false, loc);
2714 this->closure_var_ = Named_object::make_variable("closure", NULL, var);
2715 // Note that the new variable is not in any binding contour.
2717 return this->closure_var_;
2720 // Set the type of the closure variable.
2722 void
2723 Function::set_closure_type()
2725 if (this->closure_var_ == NULL)
2726 return;
2727 Named_object* closure = this->closure_var_;
2728 Struct_type* st = closure->var_value()->type()->deref()->struct_type();
2729 unsigned int index = 0;
2730 for (Closure_fields::const_iterator p = this->closure_fields_.begin();
2731 p != this->closure_fields_.end();
2732 ++p, ++index)
2734 Named_object* no = p->first;
2735 char buf[20];
2736 snprintf(buf, sizeof buf, "%u", index);
2737 std::string n = no->name() + buf;
2738 Type* var_type;
2739 if (no->is_variable())
2740 var_type = no->var_value()->type();
2741 else
2742 var_type = no->result_var_value()->type();
2743 Type* field_type = Type::make_pointer_type(var_type);
2744 st->push_field(Struct_field(Typed_identifier(n, field_type, p->second)));
2748 // Return whether this function is a method.
2750 bool
2751 Function::is_method() const
2753 return this->type_->is_method();
2756 // Add a label definition.
2758 Label*
2759 Function::add_label_definition(const std::string& label_name,
2760 source_location location)
2762 Label* lnull = NULL;
2763 std::pair<Labels::iterator, bool> ins =
2764 this->labels_.insert(std::make_pair(label_name, lnull));
2765 if (ins.second)
2767 // This is a new label.
2768 Label* label = new Label(label_name);
2769 label->define(location);
2770 ins.first->second = label;
2771 return label;
2773 else
2775 // The label was already in the hash table.
2776 Label* label = ins.first->second;
2777 if (!label->is_defined())
2779 label->define(location);
2780 return label;
2782 else
2784 error_at(location, "label %qs already defined",
2785 Gogo::message_name(label_name).c_str());
2786 inform(label->location(), "previous definition of %qs was here",
2787 Gogo::message_name(label_name).c_str());
2788 return new Label(label_name);
2793 // Add a reference to a label.
2795 Label*
2796 Function::add_label_reference(const std::string& label_name)
2798 Label* lnull = NULL;
2799 std::pair<Labels::iterator, bool> ins =
2800 this->labels_.insert(std::make_pair(label_name, lnull));
2801 if (!ins.second)
2803 // The label was already in the hash table.
2804 Label* label = ins.first->second;
2805 label->set_is_used();
2806 return label;
2808 else
2810 go_assert(ins.first->second == NULL);
2811 Label* label = new Label(label_name);
2812 ins.first->second = label;
2813 label->set_is_used();
2814 return label;
2818 // Warn about labels that are defined but not used.
2820 void
2821 Function::check_labels() const
2823 for (Labels::const_iterator p = this->labels_.begin();
2824 p != this->labels_.end();
2825 p++)
2827 Label* label = p->second;
2828 if (!label->is_used())
2829 error_at(label->location(), "label %qs defined and not used",
2830 Gogo::message_name(label->name()).c_str());
2834 // Swap one function with another. This is used when building the
2835 // thunk we use to call a function which calls recover. It may not
2836 // work for any other case.
2838 void
2839 Function::swap_for_recover(Function *x)
2841 go_assert(this->enclosing_ == x->enclosing_);
2842 std::swap(this->results_, x->results_);
2843 std::swap(this->closure_var_, x->closure_var_);
2844 std::swap(this->block_, x->block_);
2845 go_assert(this->location_ == x->location_);
2846 go_assert(this->fndecl_ == NULL && x->fndecl_ == NULL);
2847 go_assert(this->defer_stack_ == NULL && x->defer_stack_ == NULL);
2850 // Traverse the tree.
2853 Function::traverse(Traverse* traverse)
2855 unsigned int traverse_mask = traverse->traverse_mask();
2857 if ((traverse_mask
2858 & (Traverse::traverse_types | Traverse::traverse_expressions))
2859 != 0)
2861 if (Type::traverse(this->type_, traverse) == TRAVERSE_EXIT)
2862 return TRAVERSE_EXIT;
2865 // FIXME: We should check traverse_functions here if nested
2866 // functions are stored in block bindings.
2867 if (this->block_ != NULL
2868 && (traverse_mask
2869 & (Traverse::traverse_variables
2870 | Traverse::traverse_constants
2871 | Traverse::traverse_blocks
2872 | Traverse::traverse_statements
2873 | Traverse::traverse_expressions
2874 | Traverse::traverse_types)) != 0)
2876 if (this->block_->traverse(traverse) == TRAVERSE_EXIT)
2877 return TRAVERSE_EXIT;
2880 return TRAVERSE_CONTINUE;
2883 // Work out types for unspecified variables and constants.
2885 void
2886 Function::determine_types()
2888 if (this->block_ != NULL)
2889 this->block_->determine_types();
2892 // Get a pointer to the variable holding the defer stack for this
2893 // function, making it if necessary. At least at present, the value
2894 // of this variable is not used. However, a pointer to this variable
2895 // is used as a marker for the functions on the defer stack associated
2896 // with this function. Doing things this way permits inlining a
2897 // function which uses defer.
2899 Expression*
2900 Function::defer_stack(source_location location)
2902 Type* t = Type::make_pointer_type(Type::make_void_type());
2903 if (this->defer_stack_ == NULL)
2905 Expression* n = Expression::make_nil(location);
2906 this->defer_stack_ = Statement::make_temporary(t, n, location);
2907 this->defer_stack_->set_is_address_taken();
2909 Expression* ref = Expression::make_temporary_reference(this->defer_stack_,
2910 location);
2911 Expression* addr = Expression::make_unary(OPERATOR_AND, ref, location);
2912 return Expression::make_unsafe_cast(t, addr, location);
2915 // Export the function.
2917 void
2918 Function::export_func(Export* exp, const std::string& name) const
2920 Function::export_func_with_type(exp, name, this->type_);
2923 // Export a function with a type.
2925 void
2926 Function::export_func_with_type(Export* exp, const std::string& name,
2927 const Function_type* fntype)
2929 exp->write_c_string("func ");
2931 if (fntype->is_method())
2933 exp->write_c_string("(");
2934 exp->write_type(fntype->receiver()->type());
2935 exp->write_c_string(") ");
2938 exp->write_string(name);
2940 exp->write_c_string(" (");
2941 const Typed_identifier_list* parameters = fntype->parameters();
2942 if (parameters != NULL)
2944 bool is_varargs = fntype->is_varargs();
2945 bool first = true;
2946 for (Typed_identifier_list::const_iterator p = parameters->begin();
2947 p != parameters->end();
2948 ++p)
2950 if (first)
2951 first = false;
2952 else
2953 exp->write_c_string(", ");
2954 if (!is_varargs || p + 1 != parameters->end())
2955 exp->write_type(p->type());
2956 else
2958 exp->write_c_string("...");
2959 exp->write_type(p->type()->array_type()->element_type());
2963 exp->write_c_string(")");
2965 const Typed_identifier_list* results = fntype->results();
2966 if (results != NULL)
2968 if (results->size() == 1)
2970 exp->write_c_string(" ");
2971 exp->write_type(results->begin()->type());
2973 else
2975 exp->write_c_string(" (");
2976 bool first = true;
2977 for (Typed_identifier_list::const_iterator p = results->begin();
2978 p != results->end();
2979 ++p)
2981 if (first)
2982 first = false;
2983 else
2984 exp->write_c_string(", ");
2985 exp->write_type(p->type());
2987 exp->write_c_string(")");
2990 exp->write_c_string(";\n");
2993 // Import a function.
2995 void
2996 Function::import_func(Import* imp, std::string* pname,
2997 Typed_identifier** preceiver,
2998 Typed_identifier_list** pparameters,
2999 Typed_identifier_list** presults,
3000 bool* is_varargs)
3002 imp->require_c_string("func ");
3004 *preceiver = NULL;
3005 if (imp->peek_char() == '(')
3007 imp->require_c_string("(");
3008 Type* rtype = imp->read_type();
3009 *preceiver = new Typed_identifier(Import::import_marker, rtype,
3010 imp->location());
3011 imp->require_c_string(") ");
3014 *pname = imp->read_identifier();
3016 Typed_identifier_list* parameters;
3017 *is_varargs = false;
3018 imp->require_c_string(" (");
3019 if (imp->peek_char() == ')')
3020 parameters = NULL;
3021 else
3023 parameters = new Typed_identifier_list();
3024 while (true)
3026 if (imp->match_c_string("..."))
3028 imp->advance(3);
3029 *is_varargs = true;
3032 Type* ptype = imp->read_type();
3033 if (*is_varargs)
3034 ptype = Type::make_array_type(ptype, NULL);
3035 parameters->push_back(Typed_identifier(Import::import_marker,
3036 ptype, imp->location()));
3037 if (imp->peek_char() != ',')
3038 break;
3039 go_assert(!*is_varargs);
3040 imp->require_c_string(", ");
3043 imp->require_c_string(")");
3044 *pparameters = parameters;
3046 Typed_identifier_list* results;
3047 if (imp->peek_char() != ' ')
3048 results = NULL;
3049 else
3051 results = new Typed_identifier_list();
3052 imp->require_c_string(" ");
3053 if (imp->peek_char() != '(')
3055 Type* rtype = imp->read_type();
3056 results->push_back(Typed_identifier(Import::import_marker, rtype,
3057 imp->location()));
3059 else
3061 imp->require_c_string("(");
3062 while (true)
3064 Type* rtype = imp->read_type();
3065 results->push_back(Typed_identifier(Import::import_marker,
3066 rtype, imp->location()));
3067 if (imp->peek_char() != ',')
3068 break;
3069 imp->require_c_string(", ");
3071 imp->require_c_string(")");
3074 imp->require_c_string(";\n");
3075 *presults = results;
3078 // Class Block.
3080 Block::Block(Block* enclosing, source_location location)
3081 : enclosing_(enclosing), statements_(),
3082 bindings_(new Bindings(enclosing == NULL
3083 ? NULL
3084 : enclosing->bindings())),
3085 start_location_(location),
3086 end_location_(UNKNOWN_LOCATION)
3090 // Add a statement to a block.
3092 void
3093 Block::add_statement(Statement* statement)
3095 this->statements_.push_back(statement);
3098 // Add a statement to the front of a block. This is slow but is only
3099 // used for reference counts of parameters.
3101 void
3102 Block::add_statement_at_front(Statement* statement)
3104 this->statements_.insert(this->statements_.begin(), statement);
3107 // Replace a statement in a block.
3109 void
3110 Block::replace_statement(size_t index, Statement* s)
3112 go_assert(index < this->statements_.size());
3113 this->statements_[index] = s;
3116 // Add a statement before another statement.
3118 void
3119 Block::insert_statement_before(size_t index, Statement* s)
3121 go_assert(index < this->statements_.size());
3122 this->statements_.insert(this->statements_.begin() + index, s);
3125 // Add a statement after another statement.
3127 void
3128 Block::insert_statement_after(size_t index, Statement* s)
3130 go_assert(index < this->statements_.size());
3131 this->statements_.insert(this->statements_.begin() + index + 1, s);
3134 // Traverse the tree.
3137 Block::traverse(Traverse* traverse)
3139 unsigned int traverse_mask = traverse->traverse_mask();
3141 if ((traverse_mask & Traverse::traverse_blocks) != 0)
3143 int t = traverse->block(this);
3144 if (t == TRAVERSE_EXIT)
3145 return TRAVERSE_EXIT;
3146 else if (t == TRAVERSE_SKIP_COMPONENTS)
3147 return TRAVERSE_CONTINUE;
3150 if ((traverse_mask
3151 & (Traverse::traverse_variables
3152 | Traverse::traverse_constants
3153 | Traverse::traverse_expressions
3154 | Traverse::traverse_types)) != 0)
3156 for (Bindings::const_definitions_iterator pb =
3157 this->bindings_->begin_definitions();
3158 pb != this->bindings_->end_definitions();
3159 ++pb)
3161 switch ((*pb)->classification())
3163 case Named_object::NAMED_OBJECT_CONST:
3164 if ((traverse_mask & Traverse::traverse_constants) != 0)
3166 if (traverse->constant(*pb, false) == TRAVERSE_EXIT)
3167 return TRAVERSE_EXIT;
3169 if ((traverse_mask & Traverse::traverse_types) != 0
3170 || (traverse_mask & Traverse::traverse_expressions) != 0)
3172 Type* t = (*pb)->const_value()->type();
3173 if (t != NULL
3174 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3175 return TRAVERSE_EXIT;
3177 if ((traverse_mask & Traverse::traverse_expressions) != 0
3178 || (traverse_mask & Traverse::traverse_types) != 0)
3180 if ((*pb)->const_value()->traverse_expression(traverse)
3181 == TRAVERSE_EXIT)
3182 return TRAVERSE_EXIT;
3184 break;
3186 case Named_object::NAMED_OBJECT_VAR:
3187 case Named_object::NAMED_OBJECT_RESULT_VAR:
3188 if ((traverse_mask & Traverse::traverse_variables) != 0)
3190 if (traverse->variable(*pb) == TRAVERSE_EXIT)
3191 return TRAVERSE_EXIT;
3193 if (((traverse_mask & Traverse::traverse_types) != 0
3194 || (traverse_mask & Traverse::traverse_expressions) != 0)
3195 && ((*pb)->is_result_variable()
3196 || (*pb)->var_value()->has_type()))
3198 Type* t = ((*pb)->is_variable()
3199 ? (*pb)->var_value()->type()
3200 : (*pb)->result_var_value()->type());
3201 if (t != NULL
3202 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
3203 return TRAVERSE_EXIT;
3205 if ((*pb)->is_variable()
3206 && ((traverse_mask & Traverse::traverse_expressions) != 0
3207 || (traverse_mask & Traverse::traverse_types) != 0))
3209 if ((*pb)->var_value()->traverse_expression(traverse)
3210 == TRAVERSE_EXIT)
3211 return TRAVERSE_EXIT;
3213 break;
3215 case Named_object::NAMED_OBJECT_FUNC:
3216 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3217 // FIXME: Where will nested functions be found?
3218 go_unreachable();
3220 case Named_object::NAMED_OBJECT_TYPE:
3221 if ((traverse_mask & Traverse::traverse_types) != 0
3222 || (traverse_mask & Traverse::traverse_expressions) != 0)
3224 if (Type::traverse((*pb)->type_value(), traverse)
3225 == TRAVERSE_EXIT)
3226 return TRAVERSE_EXIT;
3228 break;
3230 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3231 case Named_object::NAMED_OBJECT_UNKNOWN:
3232 break;
3234 case Named_object::NAMED_OBJECT_PACKAGE:
3235 case Named_object::NAMED_OBJECT_SINK:
3236 go_unreachable();
3238 default:
3239 go_unreachable();
3244 // No point in checking traverse_mask here--if we got here we always
3245 // want to walk the statements. The traversal can insert new
3246 // statements before or after the current statement. Inserting
3247 // statements before the current statement requires updating I via
3248 // the pointer; those statements will not be traversed. Any new
3249 // statements inserted after the current statement will be traversed
3250 // in their turn.
3251 for (size_t i = 0; i < this->statements_.size(); ++i)
3253 if (this->statements_[i]->traverse(this, &i, traverse) == TRAVERSE_EXIT)
3254 return TRAVERSE_EXIT;
3257 return TRAVERSE_CONTINUE;
3260 // Work out types for unspecified variables and constants.
3262 void
3263 Block::determine_types()
3265 for (Bindings::const_definitions_iterator pb =
3266 this->bindings_->begin_definitions();
3267 pb != this->bindings_->end_definitions();
3268 ++pb)
3270 if ((*pb)->is_variable())
3271 (*pb)->var_value()->determine_type();
3272 else if ((*pb)->is_const())
3273 (*pb)->const_value()->determine_type();
3276 for (std::vector<Statement*>::const_iterator ps = this->statements_.begin();
3277 ps != this->statements_.end();
3278 ++ps)
3279 (*ps)->determine_types();
3282 // Return true if the statements in this block may fall through.
3284 bool
3285 Block::may_fall_through() const
3287 if (this->statements_.empty())
3288 return true;
3289 return this->statements_.back()->may_fall_through();
3292 // Convert a block to the backend representation.
3294 Bblock*
3295 Block::get_backend(Translate_context* context)
3297 Gogo* gogo = context->gogo();
3298 Named_object* function = context->function();
3299 std::vector<Bvariable*> vars;
3300 vars.reserve(this->bindings_->size_definitions());
3301 for (Bindings::const_definitions_iterator pv =
3302 this->bindings_->begin_definitions();
3303 pv != this->bindings_->end_definitions();
3304 ++pv)
3306 if ((*pv)->is_variable() && !(*pv)->var_value()->is_parameter())
3307 vars.push_back((*pv)->get_backend_variable(gogo, function));
3310 // FIXME: Permitting FUNCTION to be NULL here is a temporary measure
3311 // until we have a proper representation of the init function.
3312 Bfunction* bfunction;
3313 if (function == NULL)
3314 bfunction = NULL;
3315 else
3316 bfunction = tree_to_function(function->func_value()->get_decl());
3317 Bblock* ret = context->backend()->block(bfunction, context->bblock(),
3318 vars, this->start_location_,
3319 this->end_location_);
3321 Translate_context subcontext(gogo, function, this, ret);
3322 std::vector<Bstatement*> bstatements;
3323 bstatements.reserve(this->statements_.size());
3324 for (std::vector<Statement*>::const_iterator p = this->statements_.begin();
3325 p != this->statements_.end();
3326 ++p)
3327 bstatements.push_back((*p)->get_backend(&subcontext));
3329 context->backend()->block_add_statements(ret, bstatements);
3331 return ret;
3334 // Class Variable.
3336 Variable::Variable(Type* type, Expression* init, bool is_global,
3337 bool is_parameter, bool is_receiver,
3338 source_location location)
3339 : type_(type), init_(init), preinit_(NULL), location_(location),
3340 backend_(NULL), is_global_(is_global), is_parameter_(is_parameter),
3341 is_receiver_(is_receiver), is_varargs_parameter_(false),
3342 is_address_taken_(false), is_non_escaping_address_taken_(false),
3343 seen_(false), init_is_lowered_(false), type_from_init_tuple_(false),
3344 type_from_range_index_(false), type_from_range_value_(false),
3345 type_from_chan_element_(false), is_type_switch_var_(false),
3346 determined_type_(false)
3348 go_assert(type != NULL || init != NULL);
3349 go_assert(!is_parameter || init == NULL);
3352 // Traverse the initializer expression.
3355 Variable::traverse_expression(Traverse* traverse)
3357 if (this->preinit_ != NULL)
3359 if (this->preinit_->traverse(traverse) == TRAVERSE_EXIT)
3360 return TRAVERSE_EXIT;
3362 if (this->init_ != NULL)
3364 if (Expression::traverse(&this->init_, traverse) == TRAVERSE_EXIT)
3365 return TRAVERSE_EXIT;
3367 return TRAVERSE_CONTINUE;
3370 // Lower the initialization expression after parsing is complete.
3372 void
3373 Variable::lower_init_expression(Gogo* gogo, Named_object* function)
3375 if (this->init_ != NULL && !this->init_is_lowered_)
3377 if (this->seen_)
3379 // We will give an error elsewhere, this is just to prevent
3380 // an infinite loop.
3381 return;
3383 this->seen_ = true;
3385 gogo->lower_expression(function, &this->init_);
3387 this->seen_ = false;
3389 this->init_is_lowered_ = true;
3393 // Get the preinit block.
3395 Block*
3396 Variable::preinit_block(Gogo* gogo)
3398 go_assert(this->is_global_);
3399 if (this->preinit_ == NULL)
3400 this->preinit_ = new Block(NULL, this->location());
3402 // If a global variable has a preinitialization statement, then we
3403 // need to have an initialization function.
3404 gogo->set_need_init_fn();
3406 return this->preinit_;
3409 // Add a statement to be run before the initialization expression.
3411 void
3412 Variable::add_preinit_statement(Gogo* gogo, Statement* s)
3414 Block* b = this->preinit_block(gogo);
3415 b->add_statement(s);
3416 b->set_end_location(s->location());
3419 // In an assignment which sets a variable to a tuple of EXPR, return
3420 // the type of the first element of the tuple.
3422 Type*
3423 Variable::type_from_tuple(Expression* expr, bool report_error) const
3425 if (expr->map_index_expression() != NULL)
3427 Map_type* mt = expr->map_index_expression()->get_map_type();
3428 if (mt == NULL)
3429 return Type::make_error_type();
3430 return mt->val_type();
3432 else if (expr->receive_expression() != NULL)
3434 Expression* channel = expr->receive_expression()->channel();
3435 Type* channel_type = channel->type();
3436 if (channel_type->channel_type() == NULL)
3437 return Type::make_error_type();
3438 return channel_type->channel_type()->element_type();
3440 else
3442 if (report_error)
3443 error_at(this->location(), "invalid tuple definition");
3444 return Type::make_error_type();
3448 // Given EXPR used in a range clause, return either the index type or
3449 // the value type of the range, depending upon GET_INDEX_TYPE.
3451 Type*
3452 Variable::type_from_range(Expression* expr, bool get_index_type,
3453 bool report_error) const
3455 Type* t = expr->type();
3456 if (t->array_type() != NULL
3457 || (t->points_to() != NULL
3458 && t->points_to()->array_type() != NULL
3459 && !t->points_to()->is_open_array_type()))
3461 if (get_index_type)
3462 return Type::lookup_integer_type("int");
3463 else
3464 return t->deref()->array_type()->element_type();
3466 else if (t->is_string_type())
3467 return Type::lookup_integer_type("int");
3468 else if (t->map_type() != NULL)
3470 if (get_index_type)
3471 return t->map_type()->key_type();
3472 else
3473 return t->map_type()->val_type();
3475 else if (t->channel_type() != NULL)
3477 if (get_index_type)
3478 return t->channel_type()->element_type();
3479 else
3481 if (report_error)
3482 error_at(this->location(),
3483 "invalid definition of value variable for channel range");
3484 return Type::make_error_type();
3487 else
3489 if (report_error)
3490 error_at(this->location(), "invalid type for range clause");
3491 return Type::make_error_type();
3495 // EXPR should be a channel. Return the channel's element type.
3497 Type*
3498 Variable::type_from_chan_element(Expression* expr, bool report_error) const
3500 Type* t = expr->type();
3501 if (t->channel_type() != NULL)
3502 return t->channel_type()->element_type();
3503 else
3505 if (report_error)
3506 error_at(this->location(), "expected channel");
3507 return Type::make_error_type();
3511 // Return the type of the Variable. This may be called before
3512 // Variable::determine_type is called, which means that we may need to
3513 // get the type from the initializer. FIXME: If we combine lowering
3514 // with type determination, then this should be unnecessary.
3516 Type*
3517 Variable::type()
3519 // A variable in a type switch with a nil case will have the wrong
3520 // type here. This gets fixed up in determine_type, below.
3521 Type* type = this->type_;
3522 Expression* init = this->init_;
3523 if (this->is_type_switch_var_
3524 && this->type_->is_nil_constant_as_type())
3526 Type_guard_expression* tge = this->init_->type_guard_expression();
3527 go_assert(tge != NULL);
3528 init = tge->expr();
3529 type = NULL;
3532 if (this->seen_)
3534 if (this->type_ == NULL || !this->type_->is_error_type())
3536 error_at(this->location_, "variable initializer refers to itself");
3537 this->type_ = Type::make_error_type();
3539 return this->type_;
3542 this->seen_ = true;
3544 if (type != NULL)
3546 else if (this->type_from_init_tuple_)
3547 type = this->type_from_tuple(init, false);
3548 else if (this->type_from_range_index_ || this->type_from_range_value_)
3549 type = this->type_from_range(init, this->type_from_range_index_, false);
3550 else if (this->type_from_chan_element_)
3551 type = this->type_from_chan_element(init, false);
3552 else
3554 go_assert(init != NULL);
3555 type = init->type();
3556 go_assert(type != NULL);
3558 // Variables should not have abstract types.
3559 if (type->is_abstract())
3560 type = type->make_non_abstract_type();
3562 if (type->is_void_type())
3563 type = Type::make_error_type();
3566 this->seen_ = false;
3568 return type;
3571 // Fetch the type from a const pointer, in which case it should have
3572 // been set already.
3574 Type*
3575 Variable::type() const
3577 go_assert(this->type_ != NULL);
3578 return this->type_;
3581 // Set the type if necessary.
3583 void
3584 Variable::determine_type()
3586 if (this->determined_type_)
3587 return;
3588 this->determined_type_ = true;
3590 if (this->preinit_ != NULL)
3591 this->preinit_->determine_types();
3593 // A variable in a type switch with a nil case will have the wrong
3594 // type here. It will have an initializer which is a type guard.
3595 // We want to initialize it to the value without the type guard, and
3596 // use the type of that value as well.
3597 if (this->is_type_switch_var_ && this->type_->is_nil_constant_as_type())
3599 Type_guard_expression* tge = this->init_->type_guard_expression();
3600 go_assert(tge != NULL);
3601 this->type_ = NULL;
3602 this->init_ = tge->expr();
3605 if (this->init_ == NULL)
3606 go_assert(this->type_ != NULL && !this->type_->is_abstract());
3607 else if (this->type_from_init_tuple_)
3609 Expression *init = this->init_;
3610 init->determine_type_no_context();
3611 this->type_ = this->type_from_tuple(init, true);
3612 this->init_ = NULL;
3614 else if (this->type_from_range_index_ || this->type_from_range_value_)
3616 Expression* init = this->init_;
3617 init->determine_type_no_context();
3618 this->type_ = this->type_from_range(init, this->type_from_range_index_,
3619 true);
3620 this->init_ = NULL;
3622 else if (this->type_from_chan_element_)
3624 Expression* init = this->init_;
3625 init->determine_type_no_context();
3626 this->type_ = this->type_from_chan_element(init, true);
3627 this->init_ = NULL;
3629 else
3631 Type_context context(this->type_, false);
3632 this->init_->determine_type(&context);
3633 if (this->type_ == NULL)
3635 Type* type = this->init_->type();
3636 go_assert(type != NULL);
3637 if (type->is_abstract())
3638 type = type->make_non_abstract_type();
3640 if (type->is_void_type())
3642 error_at(this->location_, "variable has no type");
3643 type = Type::make_error_type();
3645 else if (type->is_nil_type())
3647 error_at(this->location_, "variable defined to nil type");
3648 type = Type::make_error_type();
3650 else if (type->is_call_multiple_result_type())
3652 error_at(this->location_,
3653 "single variable set to multiple value function call");
3654 type = Type::make_error_type();
3657 this->type_ = type;
3662 // Export the variable
3664 void
3665 Variable::export_var(Export* exp, const std::string& name) const
3667 go_assert(this->is_global_);
3668 exp->write_c_string("var ");
3669 exp->write_string(name);
3670 exp->write_c_string(" ");
3671 exp->write_type(this->type());
3672 exp->write_c_string(";\n");
3675 // Import a variable.
3677 void
3678 Variable::import_var(Import* imp, std::string* pname, Type** ptype)
3680 imp->require_c_string("var ");
3681 *pname = imp->read_identifier();
3682 imp->require_c_string(" ");
3683 *ptype = imp->read_type();
3684 imp->require_c_string(";\n");
3687 // Convert a variable to the backend representation.
3689 Bvariable*
3690 Variable::get_backend_variable(Gogo* gogo, Named_object* function,
3691 const Package* package, const std::string& name)
3693 if (this->backend_ == NULL)
3695 Backend* backend = gogo->backend();
3696 Type* type = this->type_;
3697 if (type->is_error_type()
3698 || (type->is_undefined()
3699 && (!this->is_global_ || package == NULL)))
3700 this->backend_ = backend->error_variable();
3701 else
3703 bool is_parameter = this->is_parameter_;
3704 if (this->is_receiver_ && type->points_to() == NULL)
3705 is_parameter = false;
3706 if (this->is_in_heap())
3708 is_parameter = false;
3709 type = Type::make_pointer_type(type);
3712 std::string n = Gogo::unpack_hidden_name(name);
3713 Btype* btype = type->get_backend(gogo);
3715 Bvariable* bvar;
3716 if (this->is_global_)
3717 bvar = backend->global_variable((package == NULL
3718 ? gogo->package_name()
3719 : package->name()),
3720 (package == NULL
3721 ? gogo->unique_prefix()
3722 : package->unique_prefix()),
3724 btype,
3725 package != NULL,
3726 Gogo::is_hidden_name(name),
3727 this->location_);
3728 else
3730 tree fndecl = function->func_value()->get_decl();
3731 Bfunction* bfunction = tree_to_function(fndecl);
3732 bool is_address_taken = (this->is_non_escaping_address_taken_
3733 && !this->is_in_heap());
3734 if (is_parameter)
3735 bvar = backend->parameter_variable(bfunction, n, btype,
3736 is_address_taken,
3737 this->location_);
3738 else
3739 bvar = backend->local_variable(bfunction, n, btype,
3740 is_address_taken,
3741 this->location_);
3743 this->backend_ = bvar;
3746 return this->backend_;
3749 // Class Result_variable.
3751 // Convert a result variable to the backend representation.
3753 Bvariable*
3754 Result_variable::get_backend_variable(Gogo* gogo, Named_object* function,
3755 const std::string& name)
3757 if (this->backend_ == NULL)
3759 Backend* backend = gogo->backend();
3760 Type* type = this->type_;
3761 if (type->is_error())
3762 this->backend_ = backend->error_variable();
3763 else
3765 if (this->is_in_heap())
3766 type = Type::make_pointer_type(type);
3767 Btype* btype = type->get_backend(gogo);
3768 tree fndecl = function->func_value()->get_decl();
3769 Bfunction* bfunction = tree_to_function(fndecl);
3770 std::string n = Gogo::unpack_hidden_name(name);
3771 bool is_address_taken = (this->is_non_escaping_address_taken_
3772 && !this->is_in_heap());
3773 this->backend_ = backend->local_variable(bfunction, n, btype,
3774 is_address_taken,
3775 this->location_);
3778 return this->backend_;
3781 // Class Named_constant.
3783 // Traverse the initializer expression.
3786 Named_constant::traverse_expression(Traverse* traverse)
3788 return Expression::traverse(&this->expr_, traverse);
3791 // Determine the type of the constant.
3793 void
3794 Named_constant::determine_type()
3796 if (this->type_ != NULL)
3798 Type_context context(this->type_, false);
3799 this->expr_->determine_type(&context);
3801 else
3803 // A constant may have an abstract type.
3804 Type_context context(NULL, true);
3805 this->expr_->determine_type(&context);
3806 this->type_ = this->expr_->type();
3807 go_assert(this->type_ != NULL);
3811 // Indicate that we found and reported an error for this constant.
3813 void
3814 Named_constant::set_error()
3816 this->type_ = Type::make_error_type();
3817 this->expr_ = Expression::make_error(this->location_);
3820 // Export a constant.
3822 void
3823 Named_constant::export_const(Export* exp, const std::string& name) const
3825 exp->write_c_string("const ");
3826 exp->write_string(name);
3827 exp->write_c_string(" ");
3828 if (!this->type_->is_abstract())
3830 exp->write_type(this->type_);
3831 exp->write_c_string(" ");
3833 exp->write_c_string("= ");
3834 this->expr()->export_expression(exp);
3835 exp->write_c_string(";\n");
3838 // Import a constant.
3840 void
3841 Named_constant::import_const(Import* imp, std::string* pname, Type** ptype,
3842 Expression** pexpr)
3844 imp->require_c_string("const ");
3845 *pname = imp->read_identifier();
3846 imp->require_c_string(" ");
3847 if (imp->peek_char() == '=')
3848 *ptype = NULL;
3849 else
3851 *ptype = imp->read_type();
3852 imp->require_c_string(" ");
3854 imp->require_c_string("= ");
3855 *pexpr = Expression::import_expression(imp);
3856 imp->require_c_string(";\n");
3859 // Add a method.
3861 Named_object*
3862 Type_declaration::add_method(const std::string& name, Function* function)
3864 Named_object* ret = Named_object::make_function(name, NULL, function);
3865 this->methods_.push_back(ret);
3866 return ret;
3869 // Add a method declaration.
3871 Named_object*
3872 Type_declaration::add_method_declaration(const std::string& name,
3873 Function_type* type,
3874 source_location location)
3876 Named_object* ret = Named_object::make_function_declaration(name, NULL, type,
3877 location);
3878 this->methods_.push_back(ret);
3879 return ret;
3882 // Return whether any methods ere defined.
3884 bool
3885 Type_declaration::has_methods() const
3887 return !this->methods_.empty();
3890 // Define methods for the real type.
3892 void
3893 Type_declaration::define_methods(Named_type* nt)
3895 for (Methods::const_iterator p = this->methods_.begin();
3896 p != this->methods_.end();
3897 ++p)
3898 nt->add_existing_method(*p);
3901 // We are using the type. Return true if we should issue a warning.
3903 bool
3904 Type_declaration::using_type()
3906 bool ret = !this->issued_warning_;
3907 this->issued_warning_ = true;
3908 return ret;
3911 // Class Unknown_name.
3913 // Set the real named object.
3915 void
3916 Unknown_name::set_real_named_object(Named_object* no)
3918 go_assert(this->real_named_object_ == NULL);
3919 go_assert(!no->is_unknown());
3920 this->real_named_object_ = no;
3923 // Class Named_object.
3925 Named_object::Named_object(const std::string& name,
3926 const Package* package,
3927 Classification classification)
3928 : name_(name), package_(package), classification_(classification),
3929 tree_(NULL)
3931 if (Gogo::is_sink_name(name))
3932 go_assert(classification == NAMED_OBJECT_SINK);
3935 // Make an unknown name. This is used by the parser. The name must
3936 // be resolved later. Unknown names are only added in the current
3937 // package.
3939 Named_object*
3940 Named_object::make_unknown_name(const std::string& name,
3941 source_location location)
3943 Named_object* named_object = new Named_object(name, NULL,
3944 NAMED_OBJECT_UNKNOWN);
3945 Unknown_name* value = new Unknown_name(location);
3946 named_object->u_.unknown_value = value;
3947 return named_object;
3950 // Make a constant.
3952 Named_object*
3953 Named_object::make_constant(const Typed_identifier& tid,
3954 const Package* package, Expression* expr,
3955 int iota_value)
3957 Named_object* named_object = new Named_object(tid.name(), package,
3958 NAMED_OBJECT_CONST);
3959 Named_constant* named_constant = new Named_constant(tid.type(), expr,
3960 iota_value,
3961 tid.location());
3962 named_object->u_.const_value = named_constant;
3963 return named_object;
3966 // Make a named type.
3968 Named_object*
3969 Named_object::make_type(const std::string& name, const Package* package,
3970 Type* type, source_location location)
3972 Named_object* named_object = new Named_object(name, package,
3973 NAMED_OBJECT_TYPE);
3974 Named_type* named_type = Type::make_named_type(named_object, type, location);
3975 named_object->u_.type_value = named_type;
3976 return named_object;
3979 // Make a type declaration.
3981 Named_object*
3982 Named_object::make_type_declaration(const std::string& name,
3983 const Package* package,
3984 source_location location)
3986 Named_object* named_object = new Named_object(name, package,
3987 NAMED_OBJECT_TYPE_DECLARATION);
3988 Type_declaration* type_declaration = new Type_declaration(location);
3989 named_object->u_.type_declaration = type_declaration;
3990 return named_object;
3993 // Make a variable.
3995 Named_object*
3996 Named_object::make_variable(const std::string& name, const Package* package,
3997 Variable* variable)
3999 Named_object* named_object = new Named_object(name, package,
4000 NAMED_OBJECT_VAR);
4001 named_object->u_.var_value = variable;
4002 return named_object;
4005 // Make a result variable.
4007 Named_object*
4008 Named_object::make_result_variable(const std::string& name,
4009 Result_variable* result)
4011 Named_object* named_object = new Named_object(name, NULL,
4012 NAMED_OBJECT_RESULT_VAR);
4013 named_object->u_.result_var_value = result;
4014 return named_object;
4017 // Make a sink. This is used for the special blank identifier _.
4019 Named_object*
4020 Named_object::make_sink()
4022 return new Named_object("_", NULL, NAMED_OBJECT_SINK);
4025 // Make a named function.
4027 Named_object*
4028 Named_object::make_function(const std::string& name, const Package* package,
4029 Function* function)
4031 Named_object* named_object = new Named_object(name, package,
4032 NAMED_OBJECT_FUNC);
4033 named_object->u_.func_value = function;
4034 return named_object;
4037 // Make a function declaration.
4039 Named_object*
4040 Named_object::make_function_declaration(const std::string& name,
4041 const Package* package,
4042 Function_type* fntype,
4043 source_location location)
4045 Named_object* named_object = new Named_object(name, package,
4046 NAMED_OBJECT_FUNC_DECLARATION);
4047 Function_declaration *func_decl = new Function_declaration(fntype, location);
4048 named_object->u_.func_declaration_value = func_decl;
4049 return named_object;
4052 // Make a package.
4054 Named_object*
4055 Named_object::make_package(const std::string& alias, Package* package)
4057 Named_object* named_object = new Named_object(alias, NULL,
4058 NAMED_OBJECT_PACKAGE);
4059 named_object->u_.package_value = package;
4060 return named_object;
4063 // Return the name to use in an error message.
4065 std::string
4066 Named_object::message_name() const
4068 if (this->package_ == NULL)
4069 return Gogo::message_name(this->name_);
4070 std::string ret = Gogo::message_name(this->package_->name());
4071 ret += '.';
4072 ret += Gogo::message_name(this->name_);
4073 return ret;
4076 // Set the type when a declaration is defined.
4078 void
4079 Named_object::set_type_value(Named_type* named_type)
4081 go_assert(this->classification_ == NAMED_OBJECT_TYPE_DECLARATION);
4082 Type_declaration* td = this->u_.type_declaration;
4083 td->define_methods(named_type);
4084 Named_object* in_function = td->in_function();
4085 if (in_function != NULL)
4086 named_type->set_in_function(in_function);
4087 delete td;
4088 this->classification_ = NAMED_OBJECT_TYPE;
4089 this->u_.type_value = named_type;
4092 // Define a function which was previously declared.
4094 void
4095 Named_object::set_function_value(Function* function)
4097 go_assert(this->classification_ == NAMED_OBJECT_FUNC_DECLARATION);
4098 this->classification_ = NAMED_OBJECT_FUNC;
4099 // FIXME: We should free the old value.
4100 this->u_.func_value = function;
4103 // Declare an unknown object as a type declaration.
4105 void
4106 Named_object::declare_as_type()
4108 go_assert(this->classification_ == NAMED_OBJECT_UNKNOWN);
4109 Unknown_name* unk = this->u_.unknown_value;
4110 this->classification_ = NAMED_OBJECT_TYPE_DECLARATION;
4111 this->u_.type_declaration = new Type_declaration(unk->location());
4112 delete unk;
4115 // Return the location of a named object.
4117 source_location
4118 Named_object::location() const
4120 switch (this->classification_)
4122 default:
4123 case NAMED_OBJECT_UNINITIALIZED:
4124 go_unreachable();
4126 case NAMED_OBJECT_UNKNOWN:
4127 return this->unknown_value()->location();
4129 case NAMED_OBJECT_CONST:
4130 return this->const_value()->location();
4132 case NAMED_OBJECT_TYPE:
4133 return this->type_value()->location();
4135 case NAMED_OBJECT_TYPE_DECLARATION:
4136 return this->type_declaration_value()->location();
4138 case NAMED_OBJECT_VAR:
4139 return this->var_value()->location();
4141 case NAMED_OBJECT_RESULT_VAR:
4142 return this->result_var_value()->location();
4144 case NAMED_OBJECT_SINK:
4145 go_unreachable();
4147 case NAMED_OBJECT_FUNC:
4148 return this->func_value()->location();
4150 case NAMED_OBJECT_FUNC_DECLARATION:
4151 return this->func_declaration_value()->location();
4153 case NAMED_OBJECT_PACKAGE:
4154 return this->package_value()->location();
4158 // Export a named object.
4160 void
4161 Named_object::export_named_object(Export* exp) const
4163 switch (this->classification_)
4165 default:
4166 case NAMED_OBJECT_UNINITIALIZED:
4167 case NAMED_OBJECT_UNKNOWN:
4168 go_unreachable();
4170 case NAMED_OBJECT_CONST:
4171 this->const_value()->export_const(exp, this->name_);
4172 break;
4174 case NAMED_OBJECT_TYPE:
4175 this->type_value()->export_named_type(exp, this->name_);
4176 break;
4178 case NAMED_OBJECT_TYPE_DECLARATION:
4179 error_at(this->type_declaration_value()->location(),
4180 "attempt to export %<%s%> which was declared but not defined",
4181 this->message_name().c_str());
4182 break;
4184 case NAMED_OBJECT_FUNC_DECLARATION:
4185 this->func_declaration_value()->export_func(exp, this->name_);
4186 break;
4188 case NAMED_OBJECT_VAR:
4189 this->var_value()->export_var(exp, this->name_);
4190 break;
4192 case NAMED_OBJECT_RESULT_VAR:
4193 case NAMED_OBJECT_SINK:
4194 go_unreachable();
4196 case NAMED_OBJECT_FUNC:
4197 this->func_value()->export_func(exp, this->name_);
4198 break;
4202 // Convert a variable to the backend representation.
4204 Bvariable*
4205 Named_object::get_backend_variable(Gogo* gogo, Named_object* function)
4207 if (this->classification_ == NAMED_OBJECT_VAR)
4208 return this->var_value()->get_backend_variable(gogo, function,
4209 this->package_, this->name_);
4210 else if (this->classification_ == NAMED_OBJECT_RESULT_VAR)
4211 return this->result_var_value()->get_backend_variable(gogo, function,
4212 this->name_);
4213 else
4214 go_unreachable();
4217 // Class Bindings.
4219 Bindings::Bindings(Bindings* enclosing)
4220 : enclosing_(enclosing), named_objects_(), bindings_()
4224 // Clear imports.
4226 void
4227 Bindings::clear_file_scope()
4229 Contour::iterator p = this->bindings_.begin();
4230 while (p != this->bindings_.end())
4232 bool keep;
4233 if (p->second->package() != NULL)
4234 keep = false;
4235 else if (p->second->is_package())
4236 keep = false;
4237 else if (p->second->is_function()
4238 && !p->second->func_value()->type()->is_method()
4239 && Gogo::unpack_hidden_name(p->second->name()) == "init")
4240 keep = false;
4241 else
4242 keep = true;
4244 if (keep)
4245 ++p;
4246 else
4247 p = this->bindings_.erase(p);
4251 // Look up a symbol.
4253 Named_object*
4254 Bindings::lookup(const std::string& name) const
4256 Contour::const_iterator p = this->bindings_.find(name);
4257 if (p != this->bindings_.end())
4258 return p->second->resolve();
4259 else if (this->enclosing_ != NULL)
4260 return this->enclosing_->lookup(name);
4261 else
4262 return NULL;
4265 // Look up a symbol locally.
4267 Named_object*
4268 Bindings::lookup_local(const std::string& name) const
4270 Contour::const_iterator p = this->bindings_.find(name);
4271 if (p == this->bindings_.end())
4272 return NULL;
4273 return p->second;
4276 // Remove an object from a set of bindings. This is used for a
4277 // special case in thunks for functions which call recover.
4279 void
4280 Bindings::remove_binding(Named_object* no)
4282 Contour::iterator pb = this->bindings_.find(no->name());
4283 go_assert(pb != this->bindings_.end());
4284 this->bindings_.erase(pb);
4285 for (std::vector<Named_object*>::iterator pn = this->named_objects_.begin();
4286 pn != this->named_objects_.end();
4287 ++pn)
4289 if (*pn == no)
4291 this->named_objects_.erase(pn);
4292 return;
4295 go_unreachable();
4298 // Add a method to the list of objects. This is not added to the
4299 // lookup table. This is so that we have a single list of objects
4300 // declared at the top level, which we walk through when it's time to
4301 // convert to trees.
4303 void
4304 Bindings::add_method(Named_object* method)
4306 this->named_objects_.push_back(method);
4309 // Add a generic Named_object to a Contour.
4311 Named_object*
4312 Bindings::add_named_object_to_contour(Contour* contour,
4313 Named_object* named_object)
4315 go_assert(named_object == named_object->resolve());
4316 const std::string& name(named_object->name());
4317 go_assert(!Gogo::is_sink_name(name));
4319 std::pair<Contour::iterator, bool> ins =
4320 contour->insert(std::make_pair(name, named_object));
4321 if (!ins.second)
4323 // The name was already there.
4324 if (named_object->package() != NULL
4325 && ins.first->second->package() == named_object->package()
4326 && (ins.first->second->classification()
4327 == named_object->classification()))
4329 // This is a second import of the same object.
4330 return ins.first->second;
4332 ins.first->second = this->new_definition(ins.first->second,
4333 named_object);
4334 return ins.first->second;
4336 else
4338 // Don't push declarations on the list. We push them on when
4339 // and if we find the definitions. That way we genericize the
4340 // functions in order.
4341 if (!named_object->is_type_declaration()
4342 && !named_object->is_function_declaration()
4343 && !named_object->is_unknown())
4344 this->named_objects_.push_back(named_object);
4345 return named_object;
4349 // We had an existing named object OLD_OBJECT, and we've seen a new
4350 // one NEW_OBJECT with the same name. FIXME: This does not free the
4351 // new object when we don't need it.
4353 Named_object*
4354 Bindings::new_definition(Named_object* old_object, Named_object* new_object)
4356 std::string reason;
4357 switch (old_object->classification())
4359 default:
4360 case Named_object::NAMED_OBJECT_UNINITIALIZED:
4361 go_unreachable();
4363 case Named_object::NAMED_OBJECT_UNKNOWN:
4365 Named_object* real = old_object->unknown_value()->real_named_object();
4366 if (real != NULL)
4367 return this->new_definition(real, new_object);
4368 go_assert(!new_object->is_unknown());
4369 old_object->unknown_value()->set_real_named_object(new_object);
4370 if (!new_object->is_type_declaration()
4371 && !new_object->is_function_declaration())
4372 this->named_objects_.push_back(new_object);
4373 return new_object;
4376 case Named_object::NAMED_OBJECT_CONST:
4377 break;
4379 case Named_object::NAMED_OBJECT_TYPE:
4380 if (new_object->is_type_declaration())
4381 return old_object;
4382 break;
4384 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4385 if (new_object->is_type_declaration())
4386 return old_object;
4387 if (new_object->is_type())
4389 old_object->set_type_value(new_object->type_value());
4390 new_object->type_value()->set_named_object(old_object);
4391 this->named_objects_.push_back(old_object);
4392 return old_object;
4394 break;
4396 case Named_object::NAMED_OBJECT_VAR:
4397 case Named_object::NAMED_OBJECT_RESULT_VAR:
4398 break;
4400 case Named_object::NAMED_OBJECT_SINK:
4401 go_unreachable();
4403 case Named_object::NAMED_OBJECT_FUNC:
4404 if (new_object->is_function_declaration())
4406 if (!new_object->func_declaration_value()->asm_name().empty())
4407 sorry("__asm__ for function definitions");
4408 Function_type* old_type = old_object->func_value()->type();
4409 Function_type* new_type =
4410 new_object->func_declaration_value()->type();
4411 if (old_type->is_valid_redeclaration(new_type, &reason))
4412 return old_object;
4414 break;
4416 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4418 Function_type* old_type = old_object->func_declaration_value()->type();
4419 if (new_object->is_function_declaration())
4421 Function_type* new_type =
4422 new_object->func_declaration_value()->type();
4423 if (old_type->is_valid_redeclaration(new_type, &reason))
4424 return old_object;
4426 if (new_object->is_function())
4428 Function_type* new_type = new_object->func_value()->type();
4429 if (old_type->is_valid_redeclaration(new_type, &reason))
4431 if (!old_object->func_declaration_value()->asm_name().empty())
4432 sorry("__asm__ for function definitions");
4433 old_object->set_function_value(new_object->func_value());
4434 this->named_objects_.push_back(old_object);
4435 return old_object;
4439 break;
4441 case Named_object::NAMED_OBJECT_PACKAGE:
4442 if (new_object->is_package()
4443 && (old_object->package_value()->name()
4444 == new_object->package_value()->name()))
4445 return old_object;
4447 break;
4450 std::string n = old_object->message_name();
4451 if (reason.empty())
4452 error_at(new_object->location(), "redefinition of %qs", n.c_str());
4453 else
4454 error_at(new_object->location(), "redefinition of %qs: %s", n.c_str(),
4455 reason.c_str());
4457 inform(old_object->location(), "previous definition of %qs was here",
4458 n.c_str());
4460 return old_object;
4463 // Add a named type.
4465 Named_object*
4466 Bindings::add_named_type(Named_type* named_type)
4468 return this->add_named_object(named_type->named_object());
4471 // Add a function.
4473 Named_object*
4474 Bindings::add_function(const std::string& name, const Package* package,
4475 Function* function)
4477 return this->add_named_object(Named_object::make_function(name, package,
4478 function));
4481 // Add a function declaration.
4483 Named_object*
4484 Bindings::add_function_declaration(const std::string& name,
4485 const Package* package,
4486 Function_type* type,
4487 source_location location)
4489 Named_object* no = Named_object::make_function_declaration(name, package,
4490 type, location);
4491 return this->add_named_object(no);
4494 // Define a type which was previously declared.
4496 void
4497 Bindings::define_type(Named_object* no, Named_type* type)
4499 no->set_type_value(type);
4500 this->named_objects_.push_back(no);
4503 // Traverse bindings.
4506 Bindings::traverse(Traverse* traverse, bool is_global)
4508 unsigned int traverse_mask = traverse->traverse_mask();
4510 // We don't use an iterator because we permit the traversal to add
4511 // new global objects.
4512 for (size_t i = 0; i < this->named_objects_.size(); ++i)
4514 Named_object* p = this->named_objects_[i];
4515 switch (p->classification())
4517 case Named_object::NAMED_OBJECT_CONST:
4518 if ((traverse_mask & Traverse::traverse_constants) != 0)
4520 if (traverse->constant(p, is_global) == TRAVERSE_EXIT)
4521 return TRAVERSE_EXIT;
4523 if ((traverse_mask & Traverse::traverse_types) != 0
4524 || (traverse_mask & Traverse::traverse_expressions) != 0)
4526 Type* t = p->const_value()->type();
4527 if (t != NULL
4528 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4529 return TRAVERSE_EXIT;
4530 if (p->const_value()->traverse_expression(traverse)
4531 == TRAVERSE_EXIT)
4532 return TRAVERSE_EXIT;
4534 break;
4536 case Named_object::NAMED_OBJECT_VAR:
4537 case Named_object::NAMED_OBJECT_RESULT_VAR:
4538 if ((traverse_mask & Traverse::traverse_variables) != 0)
4540 if (traverse->variable(p) == TRAVERSE_EXIT)
4541 return TRAVERSE_EXIT;
4543 if (((traverse_mask & Traverse::traverse_types) != 0
4544 || (traverse_mask & Traverse::traverse_expressions) != 0)
4545 && (p->is_result_variable()
4546 || p->var_value()->has_type()))
4548 Type* t = (p->is_variable()
4549 ? p->var_value()->type()
4550 : p->result_var_value()->type());
4551 if (t != NULL
4552 && Type::traverse(t, traverse) == TRAVERSE_EXIT)
4553 return TRAVERSE_EXIT;
4555 if (p->is_variable()
4556 && ((traverse_mask & Traverse::traverse_types) != 0
4557 || (traverse_mask & Traverse::traverse_expressions) != 0))
4559 if (p->var_value()->traverse_expression(traverse)
4560 == TRAVERSE_EXIT)
4561 return TRAVERSE_EXIT;
4563 break;
4565 case Named_object::NAMED_OBJECT_FUNC:
4566 if ((traverse_mask & Traverse::traverse_functions) != 0)
4568 int t = traverse->function(p);
4569 if (t == TRAVERSE_EXIT)
4570 return TRAVERSE_EXIT;
4571 else if (t == TRAVERSE_SKIP_COMPONENTS)
4572 break;
4575 if ((traverse_mask
4576 & (Traverse::traverse_variables
4577 | Traverse::traverse_constants
4578 | Traverse::traverse_functions
4579 | Traverse::traverse_blocks
4580 | Traverse::traverse_statements
4581 | Traverse::traverse_expressions
4582 | Traverse::traverse_types)) != 0)
4584 if (p->func_value()->traverse(traverse) == TRAVERSE_EXIT)
4585 return TRAVERSE_EXIT;
4587 break;
4589 case Named_object::NAMED_OBJECT_PACKAGE:
4590 // These are traversed in Gogo::traverse.
4591 go_assert(is_global);
4592 break;
4594 case Named_object::NAMED_OBJECT_TYPE:
4595 if ((traverse_mask & Traverse::traverse_types) != 0
4596 || (traverse_mask & Traverse::traverse_expressions) != 0)
4598 if (Type::traverse(p->type_value(), traverse) == TRAVERSE_EXIT)
4599 return TRAVERSE_EXIT;
4601 break;
4603 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
4604 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
4605 case Named_object::NAMED_OBJECT_UNKNOWN:
4606 break;
4608 case Named_object::NAMED_OBJECT_SINK:
4609 default:
4610 go_unreachable();
4614 return TRAVERSE_CONTINUE;
4617 // Class Label.
4619 // Get the backend representation for a label.
4621 Blabel*
4622 Label::get_backend_label(Translate_context* context)
4624 if (this->blabel_ == NULL)
4626 Function* function = context->function()->func_value();
4627 tree fndecl = function->get_decl();
4628 Bfunction* bfunction = tree_to_function(fndecl);
4629 this->blabel_ = context->backend()->label(bfunction, this->name_,
4630 this->location_);
4632 return this->blabel_;
4635 // Return an expression for the address of this label.
4637 Bexpression*
4638 Label::get_addr(Translate_context* context, source_location location)
4640 Blabel* label = this->get_backend_label(context);
4641 return context->backend()->label_address(label, location);
4644 // Class Unnamed_label.
4646 // Get the backend representation for an unnamed label.
4648 Blabel*
4649 Unnamed_label::get_blabel(Translate_context* context)
4651 if (this->blabel_ == NULL)
4653 Function* function = context->function()->func_value();
4654 tree fndecl = function->get_decl();
4655 Bfunction* bfunction = tree_to_function(fndecl);
4656 this->blabel_ = context->backend()->label(bfunction, "",
4657 this->location_);
4659 return this->blabel_;
4662 // Return a statement which defines this unnamed label.
4664 Bstatement*
4665 Unnamed_label::get_definition(Translate_context* context)
4667 Blabel* blabel = this->get_blabel(context);
4668 return context->backend()->label_definition_statement(blabel);
4671 // Return a goto statement to this unnamed label.
4673 Bstatement*
4674 Unnamed_label::get_goto(Translate_context* context, source_location location)
4676 Blabel* blabel = this->get_blabel(context);
4677 return context->backend()->goto_statement(blabel, location);
4680 // Class Package.
4682 Package::Package(const std::string& name, const std::string& unique_prefix,
4683 source_location location)
4684 : name_(name), unique_prefix_(unique_prefix), bindings_(new Bindings(NULL)),
4685 priority_(0), location_(location), used_(false), is_imported_(false),
4686 uses_sink_alias_(false)
4688 go_assert(!name.empty() && !unique_prefix.empty());
4691 // Set the priority. We may see multiple priorities for an imported
4692 // package; we want to use the largest one.
4694 void
4695 Package::set_priority(int priority)
4697 if (priority > this->priority_)
4698 this->priority_ = priority;
4701 // Determine types of constants. Everything else in a package
4702 // (variables, function declarations) should already have a fixed
4703 // type. Constants may have abstract types.
4705 void
4706 Package::determine_types()
4708 Bindings* bindings = this->bindings_;
4709 for (Bindings::const_definitions_iterator p = bindings->begin_definitions();
4710 p != bindings->end_definitions();
4711 ++p)
4713 if ((*p)->is_const())
4714 (*p)->const_value()->determine_type();
4718 // Class Traverse.
4720 // Destructor.
4722 Traverse::~Traverse()
4724 if (this->types_seen_ != NULL)
4725 delete this->types_seen_;
4726 if (this->expressions_seen_ != NULL)
4727 delete this->expressions_seen_;
4730 // Record that we are looking at a type, and return true if we have
4731 // already seen it.
4733 bool
4734 Traverse::remember_type(const Type* type)
4736 if (type->is_error_type())
4737 return true;
4738 go_assert((this->traverse_mask() & traverse_types) != 0
4739 || (this->traverse_mask() & traverse_expressions) != 0);
4740 // We only have to remember named types, as they are the only ones
4741 // we can see multiple times in a traversal.
4742 if (type->classification() != Type::TYPE_NAMED)
4743 return false;
4744 if (this->types_seen_ == NULL)
4745 this->types_seen_ = new Types_seen();
4746 std::pair<Types_seen::iterator, bool> ins = this->types_seen_->insert(type);
4747 return !ins.second;
4750 // Record that we are looking at an expression, and return true if we
4751 // have already seen it.
4753 bool
4754 Traverse::remember_expression(const Expression* expression)
4756 go_assert((this->traverse_mask() & traverse_types) != 0
4757 || (this->traverse_mask() & traverse_expressions) != 0);
4758 if (this->expressions_seen_ == NULL)
4759 this->expressions_seen_ = new Expressions_seen();
4760 std::pair<Expressions_seen::iterator, bool> ins =
4761 this->expressions_seen_->insert(expression);
4762 return !ins.second;
4765 // The default versions of these functions should never be called: the
4766 // traversal mask indicates which functions may be called.
4769 Traverse::variable(Named_object*)
4771 go_unreachable();
4775 Traverse::constant(Named_object*, bool)
4777 go_unreachable();
4781 Traverse::function(Named_object*)
4783 go_unreachable();
4787 Traverse::block(Block*)
4789 go_unreachable();
4793 Traverse::statement(Block*, size_t*, Statement*)
4795 go_unreachable();
4799 Traverse::expression(Expression**)
4801 go_unreachable();
4805 Traverse::type(Type*)
4807 go_unreachable();